Add a lot

This commit is contained in:
Mathieu Sanchez 2018-11-27 13:59:21 +09:00
parent d9e043c468
commit 561bfbf475
37 changed files with 8589 additions and 7952 deletions

View File

@ -10,12 +10,15 @@ RewriteRule ^ - [L]
# RewriteCond %{HTTP_HOST} ^eldotravo.fr$ # RewriteCond %{HTTP_HOST} ^eldotravo.fr$
# RewriteRule ^(.*)$ http://www.eldotravo.fr/$1 [R=301,L,E=END:1] # RewriteRule ^(.*)$ http://www.eldotravo.fr/$1 [R=301,L,E=END:1]
# Redirection des fichiers static pour contact.sanchez-mathieu.dev # Redirection des fichiers static pour contact.sanchez-mathieu.test
RewriteCond %{HTTP_HOST} ^contact.sanchez-mathieu.dev$ RewriteCond %{HTTP_HOST} ^contact.sanchez-mathieu.test
RewriteCond %{DOCUMENT_ROOT}/static%{REQUEST_URI} -f RewriteCond %{DOCUMENT_ROOT}/static%{REQUEST_URI} -f
RewriteRule ^(.*)$ static/$1 [L,E=END:1] RewriteRule ^(.*)$ static/$1 [L,E=END:1]
# RewriteRule ^haute-garonne/toulouse/installation-entretien-climatisation /haute-garonne/toulouse/climatisation.php [L] # Redirection des fichiers static pour contact.sanchez-mathieu.fr
RewriteCond %{HTTP_HOST} ^contact.sanchez-mathieu.fr
RewriteCond %{DOCUMENT_ROOT}/static%{REQUEST_URI} -f
RewriteRule ^(.*)$ static/$1 [L,E=END:1]
# Redirection de toutes les requêtes vers Index.php # Redirection de toutes les requêtes vers Index.php
RewriteRule ^ index.php [L,E=END:1] RewriteRule ^ index.php [L,E=END:1]

View File

@ -35,7 +35,7 @@ if ( count( $pages ) > 1 && $pages[ count( $pages ) - 1 ] == '' ) {
if ( $pages[0] == 'api' && isset( $pages[1] ) && preg_match( '#^([a-z]+)$#', $pages[1], $api1 ) && isset( $pages[2] ) && preg_match( '#^([a-z-]+)$#', $pages[2], $api2 ) ) { if ( $pages[0] == 'api' && isset( $pages[1] ) && preg_match( '#^([a-z]+)$#', $pages[1], $api1 ) && isset( $pages[2] ) && preg_match( '#^([a-z-]+)$#', $pages[2], $api2 ) ) {
new APIRouter( $api1[0], $api2[0] ); new APIRouter( $api1[0], $api2[0] );
} else if ( preg_match( '#^test\.dev$#', $_SERVER['SERVER_NAME'] ) ) { } else if ( preg_match( '#^contact.sanchez-mathieu\.test$#', $_SERVER[ 'SERVER_NAME' ] ) || preg_match( '#^contact.sanchez-mathieu\.fr#', $_SERVER[ 'SERVER_NAME' ] ) ) {
new SiteRouter( $pages ); new SiteRouter( $pages );
} else { } else {
new Error( 404 ); new Error( 404 );

View File

@ -6,24 +6,24 @@ use CAUProject3Contact\Controller\Controller;
class API extends Controller { class API extends Controller {
private $declaredFunctions = []; private $declaredFunctions = [];
/** /**
* API constructor. * API constructor.
* *
* @param array $declaredFunctions * @param array $declaredFunctions
*/ */
public function __construct( array $declaredFunctions ) { public function __construct( array $declaredFunctions ) {
parent::__construct(); parent::__construct();
$this->declaredFunctions = $declaredFunctions; $this->declaredFunctions = $declaredFunctions;
} }
/** /**
* @return array * @return array
*/ */
public function getDeclaredFunctions() { public function getDeclaredFunctions() {
return $this->declaredFunctions; return $this->declaredFunctions;
} }
} }
?> ?>

201
src/API/APIContact.php Normal file
View File

@ -0,0 +1,201 @@
<?php
namespace CAUProject3Contact\API;
use CAUProject3Contact\Model\Contact;
class APIContact extends API {
private $declaredFunctions = [
'insert' => [
'method' => 'POST',
'params' => [
'firstName' => [
'required' => true,
'type' => 'string'
],
'lastName' => [
'required' => true,
'type' => 'string'
],
'surname' => [
'required' => false,
'type' => 'string'
],
'email' => [
'required' => false,
'type' => 'string'
],
'address' => [
'required' => false,
'type' => 'string'
],
'phoneNumber' => [
'required' => false,
'type' => 'string'
],
'birthday' => [
'required' => false,
'type' => 'string'
],
]
],
'delete' => [
'method' => 'POST',
'params' => [
'id' => [
'required' => true,
'type' => 'int'
]
]
],
'get-contacts' => [
'method' => 'GET',
'params' => []
],
'update' => [
'method' => 'POST',
'params' => [
'id' => [
'required' => true,
'type' => 'int'
],
'firstName' => [
'required' => false,
'type' => 'string'
],
'lastName' => [
'required' => false,
'type' => 'string'
],
'surname' => [
'required' => false,
'type' => 'string'
],
'email' => [
'required' => false,
'type' => 'string'
],
'address' => [
'required' => false,
'type' => 'string'
],
'phoneNumber' => [
'required' => false,
'type' => 'string'
],
'birthday' => [
'required' => false,
'type' => 'string'
]
]
],
'search' => [
'method' => 'POST',
'params' => [
'query' => [
'required' => true,
'type' => 'string'
]
]
]
];
/**
* APIContact constructor.
*
* @param array $declaredFunctions
*/
public function __construct() {
parent::__construct( $this->declaredFunctions );
}
/**
* @return array
*/
public function getDeclaredFunctions() {
return $this->declaredFunctions;
}
public function insert( array $data ) {
$id = Contact::insertNewContact( $data[ "firstName" ], $data[ "lastName" ], $data[ "surname" ],
$data[ "email" ], $data[ "address" ], $data[ "phoneNumber" ], $data[ "birthday" ] );
$this->returnJson( json_encode( [
"status" => "success",
"data" => [
"id" => $id
]
] ) );
}
public function delete( array $data ) {
Contact::deleteContact( $data[ "id" ] );
}
public function getContacts() {
$this->returnJson( json_encode( [
"contacts" => Contact::getAllContact()
] ) );
}
public function update( array $data ) {
$contact = Contact::getById( $data[ "id" ] );
$newData = [];
if ( $data[ "firstName" ] !== null && $data[ "firstName" ] !== "" ) {
$newData[ "first_name" ] = $data[ "firstName" ];
}
if ( $data[ "lastName" ] !== null && $data[ "lastName" ] !== "" ) {
$newData[ "last_name" ] = $data[ "lastName" ];
}
if ( $data[ "surname" ] !== null && $data[ "surname" ] !== "" ) {
$newData[ "surname" ] = $data[ "surname" ];
}
if ( $data[ "email" ] !== null && $data[ "email" ] !== "" ) {
$newData[ "email" ] = $data[ "email" ];
}
if ( $data[ "address" ] !== null && $data[ "address" ] !== "" ) {
$newData[ "address" ] = $data[ "address" ];
}
if ( $data[ "phoneNumber" ] !== null && $data[ "phoneNumber" ] !== "" ) {
$newData[ "phone_number" ] = $data[ "phoneNumber" ];
}
if ( $data[ "birthday" ] !== null && $data[ "birthday" ] !== "" ) {
$newData[ "birthday" ] = date( "Y-m-d", strtotime( $data[ "birthday" ] ) );
}
$contact->updateContact( $newData );
$this->returnJson( json_encode( $contact ) );
}
public function search( array $data ) {
if ( count_chars( $data[ "query" ] ) >= 3 ) {
$result = Contact::search( $data[ "query" ] );
if ( $result !== null ) {
$this->returnJson( [
"status" => "success",
"code" => 200,
"result" => $result,
] );
} else {
$this->returnJson( [
"status" => "error",
"code" => 404,
"message" => "Nothing find",
] );
}
} else {
$this->returnJson( [
"status" => "error",
"code" => 400,
"message" => "Need at least 3 chars",
] );
}
}
}
?>

View File

@ -6,87 +6,88 @@ use CAUProject3Contact\Controller\Controller;
class APIError extends Controller { class APIError extends Controller {
/** /**
* APIError constructor. * APIError constructor.
* *
* @param int $ErrCode * @param int $ErrCode
* @param string $devMessage * @param string $devMessage
* @param string $publicMessage * @param string $publicMessage
* @param string $code * @param string $code
*/ */
public function __construct( int $ErrCode = 500, string $devMessage = 'Erreur inconnue', string $publicMessage = 'Une erreur inconnue s\'est produite', string $code = '' ) { public function __construct( int $ErrCode = 500, string $devMessage = 'Erreur inconnue',
parent::__construct(); string $publicMessage = 'Une erreur inconnue s\'est produite', string $code = '' ) {
parent::__construct();
$tabCode = [ $tabCode = [
//Informational 1xx //Informational 1xx
100 => [ 'label' => '100 Continue', 'msg' => '100 Continue' ], 100 => [ 'label' => '100 Continue', 'msg' => '100 Continue' ],
101 => [ 'label' => '101 Switching Protocols', 'msg' => '101 Switching Protocols' ], 101 => [ 'label' => '101 Switching Protocols', 'msg' => '101 Switching Protocols' ],
//Successful 2xx //Successful 2xx
200 => [ 'label' => '200 OK', 'msg' => '200 OK' ], 200 => [ 'label' => '200 OK', 'msg' => '200 OK' ],
201 => [ 'label' => '201 Created', 'msg' => '201 Created' ], 201 => [ 'label' => '201 Created', 'msg' => '201 Created' ],
202 => [ 'label' => '202 Accepted', 'msg' => '202 Accepted' ], 202 => [ 'label' => '202 Accepted', 'msg' => '202 Accepted' ],
203 => [ 'label' => '203 Non-Authoritative Information', 'msg' => '203 Non-Authoritative Information' ], 203 => [ 'label' => '203 Non-Authoritative Information', 'msg' => '203 Non-Authoritative Information' ],
204 => [ 'label' => '204 No Content', 'msg' => '204 No Content' ], 204 => [ 'label' => '204 No Content', 'msg' => '204 No Content' ],
205 => [ 'label' => '205 Reset Content', 'msg' => '205 Reset Content' ], 205 => [ 'label' => '205 Reset Content', 'msg' => '205 Reset Content' ],
206 => [ 'label' => '206 Partial Content', 'msg' => '206 Partial Content' ], 206 => [ 'label' => '206 Partial Content', 'msg' => '206 Partial Content' ],
226 => [ 'label' => '226 IM Used', 'msg' => '226 IM Used' ], 226 => [ 'label' => '226 IM Used', 'msg' => '226 IM Used' ],
//Redirection 3xx //Redirection 3xx
300 => [ 'label' => '300 Multiple Choices', 'msg' => '300 Multiple Choices' ], 300 => [ 'label' => '300 Multiple Choices', 'msg' => '300 Multiple Choices' ],
301 => [ 'label' => '301 Moved Permanently', 'msg' => '301 Moved Permanently' ], 301 => [ 'label' => '301 Moved Permanently', 'msg' => '301 Moved Permanently' ],
302 => [ 'label' => '302 Found', 'msg' => '302 Found' ], 302 => [ 'label' => '302 Found', 'msg' => '302 Found' ],
303 => [ 'label' => '303 See Other', 'msg' => '303 See Other' ], 303 => [ 'label' => '303 See Other', 'msg' => '303 See Other' ],
304 => [ 'label' => '304 Not Modified', 'msg' => '304 Not Modified' ], 304 => [ 'label' => '304 Not Modified', 'msg' => '304 Not Modified' ],
305 => [ 'label' => '305 Use Proxy', 'msg' => '305 Use Proxy' ], 305 => [ 'label' => '305 Use Proxy', 'msg' => '305 Use Proxy' ],
306 => [ 'label' => '306 (Unused)', 'msg' => '306 (Unused)' ], 306 => [ 'label' => '306 (Unused)', 'msg' => '306 (Unused)' ],
307 => [ 'label' => '307 Temporary Redirect', 'msg' => '307 Temporary Redirect' ], 307 => [ 'label' => '307 Temporary Redirect', 'msg' => '307 Temporary Redirect' ],
//Client Error 4xx //Client Error 4xx
400 => [ 'label' => '400 Bad Request', 'msg' => '400 Bad Request' ], 400 => [ 'label' => '400 Bad Request', 'msg' => '400 Bad Request' ],
401 => [ 'label' => '401 Unauthorized', 'msg' => 'Vous n\'êtes pas autorisé à accéder à cette page' ], 401 => [ 'label' => '401 Unauthorized', 'msg' => 'Vous n\'êtes pas autorisé à accéder à cette page' ],
402 => [ 'label' => '402 Payment Required', 'msg' => '402 Payment Required' ], 402 => [ 'label' => '402 Payment Required', 'msg' => '402 Payment Required' ],
403 => [ 'label' => '403 Forbidden', 'msg' => '403 Forbidden' ], 403 => [ 'label' => '403 Forbidden', 'msg' => '403 Forbidden' ],
404 => [ 'label' => '404 Not Found', 'msg' => 'Page non trouvée' ], 404 => [ 'label' => '404 Not Found', 'msg' => 'Page non trouvée' ],
405 => [ 'label' => '405 Method Not Allowed', 'msg' => '405 Method Not Allowed' ], 405 => [ 'label' => '405 Method Not Allowed', 'msg' => '405 Method Not Allowed' ],
406 => [ 'label' => '406 Not Acceptable', 'msg' => '406 Not Acceptable' ], 406 => [ 'label' => '406 Not Acceptable', 'msg' => '406 Not Acceptable' ],
407 => [ 'label' => '407 Proxy Authentication Required', 'msg' => '407 Proxy Authentication Required' ], 407 => [ 'label' => '407 Proxy Authentication Required', 'msg' => '407 Proxy Authentication Required' ],
408 => [ 'label' => '408 Request Timeout', 'msg' => '408 Request Timeout' ], 408 => [ 'label' => '408 Request Timeout', 'msg' => '408 Request Timeout' ],
409 => [ 'label' => '409 Conflict', 'msg' => '409 Conflict' ], 409 => [ 'label' => '409 Conflict', 'msg' => '409 Conflict' ],
410 => [ 'label' => '410 Gone', 'msg' => '410 Gone' ], 410 => [ 'label' => '410 Gone', 'msg' => '410 Gone' ],
411 => [ 'label' => '411 Length Required', 'msg' => '411 Length Required' ], 411 => [ 'label' => '411 Length Required', 'msg' => '411 Length Required' ],
412 => [ 'label' => '412 Precondition Failed', 'msg' => '412 Precondition Failed' ], 412 => [ 'label' => '412 Precondition Failed', 'msg' => '412 Precondition Failed' ],
413 => [ 'label' => '413 Request Entity Too Large', 'msg' => '413 Request Entity Too Large' ], 413 => [ 'label' => '413 Request Entity Too Large', 'msg' => '413 Request Entity Too Large' ],
414 => [ 'label' => '414 Request-URI Too Long', 'msg' => '414 Request-URI Too Long' ], 414 => [ 'label' => '414 Request-URI Too Long', 'msg' => '414 Request-URI Too Long' ],
415 => [ 'label' => '415 Unsupported Media Type', 'msg' => '415 Unsupported Media Type' ], 415 => [ 'label' => '415 Unsupported Media Type', 'msg' => '415 Unsupported Media Type' ],
416 => [ 'label' => '416 Requested Range Not Satisfiable', 'msg' => '416 Requested Range Not Satisfiable' ], 416 => [ 'label' => '416 Requested Range Not Satisfiable', 'msg' => '416 Requested Range Not Satisfiable' ],
417 => [ 'label' => '417 Expectation Failed', 'msg' => '417 Expectation Failed' ], 417 => [ 'label' => '417 Expectation Failed', 'msg' => '417 Expectation Failed' ],
418 => [ 'label' => '418 I\'m a teapot', 'msg' => '418 I\'m a teapot' ], 418 => [ 'label' => '418 I\'m a teapot', 'msg' => '418 I\'m a teapot' ],
422 => [ 'label' => '422 Unprocessable Entity', 'msg' => '422 Unprocessable Entity' ], 422 => [ 'label' => '422 Unprocessable Entity', 'msg' => '422 Unprocessable Entity' ],
423 => [ 'label' => '423 Locked', 'msg' => '423 Locked' ], 423 => [ 'label' => '423 Locked', 'msg' => '423 Locked' ],
426 => [ 'label' => '426 Upgrade Required', 'msg' => '426 Upgrade Required' ], 426 => [ 'label' => '426 Upgrade Required', 'msg' => '426 Upgrade Required' ],
428 => [ 'label' => '428 Precondition Required', 'msg' => '428 Precondition Required' ], 428 => [ 'label' => '428 Precondition Required', 'msg' => '428 Precondition Required' ],
429 => [ 'label' => '429 Too Many Requests', 'msg' => '429 Too Many Requests' ], 429 => [ 'label' => '429 Too Many Requests', 'msg' => '429 Too Many Requests' ],
431 => [ 'label' => '431 Request Header Fields Too Large', 'msg' => '431 Request Header Fields Too Large' ], 431 => [ 'label' => '431 Request Header Fields Too Large', 'msg' => '431 Request Header Fields Too Large' ],
//Server Error 5xx //Server Error 5xx
500 => [ 'label' => '500 Internal Server Error', 'msg' => 'Une erreur est survenue' ], 500 => [ 'label' => '500 Internal Server Error', 'msg' => 'Une erreur est survenue' ],
501 => [ 'label' => '501 Not Implemented', 'msg' => '501 Not Implemented' ], 501 => [ 'label' => '501 Not Implemented', 'msg' => '501 Not Implemented' ],
502 => [ 'label' => '502 Bad Gateway', 'msg' => '502 Bad Gateway' ], 502 => [ 'label' => '502 Bad Gateway', 'msg' => '502 Bad Gateway' ],
503 => [ 'label' => '503 Service Unavailable', 'msg' => '503 Service Unavailable' ], 503 => [ 'label' => '503 Service Unavailable', 'msg' => '503 Service Unavailable' ],
504 => [ 'label' => '504 Gateway Timeout', 'msg' => '504 Gateway Timeout' ], 504 => [ 'label' => '504 Gateway Timeout', 'msg' => '504 Gateway Timeout' ],
505 => [ 'label' => '505 HTTP Version Not Supported', 'msg' => '505 HTTP Version Not Supported' ], 505 => [ 'label' => '505 HTTP Version Not Supported', 'msg' => '505 HTTP Version Not Supported' ],
506 => [ 'label' => '506 Variant Also Negotiates', 'msg' => '506 Variant Also Negotiates' ], 506 => [ 'label' => '506 Variant Also Negotiates', 'msg' => '506 Variant Also Negotiates' ],
510 => [ 'label' => '510 Not Extended', 'msg' => '510 Not Extended' ], 510 => [ 'label' => '510 Not Extended', 'msg' => '510 Not Extended' ],
511 => [ 'label' => '511 Network Authentication Required', 'msg' => '511 Network Authentication Required' ] 511 => [ 'label' => '511 Network Authentication Required', 'msg' => '511 Network Authentication Required' ]
]; ];
header( 'Content-Type: application/json' ); header( 'Content-Type: application/json' );
header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $tabCode[ $ErrCode ]['label'] ); header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' ' . $tabCode[ $ErrCode ][ 'label' ] );
echo json_encode( [ echo json_encode( [
'status' => 'echec', 'status' => 'echec',
'msg' => $publicMessage, 'msg' => $publicMessage,
'devMsg' => $devMessage, 'devMsg' => $devMessage,
'code' => $code 'code' => $code
], JSON_PRETTY_PRINT ); ], JSON_PRETTY_PRINT );
exit(); exit();
} }
} }
?> ?>

View File

@ -6,127 +6,127 @@ use CAUProject3Contact\Config;
class APIRouter { class APIRouter {
//Les méthodes HTTP gérée par l'API //Les méthodes HTTP gérée par l'API
const HTTP_METHODS = [ 'GET', 'POST', 'DELETE', 'PUT' ]; const HTTP_METHODS = [ 'GET', 'POST', 'DELETE', 'PUT' ];
/** /**
* APIRouter constructor. * APIRouter constructor.
* *
* @param string $file * @param string $file
* @param string $action * @param string $action
*/ */
public function __construct( string $file, string $action ) { public function __construct( string $file, string $action ) {
//On vérifie que les paramètres ne sont pas vides //On vérifie que les paramètres ne sont pas vides
if ( empty( $file ) || empty( $action ) ) { if ( empty( $file ) || empty( $action ) ) {
new APIError(); new APIError();
} }
//On vérifie que la classe appelée existe //On vérifie que la classe appelée existe
$fileName = 'API' . ucfirst( $file ); $fileName = 'API' . ucfirst( $file );
if ( ! file_exists( 'src/API/' . $fileName . '.php' ) ) { if ( !file_exists( 'src/API/' . $fileName . '.php' ) ) {
new APIError( 404 ); new APIError( 404 );
} }
//On instancie la classe. //On instancie la classe.
$class = '\\' . Config::NAMESPACE . '\\API\\' . $fileName; $class = '\\' . Config::NAMESPACE . '\\API\\' . $fileName;
$class = new $class( $action ); $class = new $class( $action );
//On vérifie que l'action demandé est déclarée //On vérifie que l'action demandé est déclarée
if ( ! array_key_exists( $action, $class->getDeclaredFunctions() ) ) { if ( !array_key_exists( $action, $class->getDeclaredFunctions() ) ) {
new APIError( 404 ); new APIError( 404 );
} }
//On reconstruit le nom de la fonction //On reconstruit le nom de la fonction
$array = explode( '-', $action ); $array = explode( '-', $action );
foreach ( $array as $key => $value ) { foreach ( $array as $key => $value ) {
if ( $key == 0 ) { if ( $key == 0 ) {
$array[ $key ] = $value; $array[ $key ] = $value;
} else { } else {
$array[ $key ] = ucfirst( $value ); $array[ $key ] = ucfirst( $value );
} }
} }
$function = implode( '', $array ); //le nom de la fonction $function = implode( '', $array ); //le nom de la fonction
//On vérifie que la fonction existe dans la classe //On vérifie que la fonction existe dans la classe
if ( ! method_exists( $class, $function ) ) { if ( !method_exists( $class, $function ) ) {
new APIError( 500, 'La fonction ' . $function . ' n\'existe pas dans la classe ' . get_class( $class ) ); new APIError( 500, 'La fonction ' . $function . ' n\'existe pas dans la classe ' . get_class( $class ) );
} }
//On vérifie que la méthode d'envoie est référencée //On vérifie que la méthode d'envoie est référencée
$method = $class->getDeclaredFunctions()[ $action ]['method']; $method = $class->getDeclaredFunctions()[ $action ][ 'method' ];
if ( ! in_array( $method, self::HTTP_METHODS ) ) { if ( !in_array( $method, self::HTTP_METHODS ) ) {
new APIError( 500, 'méthode http inconnue' ); new APIError( 500, 'méthode http inconnue' );
} }
//On vérifie que la méthode requise et la mathode obtenue sont les même //On vérifie que la méthode requise et la mathode obtenue sont les même
if ( $method != $_SERVER['REQUEST_METHOD'] ) { if ( $method != $_SERVER[ 'REQUEST_METHOD' ] ) {
new APIError( 400, 'La méthode HTTP ne correspond pas à la méthode prévue' ); new APIError( 400, 'La méthode HTTP ne correspond pas à la méthode prévue' );
} }
//On met les paramètres dans le tableau $data //On met les paramètres dans le tableau $data
$params = $class->getDeclaredFunctions()[ $action ]['params']; $params = $class->getDeclaredFunctions()[ $action ][ 'params' ];
$data = []; $data = [];
if ( ! empty( $params ) ) { if ( !empty( $params ) ) {
if ( $method == 'DELETE' || $method == 'PUT' ) { if ( $method == 'DELETE' || $method == 'PUT' ) {
parse_str( file_get_contents( 'php://input' ), $data ); parse_str( file_get_contents( 'php://input' ), $data );
} else if ( $method == 'POST' ) { } else if ( $method == 'POST' ) {
$data = $_POST; $data = $_POST;
} else if ( $method == 'GET' ) { } else if ( $method == 'GET' ) {
$data = $_GET; $data = $_GET;
} }
//On boucle sur les paramètres de la doc de la fonction //On boucle sur les paramètres de la doc de la fonction
foreach ( $params as $p => $options ) { foreach ( $params as $p => $options ) {
if ( ! isset( $options['required'] ) ) { if ( !isset( $options[ 'required' ] ) ) {
$options['required'] = false; $options[ 'required' ] = false;
} }
//Si le paramètre est obligatoire et qu'il est vide ou non fourni on lève une erreur 400 BAD REQUEST //Si le paramètre est obligatoire et qu'il est vide ou non fourni on lève une erreur 400 BAD REQUEST
if ( $options['required'] && ( ! array_key_exists( $p, $data ) || ( empty( $data[ $p ] ) && $data[ $p ] != '0' ) ) ) { if ( $options[ 'required' ] && ( !array_key_exists( $p, $data ) || ( empty( $data[ $p ] ) && $data[ $p ] != '0' ) ) ) {
$devMsg = 'Paramètre ' . $p . ' manquant'; $devMsg = 'Paramètre ' . $p . ' manquant';
if ( isset( $options['devMsg'] ) ) { if ( isset( $options[ 'devMsg' ] ) ) {
$devMsg = $options['devMsg']; $devMsg = $options[ 'devMsg' ];
} }
$publicMsg = 'Des paramètres obligatoires ne sont pas envoyés ou sont vides'; $publicMsg = 'Des paramètres obligatoires ne sont pas envoyés ou sont vides';
if ( isset( $options['publicMsg'] ) ) { if ( isset( $options[ 'publicMsg' ] ) ) {
$publicMsg = $options['publicMsg']; $publicMsg = $options[ 'publicMsg' ];
} }
$code = ''; $code = '';
if ( isset( $options['code'] ) ) { if ( isset( $options[ 'code' ] ) ) {
$code = $options['code']; $code = $options[ 'code' ];
} }
new APIError( 400, $devMsg, $publicMsg, $code ); new APIError( 400, $devMsg, $publicMsg, $code );
} }
//On vérifie que le type donné correspond au typage requis //On vérifie que le type donné correspond au typage requis
if ( isset( $options['type'] ) ) { if ( isset( $options[ 'type' ] ) ) {
if ( $options['type'] == 'int' ) { if ( $options[ 'type' ] == 'int' ) {
if ( ctype_digit( $data[ $p ] ) ) { if ( ctype_digit( $data[ $p ] ) ) {
$data[ $p ] = (int) $data[ $p ]; $data[ $p ] = (int)$data[ $p ];
} else { } else {
new APIError( 400, 'Le type donné ne correspond pas au type demandé pour le paramètre ' . $p . ' : string donné, ' . $options['type'] . ' requis' ); new APIError( 400, 'Le type donné ne correspond pas au type demandé pour le paramètre ' . $p . ' : string donné, ' . $options[ 'type' ] . ' requis' );
} }
} else if ( $options['type'] == 'bool' ) { } else if ( $options[ 'type' ] == 'bool' ) {
if ( $data[ $p ] == 'true' || $data[ $p ] == '1' ) { if ( $data[ $p ] == 'true' || $data[ $p ] == '1' ) {
$data[ $p ] = true; $data[ $p ] = true;
} else if ( $data[ $p ] == 'false' || $data[ $p ] == '0' ) { } else if ( $data[ $p ] == 'false' || $data[ $p ] == '0' ) {
$data[ $p ] = false; $data[ $p ] = false;
} else { } else {
new APIError( 400, 'Le type donné ne correspond pas au type demandé pour le paramètre ' . $p . ' : string donné, ' . $options['type'] . ' requis' ); new APIError( 400, 'Le type donné ne correspond pas au type demandé pour le paramètre ' . $p . ' : string donné, ' . $options[ 'type' ] . ' requis' );
} }
} }
} }
//Si un paramètre non obligatoire n'est pas donné par l'utilisateur on lui donne la valeur par défaut d'une chaine vide //Si un paramètre non obligatoire n'est pas donné par l'utilisateur on lui donne la valeur par défaut d'une chaine vide
if ( ! array_key_exists( $p, $data ) ) { if ( !array_key_exists( $p, $data ) ) {
$data[ $p ] = ''; $data[ $p ] = '';
} }
} }
} }
//On appelle la fonction correspondante pour le traitement //On appelle la fonction correspondante pour le traitement
$class->$function( $data ); $class->$function( $data );
} }
} }
?> ?>

View File

@ -4,21 +4,21 @@ namespace CAUProject3Contact;
class Autoloader { class Autoloader {
/** /**
* Enregistre notre autoloader * Enregistre notre autoloader
*/ */
static function register() { static function register() {
spl_autoload_register( array( __CLASS__, 'autoload' ) ); spl_autoload_register( array( __CLASS__, 'autoload' ) );
} }
/** /**
* Inclue le fichier correspondant à notre classe * Inclue le fichier correspondant à notre classe
* *
* @param $class string Le nom de la classe à charger * @param $class string Le nom de la classe à charger
*/ */
static function autoload( $class ) { static function autoload( $class ) {
if ( preg_match( '#^' . Config::NAMESPACE . '\\\(.+)$#', $class, $matches ) ) { if ( preg_match( '#^' . Config::NAMESPACE . '\\\(.+)$#', $class, $matches ) ) {
require 'src/' . str_replace( '\\', '/', $matches[1] ) . '.php'; require 'src/' . str_replace( '\\', '/', $matches[ 1 ] ) . '.php';
} }
} }
} }

View File

@ -3,12 +3,12 @@
namespace CAUProject3Contact; namespace CAUProject3Contact;
class Config { class Config {
const SITE_JS_VERSION = '1.00'; const SITE_JS_VERSION = '0.01';
const SITE_CSS_VERSION = '1.00'; const SITE_CSS_VERSION = '0.01';
const TITLE_HEADER = 'Your contact'; const TITLE_HEADER = 'Your contact';
const DESCRIPTION_HEADER = 'Manage your contact easly'; const DESCRIPTION_HEADER = 'Manage your contact easly';
const NAMESPACE = 'CAUProject3Contact'; const NAMESPACE = 'CAUProject3Contact';
const FAVICON_PATH = '/img/favicon.png'; const FAVICON_PATH = '/img/favicon.ico';
} }

View File

@ -6,35 +6,35 @@ use CAUProject3Contact\Config;
class Controller { class Controller {
private $data; private $data;
public function __construct() { public function __construct() {
$this->data = []; $this->data = [];
} }
protected function view() { protected function view() {
ob_start(); ob_start();
extract( $this->data ); extract( $this->data );
require 'src/View/' . str_replace( '\\', '/', preg_replace( '#^' . Config::NAMESPACE . '\\\Controller\\\#', '', get_class( $this ) ) ) . '.php'; require 'src/View/' . str_replace( '\\', '/', preg_replace( '#^' . Config::NAMESPACE . '\\\Controller\\\#', '', get_class( $this ) ) ) . '.php';
ob_end_flush(); ob_end_flush();
exit(); exit();
} }
protected function addData( $data ) { protected function addData( $data ) {
$this->data += $data; $this->data += $data;
} }
protected function returnJson( $data ) { protected function returnJson( $data ) {
header( 'Content-Type: application/json' ); header( 'Content-Type: application/json' );
echo json_encode( $data ); echo json_encode( $data );
exit(); exit();
} }
protected function throwError( $msg, $code = '' ) { protected function throwError( $msg, $code = '' ) {
header( 'Content-Type: application/json' ); header( 'Content-Type: application/json' );
echo json_encode( [ 'status' => 'echec', 'msg' => $msg, 'code' => $code ], JSON_PRETTY_PRINT ); echo json_encode( [ 'status' => 'echec', 'msg' => $msg, 'code' => $code ], JSON_PRETTY_PRINT );
exit(); exit();
} }
} }
?> ?>

View File

@ -6,67 +6,67 @@ use CAUProject3Contact\Config;
class ControllerSite { class ControllerSite {
private $data; private $data;
private $head; private $head;
private $footer; private $footer;
public function __construct() { public function __construct() {
$this->data = []; $this->data = [];
$this->head = []; $this->head = [];
$this->footer = []; $this->footer = [];
} }
protected function view( $header = true, $footer = true ) { protected function view( $header = true, $footer = true ) {
ob_start(); ob_start();
extract( $this->data ); extract( $this->data );
if ( empty( $this->head['title'] ) ) { if ( empty( $this->head[ 'title' ] ) ) {
$this->head['title'] = Config::TITLE_HEADER; $this->head[ 'title' ] = Config::TITLE_HEADER;
} }
if ( empty( $this->head['description'] ) ) { if ( empty( $this->head[ 'description' ] ) ) {
$this->head['description'] = Config::DESCRIPTION_HEADER; $this->head[ 'description' ] = Config::DESCRIPTION_HEADER;
} }
if ( $header ) { if ( $header ) {
require 'src/View/Site/tpl/head.php'; require 'src/View/Site/tpl/head.php';
} }
require 'src/View/' . str_replace( '\\', '/', preg_replace( '#^' . Config::NAMESPACE . '\\\Controller\\\#', '', get_class( $this ) ) ) . '.php'; require 'src/View/' . str_replace( '\\', '/', preg_replace( '#^' . Config::NAMESPACE . '\\\Controller\\\#', '', get_class( $this ) ) ) . '.php';
if ( $footer ) { if ( $footer ) {
require 'src/View/Site/tpl/footer.php'; require 'src/View/Site/tpl/footer.php';
} }
ob_end_flush(); ob_end_flush();
exit(); exit();
} }
protected function addHead( $head ) { protected function addHead( $head ) {
$this->head += $head; $this->head += $head;
} }
protected function addData( $data ) { protected function addData( $data ) {
$this->data += $data; $this->data += $data;
} }
protected function addFooter( $footer ) { protected function addFooter( $footer ) {
$this->footer += $footer; $this->footer += $footer;
} }
/** /**
* @param $data * @param $data
*/ */
protected function returnJson( $data ) { protected function returnJson( $data ) {
header( 'Content-Type: application/json' ); header( 'Content-Type: application/json' );
echo json_encode( $data ); echo json_encode( $data );
exit(); exit();
} }
protected function throwError( $msg, $code = '' ) { protected function throwError( $msg, $code = '' ) {
header( 'Content-Type: application/json' ); header( 'Content-Type: application/json' );
echo json_encode( [ 'status' => 'echec', 'msg' => $msg, 'code' => $code ], JSON_PRETTY_PRINT ); echo json_encode( [ 'status' => 'echec', 'msg' => $msg, 'code' => $code ], JSON_PRETTY_PRINT );
exit(); exit();
} }
} }
?> ?>

View File

@ -4,96 +4,96 @@ namespace CAUProject3Contact\Controller;
class Error extends Controller { class Error extends Controller {
/** /**
* Error constructor. * Error constructor.
* *
* @param int $ErrCode * @param int $ErrCode
* @param string $message * @param string $message
*/ */
public function __construct( $ErrCode = 500, $message = '' ) { public function __construct( $ErrCode = 500, $message = '' ) {
parent::__construct(); parent::__construct();
$tabCode = [ $tabCode = [
//Informational 1xx //Informational 1xx
100 => [ 'label' => '100 Continue', 'msg' => '100 Continue' ], 100 => [ 'label' => '100 Continue', 'msg' => '100 Continue' ],
101 => [ 'label' => '101 Switching Protocols', 'msg' => '101 Switching Protocols' ], 101 => [ 'label' => '101 Switching Protocols', 'msg' => '101 Switching Protocols' ],
//Successful 2xx //Successful 2xx
200 => [ 'label' => '200 OK', 'msg' => '200 OK' ], 200 => [ 'label' => '200 OK', 'msg' => '200 OK' ],
201 => [ 'label' => '201 Created', 'msg' => '201 Created' ], 201 => [ 'label' => '201 Created', 'msg' => '201 Created' ],
202 => [ 'label' => '202 Accepted', 'msg' => '202 Accepted' ], 202 => [ 'label' => '202 Accepted', 'msg' => '202 Accepted' ],
203 => [ 'label' => '203 Non-Authoritative Information', 'msg' => '203 Non-Authoritative Information' ], 203 => [ 'label' => '203 Non-Authoritative Information', 'msg' => '203 Non-Authoritative Information' ],
204 => [ 'label' => '204 No Content', 'msg' => '204 No Content' ], 204 => [ 'label' => '204 No Content', 'msg' => '204 No Content' ],
205 => [ 'label' => '205 Reset Content', 'msg' => '205 Reset Content' ], 205 => [ 'label' => '205 Reset Content', 'msg' => '205 Reset Content' ],
206 => [ 'label' => '206 Partial Content', 'msg' => '206 Partial Content' ], 206 => [ 'label' => '206 Partial Content', 'msg' => '206 Partial Content' ],
226 => [ 'label' => '226 IM Used', 'msg' => '226 IM Used' ], 226 => [ 'label' => '226 IM Used', 'msg' => '226 IM Used' ],
//Redirection 3xx //Redirection 3xx
300 => [ 'label' => '300 Multiple Choices', 'msg' => '300 Multiple Choices' ], 300 => [ 'label' => '300 Multiple Choices', 'msg' => '300 Multiple Choices' ],
301 => [ 'label' => '301 Moved Permanently', 'msg' => '301 Moved Permanently' ], 301 => [ 'label' => '301 Moved Permanently', 'msg' => '301 Moved Permanently' ],
302 => [ 'label' => '302 Found', 'msg' => '302 Found' ], 302 => [ 'label' => '302 Found', 'msg' => '302 Found' ],
303 => [ 'label' => '303 See Other', 'msg' => '303 See Other' ], 303 => [ 'label' => '303 See Other', 'msg' => '303 See Other' ],
304 => [ 'label' => '304 Not Modified', 'msg' => '304 Not Modified' ], 304 => [ 'label' => '304 Not Modified', 'msg' => '304 Not Modified' ],
305 => [ 'label' => '305 Use Proxy', 'msg' => '305 Use Proxy' ], 305 => [ 'label' => '305 Use Proxy', 'msg' => '305 Use Proxy' ],
306 => [ 'label' => '306 (Unused)', 'msg' => '306 (Unused)' ], 306 => [ 'label' => '306 (Unused)', 'msg' => '306 (Unused)' ],
307 => [ 'label' => '307 Temporary Redirect', 'msg' => '307 Temporary Redirect' ], 307 => [ 'label' => '307 Temporary Redirect', 'msg' => '307 Temporary Redirect' ],
//Client Error 4xx //Client Error 4xx
400 => [ 'label' => '400 Bad Request', 'msg' => '400 Bad Request' ], 400 => [ 'label' => '400 Bad Request', 'msg' => '400 Bad Request' ],
401 => [ 'label' => '401 Unauthorized', 'msg' => 'Vous n\'êtes pas autorisé à accéder à cette page' ], 401 => [ 'label' => '401 Unauthorized', 'msg' => 'Vous n\'êtes pas autorisé à accéder à cette page' ],
402 => [ 'label' => '402 Payment Required', 'msg' => '402 Payment Required' ], 402 => [ 'label' => '402 Payment Required', 'msg' => '402 Payment Required' ],
403 => [ 'label' => '403 Forbidden', 'msg' => '403 Forbidden' ], 403 => [ 'label' => '403 Forbidden', 'msg' => '403 Forbidden' ],
404 => [ 'label' => '404 Not Found', 'msg' => 'Page non trouvée' ], 404 => [ 'label' => '404 Not Found', 'msg' => 'Page non trouvée' ],
405 => [ 'label' => '405 Method Not Allowed', 'msg' => '405 Method Not Allowed' ], 405 => [ 'label' => '405 Method Not Allowed', 'msg' => '405 Method Not Allowed' ],
406 => [ 'label' => '406 Not Acceptable', 'msg' => '406 Not Acceptable' ], 406 => [ 'label' => '406 Not Acceptable', 'msg' => '406 Not Acceptable' ],
407 => [ 'label' => '407 Proxy Authentication Required', 'msg' => '407 Proxy Authentication Required' ], 407 => [ 'label' => '407 Proxy Authentication Required', 'msg' => '407 Proxy Authentication Required' ],
408 => [ 'label' => '408 Request Timeout', 'msg' => '408 Request Timeout' ], 408 => [ 'label' => '408 Request Timeout', 'msg' => '408 Request Timeout' ],
409 => [ 'label' => '409 Conflict', 'msg' => '409 Conflict' ], 409 => [ 'label' => '409 Conflict', 'msg' => '409 Conflict' ],
410 => [ 'label' => '410 Gone', 'msg' => '410 Gone' ], 410 => [ 'label' => '410 Gone', 'msg' => '410 Gone' ],
411 => [ 'label' => '411 Length Required', 'msg' => '411 Length Required' ], 411 => [ 'label' => '411 Length Required', 'msg' => '411 Length Required' ],
412 => [ 'label' => '412 Precondition Failed', 'msg' => '412 Precondition Failed' ], 412 => [ 'label' => '412 Precondition Failed', 'msg' => '412 Precondition Failed' ],
413 => [ 'label' => '413 Request Entity Too Large', 'msg' => '413 Request Entity Too Large' ], 413 => [ 'label' => '413 Request Entity Too Large', 'msg' => '413 Request Entity Too Large' ],
414 => [ 'label' => '414 Request-URI Too Long', 'msg' => '414 Request-URI Too Long' ], 414 => [ 'label' => '414 Request-URI Too Long', 'msg' => '414 Request-URI Too Long' ],
415 => [ 'label' => '415 Unsupported Media Type', 'msg' => '415 Unsupported Media Type' ], 415 => [ 'label' => '415 Unsupported Media Type', 'msg' => '415 Unsupported Media Type' ],
416 => [ 'label' => '416 Requested Range Not Satisfiable', 'msg' => '416 Requested Range Not Satisfiable' ], 416 => [ 'label' => '416 Requested Range Not Satisfiable', 'msg' => '416 Requested Range Not Satisfiable' ],
417 => [ 'label' => '417 Expectation Failed', 'msg' => '417 Expectation Failed' ], 417 => [ 'label' => '417 Expectation Failed', 'msg' => '417 Expectation Failed' ],
418 => [ 'label' => '418 I\'m a teapot', 'msg' => '418 I\'m a teapot' ], 418 => [ 'label' => '418 I\'m a teapot', 'msg' => '418 I\'m a teapot' ],
422 => [ 'label' => '422 Unprocessable Entity', 'msg' => '422 Unprocessable Entity' ], 422 => [ 'label' => '422 Unprocessable Entity', 'msg' => '422 Unprocessable Entity' ],
423 => [ 'label' => '423 Locked', 'msg' => '423 Locked' ], 423 => [ 'label' => '423 Locked', 'msg' => '423 Locked' ],
426 => [ 'label' => '426 Upgrade Required', 'msg' => '426 Upgrade Required' ], 426 => [ 'label' => '426 Upgrade Required', 'msg' => '426 Upgrade Required' ],
428 => [ 'label' => '428 Precondition Required', 'msg' => '428 Precondition Required' ], 428 => [ 'label' => '428 Precondition Required', 'msg' => '428 Precondition Required' ],
429 => [ 'label' => '429 Too Many Requests', 'msg' => '429 Too Many Requests' ], 429 => [ 'label' => '429 Too Many Requests', 'msg' => '429 Too Many Requests' ],
431 => [ 'label' => '431 Request Header Fields Too Large', 'msg' => '431 Request Header Fields Too Large' ], 431 => [ 'label' => '431 Request Header Fields Too Large', 'msg' => '431 Request Header Fields Too Large' ],
//Server Error 5xx //Server Error 5xx
500 => [ 'label' => '500 Internal Server Error', 'msg' => 'Une erreur est survenue' ], 500 => [ 'label' => '500 Internal Server Error', 'msg' => 'Une erreur est survenue' ],
501 => [ 'label' => '501 Not Implemented', 'msg' => '501 Not Implemented' ], 501 => [ 'label' => '501 Not Implemented', 'msg' => '501 Not Implemented' ],
502 => [ 'label' => '502 Bad Gateway', 'msg' => '502 Bad Gateway' ], 502 => [ 'label' => '502 Bad Gateway', 'msg' => '502 Bad Gateway' ],
503 => [ 'label' => '503 Service Unavailable', 'msg' => '503 Service Unavailable' ], 503 => [ 'label' => '503 Service Unavailable', 'msg' => '503 Service Unavailable' ],
504 => [ 'label' => '504 Gateway Timeout', 'msg' => '504 Gateway Timeout' ], 504 => [ 'label' => '504 Gateway Timeout', 'msg' => '504 Gateway Timeout' ],
505 => [ 'label' => '505 HTTP Version Not Supported', 'msg' => '505 HTTP Version Not Supported' ], 505 => [ 'label' => '505 HTTP Version Not Supported', 'msg' => '505 HTTP Version Not Supported' ],
506 => [ 'label' => '506 Variant Also Negotiates', 'msg' => '506 Variant Also Negotiates' ], 506 => [ 'label' => '506 Variant Also Negotiates', 'msg' => '506 Variant Also Negotiates' ],
510 => [ 'label' => '510 Not Extended', 'msg' => '510 Not Extended' ], 510 => [ 'label' => '510 Not Extended', 'msg' => '510 Not Extended' ],
511 => [ 'label' => '511 Network Authentication Required', 'msg' => '511 Network Authentication Required' ] 511 => [ 'label' => '511 Network Authentication Required', 'msg' => '511 Network Authentication Required' ]
]; ];
if ( isset( $tabCode[ $ErrCode ] ) ) { if ( isset( $tabCode[ $ErrCode ] ) ) {
header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $tabCode[ $ErrCode ]['label'] ); header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' ' . $tabCode[ $ErrCode ][ 'label' ] );
if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) { if ( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) == 'xmlhttprequest' ) {
$this->throwError( $tabCode[ $ErrCode ]['msg'], 'Erreur_' . $ErrCode ); $this->throwError( $tabCode[ $ErrCode ][ 'msg' ], 'Erreur_' . $ErrCode );
} }
$erreur = $tabCode[ $ErrCode ]['msg']; $erreur = $tabCode[ $ErrCode ][ 'msg' ];
$this->addData( [ 'erreur' => $erreur ] ); $this->addData( [ 'erreur' => $erreur ] );
} else { } else {
header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $tabCode[500]['label'] ); header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' ' . $tabCode[ 500 ][ 'label' ] );
if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) { if ( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) == 'xmlhttprequest' ) {
$this->throwError( $tabCode[500]['msg'], 'Erreur_500' ); $this->throwError( $tabCode[ 500 ][ 'msg' ], 'Erreur_500' );
} }
$erreur = $tabCode[500]['msg']; $erreur = $tabCode[ 500 ][ 'msg' ];
$this->addData( [ 'erreur' => $erreur ] ); $this->addData( [ 'erreur' => $erreur ] );
} }
if ( ! empty( $message ) ) { if ( !empty( $message ) ) {
$this->addData( [ 'message' => $message ] ); $this->addData( [ 'message' => $message ] );
} }
$this->view(); $this->view();
} }
} }

View File

@ -3,25 +3,27 @@
namespace CAUProject3Contact\Controller\Site; namespace CAUProject3Contact\Controller\Site;
use CAUProject3Contact\Controller\ControllerSite; use CAUProject3Contact\Controller\ControllerSite;
use CAUProject3Contact\Model\Contact;
class Index extends ControllerSite { class Index extends ControllerSite {
/** /**
* Index constructor. * Index constructor.
*/ */
public function __construct() { public function __construct() {
parent::__construct(); parent::__construct();
$this->addHead( [ $this->addHead( [] );
] );
$this->addFooter( [ $this->addFooter( [] );
] ); $contacts = Contact::getAllContact();
$this->addData( [] ); $this->addData( [
$this->view(); "contacts" => $contacts
} ] );
$this->view();
}
} }
?> ?>

View File

@ -6,101 +6,101 @@ use CAUProject3Contact\Controller\ControllerSite;
class SiteError extends ControllerSite { class SiteError extends ControllerSite {
/** /**
* SiteError constructor. * SiteError constructor.
* *
* @param int $ErrCode * @param int $ErrCode
* @param string $message * @param string $message
*/ */
public function __construct( $ErrCode = 500, $message = '' ) { public function __construct( $ErrCode = 500, $message = '' ) {
parent::__construct(); parent::__construct();
$tabCode = [ $tabCode = [
//Informational 1xx //Informational 1xx
100 => [ 'label' => '100 Continue', 'msg' => '100 Continue' ], 100 => [ 'label' => '100 Continue', 'msg' => '100 Continue' ],
101 => [ 'label' => '101 Switching Protocols', 'msg' => '101 Switching Protocols' ], 101 => [ 'label' => '101 Switching Protocols', 'msg' => '101 Switching Protocols' ],
//Successful 2xx //Successful 2xx
200 => [ 'label' => '200 OK', 'msg' => '200 OK' ], 200 => [ 'label' => '200 OK', 'msg' => '200 OK' ],
201 => [ 'label' => '201 Created', 'msg' => '201 Created' ], 201 => [ 'label' => '201 Created', 'msg' => '201 Created' ],
202 => [ 'label' => '202 Accepted', 'msg' => '202 Accepted' ], 202 => [ 'label' => '202 Accepted', 'msg' => '202 Accepted' ],
203 => [ 'label' => '203 Non-Authoritative Information', 'msg' => '203 Non-Authoritative Information' ], 203 => [ 'label' => '203 Non-Authoritative Information', 'msg' => '203 Non-Authoritative Information' ],
204 => [ 'label' => '204 No Content', 'msg' => '204 No Content' ], 204 => [ 'label' => '204 No Content', 'msg' => '204 No Content' ],
205 => [ 'label' => '205 Reset Content', 'msg' => '205 Reset Content' ], 205 => [ 'label' => '205 Reset Content', 'msg' => '205 Reset Content' ],
206 => [ 'label' => '206 Partial Content', 'msg' => '206 Partial Content' ], 206 => [ 'label' => '206 Partial Content', 'msg' => '206 Partial Content' ],
226 => [ 'label' => '226 IM Used', 'msg' => '226 IM Used' ], 226 => [ 'label' => '226 IM Used', 'msg' => '226 IM Used' ],
//Redirection 3xx //Redirection 3xx
300 => [ 'label' => '300 Multiple Choices', 'msg' => '300 Multiple Choices' ], 300 => [ 'label' => '300 Multiple Choices', 'msg' => '300 Multiple Choices' ],
301 => [ 'label' => '301 Moved Permanently', 'msg' => '301 Moved Permanently' ], 301 => [ 'label' => '301 Moved Permanently', 'msg' => '301 Moved Permanently' ],
302 => [ 'label' => '302 Found', 'msg' => '302 Found' ], 302 => [ 'label' => '302 Found', 'msg' => '302 Found' ],
303 => [ 'label' => '303 See Other', 'msg' => '303 See Other' ], 303 => [ 'label' => '303 See Other', 'msg' => '303 See Other' ],
304 => [ 'label' => '304 Not Modified', 'msg' => '304 Not Modified' ], 304 => [ 'label' => '304 Not Modified', 'msg' => '304 Not Modified' ],
305 => [ 'label' => '305 Use Proxy', 'msg' => '305 Use Proxy' ], 305 => [ 'label' => '305 Use Proxy', 'msg' => '305 Use Proxy' ],
306 => [ 'label' => '306 (Unused)', 'msg' => '306 (Unused)' ], 306 => [ 'label' => '306 (Unused)', 'msg' => '306 (Unused)' ],
307 => [ 'label' => '307 Temporary Redirect', 'msg' => '307 Temporary Redirect' ], 307 => [ 'label' => '307 Temporary Redirect', 'msg' => '307 Temporary Redirect' ],
//Client Error 4xx //Client Error 4xx
400 => [ 'label' => '400 Bad Request', 'msg' => '400 Bad Request' ], 400 => [ 'label' => '400 Bad Request', 'msg' => '400 Bad Request' ],
401 => [ 'label' => '401 Unauthorized', 'msg' => '401 Unauthorized' ], 401 => [ 'label' => '401 Unauthorized', 'msg' => '401 Unauthorized' ],
402 => [ 'label' => '402 Payment Required', 'msg' => '402 Payment Required' ], 402 => [ 'label' => '402 Payment Required', 'msg' => '402 Payment Required' ],
403 => [ 'label' => '403 Forbidden', 'msg' => '403 Forbidden' ], 403 => [ 'label' => '403 Forbidden', 'msg' => '403 Forbidden' ],
404 => [ 'label' => '404 Not Found', 'msg' => 'Page non trouvée' ], 404 => [ 'label' => '404 Not Found', 'msg' => 'Page non trouvée' ],
405 => [ 'label' => '405 Method Not Allowed', 'msg' => '405 Method Not Allowed' ], 405 => [ 'label' => '405 Method Not Allowed', 'msg' => '405 Method Not Allowed' ],
406 => [ 'label' => '406 Not Acceptable', 'msg' => '406 Not Acceptable' ], 406 => [ 'label' => '406 Not Acceptable', 'msg' => '406 Not Acceptable' ],
407 => [ 'label' => '407 Proxy Authentication Required', 'msg' => '407 Proxy Authentication Required' ], 407 => [ 'label' => '407 Proxy Authentication Required', 'msg' => '407 Proxy Authentication Required' ],
408 => [ 'label' => '408 Request Timeout', 'msg' => '408 Request Timeout' ], 408 => [ 'label' => '408 Request Timeout', 'msg' => '408 Request Timeout' ],
409 => [ 'label' => '409 Conflict', 'msg' => '409 Conflict' ], 409 => [ 'label' => '409 Conflict', 'msg' => '409 Conflict' ],
410 => [ 'label' => '410 Gone', 'msg' => 'Cet artisan n\'est plus plus référencé sur Eldotravo' ], 410 => [ 'label' => '410 Gone', 'msg' => 'Cet artisan n\'est plus plus référencé sur Eldotravo' ],
411 => [ 'label' => '411 Length Required', 'msg' => '411 Length Required' ], 411 => [ 'label' => '411 Length Required', 'msg' => '411 Length Required' ],
412 => [ 'label' => '412 Precondition Failed', 'msg' => '412 Precondition Failed' ], 412 => [ 'label' => '412 Precondition Failed', 'msg' => '412 Precondition Failed' ],
413 => [ 'label' => '413 Request Entity Too Large', 'msg' => '413 Request Entity Too Large' ], 413 => [ 'label' => '413 Request Entity Too Large', 'msg' => '413 Request Entity Too Large' ],
414 => [ 'label' => '414 Request-URI Too Long', 'msg' => '414 Request-URI Too Long' ], 414 => [ 'label' => '414 Request-URI Too Long', 'msg' => '414 Request-URI Too Long' ],
415 => [ 'label' => '415 Unsupported Media Type', 'msg' => '415 Unsupported Media Type' ], 415 => [ 'label' => '415 Unsupported Media Type', 'msg' => '415 Unsupported Media Type' ],
416 => [ 'label' => '416 Requested Range Not Satisfiable', 'msg' => '416 Requested Range Not Satisfiable' ], 416 => [ 'label' => '416 Requested Range Not Satisfiable', 'msg' => '416 Requested Range Not Satisfiable' ],
417 => [ 'label' => '417 Expectation Failed', 'msg' => '417 Expectation Failed' ], 417 => [ 'label' => '417 Expectation Failed', 'msg' => '417 Expectation Failed' ],
418 => [ 'label' => '418 I\'m a teapot', 'msg' => '418 I\'m a teapot' ], 418 => [ 'label' => '418 I\'m a teapot', 'msg' => '418 I\'m a teapot' ],
422 => [ 'label' => '422 Unprocessable Entity', 'msg' => '422 Unprocessable Entity' ], 422 => [ 'label' => '422 Unprocessable Entity', 'msg' => '422 Unprocessable Entity' ],
423 => [ 'label' => '423 Locked', 'msg' => '423 Locked' ], 423 => [ 'label' => '423 Locked', 'msg' => '423 Locked' ],
426 => [ 'label' => '426 Upgrade Required', 'msg' => '426 Upgrade Required' ], 426 => [ 'label' => '426 Upgrade Required', 'msg' => '426 Upgrade Required' ],
428 => [ 'label' => '428 Precondition Required', 'msg' => '428 Precondition Required' ], 428 => [ 'label' => '428 Precondition Required', 'msg' => '428 Precondition Required' ],
429 => [ 'label' => '429 Too Many Requests', 'msg' => '429 Too Many Requests' ], 429 => [ 'label' => '429 Too Many Requests', 'msg' => '429 Too Many Requests' ],
431 => [ 'label' => '431 Request Header Fields Too Large', 'msg' => '431 Request Header Fields Too Large' ], 431 => [ 'label' => '431 Request Header Fields Too Large', 'msg' => '431 Request Header Fields Too Large' ],
//Server Error 5xx //Server Error 5xx
500 => [ 'label' => '500 Internal Server Error', 'msg' => 'Une erreur est survenue' ], 500 => [ 'label' => '500 Internal Server Error', 'msg' => 'Une erreur est survenue' ],
501 => [ 'label' => '501 Not Implemented', 'msg' => '501 Not Implemented' ], 501 => [ 'label' => '501 Not Implemented', 'msg' => '501 Not Implemented' ],
502 => [ 'label' => '502 Bad Gateway', 'msg' => '502 Bad Gateway' ], 502 => [ 'label' => '502 Bad Gateway', 'msg' => '502 Bad Gateway' ],
503 => [ 'label' => '503 Service Unavailable', 'msg' => '503 Service Unavailable' ], 503 => [ 'label' => '503 Service Unavailable', 'msg' => '503 Service Unavailable' ],
504 => [ 'label' => '504 Gateway Timeout', 'msg' => '504 Gateway Timeout' ], 504 => [ 'label' => '504 Gateway Timeout', 'msg' => '504 Gateway Timeout' ],
505 => [ 'label' => '505 HTTP Version Not Supported', 'msg' => '505 HTTP Version Not Supported' ], 505 => [ 'label' => '505 HTTP Version Not Supported', 'msg' => '505 HTTP Version Not Supported' ],
506 => [ 'label' => '506 Variant Also Negotiates', 'msg' => '506 Variant Also Negotiates' ], 506 => [ 'label' => '506 Variant Also Negotiates', 'msg' => '506 Variant Also Negotiates' ],
510 => [ 'label' => '510 Not Extended', 'msg' => '510 Not Extended' ], 510 => [ 'label' => '510 Not Extended', 'msg' => '510 Not Extended' ],
511 => [ 'label' => '511 Network Authentication Required', 'msg' => '511 Network Authentication Required' ] 511 => [ 'label' => '511 Network Authentication Required', 'msg' => '511 Network Authentication Required' ]
]; ];
if ( isset( $tabCode[ $ErrCode ] ) ) { if ( isset( $tabCode[ $ErrCode ] ) ) {
header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $tabCode[ $ErrCode ]['label'] ); header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' ' . $tabCode[ $ErrCode ][ 'label' ] );
if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) { if ( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) == 'xmlhttprequest' ) {
$this->throwError( 'Erreur ' . $tabCode[ $ErrCode ]['label'], 'Erreur_' . $ErrCode ); $this->throwError( 'Erreur ' . $tabCode[ $ErrCode ][ 'label' ], 'Erreur_' . $ErrCode );
} }
$erreur = $tabCode[ $ErrCode ]['msg']; $erreur = $tabCode[ $ErrCode ][ 'msg' ];
$this->addData( [ 'erreur' => $erreur ] ); $this->addData( [ 'erreur' => $erreur ] );
} else { } else {
header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $tabCode[500]['label'] ); header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' ' . $tabCode[ 500 ][ 'label' ] );
if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) { if ( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) == 'xmlhttprequest' ) {
$this->throwError( 'Erreur ' . $tabCode[500]['label'], 'Erreur_500' ); $this->throwError( 'Erreur ' . $tabCode[ 500 ][ 'label' ], 'Erreur_500' );
} }
$erreur = $tabCode[500]['msg']; $erreur = $tabCode[ 500 ][ 'msg' ];
$this->addData( [ 'erreur' => $erreur ] ); $this->addData( [ 'erreur' => $erreur ] );
} }
if ( ! empty( $message ) ) { if ( !empty( $message ) ) {
$this->addData( [ 'message' => $message ] ); $this->addData( [ 'message' => $message ] );
} }
$this->addHead( [ $this->addHead( [
'title' => 'Un erreur est survenue', 'title' => 'Un erreur est survenue',
'description' => 'Oops une erreur est survenue', 'description' => 'Oops une erreur est survenue',
'robotNoIndex' => true 'robotNoIndex' => true
] ); ] );
$this->view(); $this->view();
} }
} }

View File

@ -4,21 +4,21 @@ namespace CAUProject3Contact\Controller\Site;
class SiteRouter { class SiteRouter {
/** /**
* SiteRouter constructor. * SiteRouter constructor.
* *
* @param $pages * @param $pages
*/ */
public function __construct( $pages ) { public function __construct( $pages ) {
set_error_handler( 'errorHandler' ); set_error_handler( 'errorHandler' );
if ( $pages[0] == '' ) { if ( $pages[ 0 ] == '' ) {
new Index(); new Index();
} else { } else {
new SiteError( 404 ); new SiteError( 404 );
} }
} }
} }
?> ?>

View File

@ -6,35 +6,43 @@ use Exception;
use PDO; use PDO;
class BDD { class BDD {
const SQL_SERVER = 'sql.sanchez-mathieu.fr'; // BDD Server
const SQL_LOGIN = 'why7n0_contact'; // BDD Login
const SQL_PASSWORD = 'fC3c87Gy'; // BDD Password
const SQL_DB = 'why7n0_contact'; // BDD Name
private static $bdd; // Server BDD
// const SQL_SERVER = 'sql.sanchez-mathieu.fr'; // BDD Server
// const SQL_LOGIN = 'why7n0_contact'; // BDD Login
// const SQL_PASSWORD = 'fC3c87Gy'; // BDD Password
// const SQL_DB = 'why7n0_contact'; // BDD Name
public function __construct() { // Local BDD
try { const SQL_SERVER = 'localhost'; // BDD Server
$pdo_options = [ const SQL_LOGIN = 'root'; // BDD Login
PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, const SQL_PASSWORD = ''; // BDD Password
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4', const SQL_DB = 'contact'; // BDD Name
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
self::$bdd = new PDO( 'mysql:host=' . self::SQL_SERVER . ';dbname=' . self::SQL_DB . ';charset=utf8', private static $bdd;
self::SQL_LOGIN, self::SQL_PASSWORD, $pdo_options );
} catch ( Exception $e ) {
die( 'Erreur : ' . $e->getMessage() );
}
}
public static function instance() { public function __construct() {
return self::$bdd; try {
} $pdo_options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
public static function lastInsertId() { self::$bdd = new PDO( 'mysql:host=' . self::SQL_SERVER . ';dbname=' . self::SQL_DB . ';charset=utf8',
return self::$bdd->lastInsertId(); self::SQL_LOGIN, self::SQL_PASSWORD, $pdo_options );
} } catch ( Exception $e ) {
die( 'Erreur : ' . $e->getMessage() );
}
}
public static function instance() {
return self::$bdd;
}
public static function lastInsertId() {
return self::$bdd->lastInsertId();
}
} }
?> ?>

View File

@ -4,10 +4,11 @@ namespace CAUProject3Contact\Model;
abstract class BDTables { abstract class BDTables {
// const NOM = 'bd_nom' // const NOM = 'bd_nom'
// Ex : const ABONNEMENT = 'abonnement'; // Ex : const ABONNEMENT = 'abonnement';
const LOGS = "logs"; const LOGS = "logs";
const CONTACT = "contact";
} }
?> ?>

220
src/Model/Contact.php Normal file
View File

@ -0,0 +1,220 @@
<?php
namespace CAUProject3Contact\Model;
class Contact {
public $id;
public $firstName;
public $lastName;
public $surname;
public $email;
public $address;
public $phoneNumber;
public $birthday;
// Constructors
public function __construct( int $id = null, string $firstName = null, string $lastName = null,
string $surname = null, string $email = null, string $address = null,
string $phoneNumber = null, string $birthday = null ) {
if ( $id === null || $firstName === null || $lastName === null ) {
return;
}
$this->id = $id;
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->surname = $surname;
$this->email = $email;
$this->address = $address;
$this->phoneNumber = $phoneNumber;
$this->birthday = $birthday;
}
public static function getById( int $id ) {
$req = BDD::instance()->prepare( "SELECT * FROM " . BDTables::CONTACT .
" WHERE `id` = :id" );
$req->execute( [ "id" => $id ] );
$d = $req->fetch();
return new Contact( $d[ "id" ], $d[ "first_name" ], $d[ "last_name" ], $d[ "surname" ],
$d[ "email" ], $d[ "address" ], $d[ "phone_number" ], $d[ "birthday" ] );
}
// Getters
public static function insertNewContact( string $firstName, string $lastName, string $surname = null,
string $email = null,
string $address = null, string $phoneNumber = null,
string $birthday = null ) {
$data = [
"first_name" => $firstName,
"last_name" => $lastName,
];
if ( $surname !== null && $surname !== "" ) {
$data[ "surname" ] = $surname;
}
if ( $email !== null && $email !== "" ) {
$data[ "email" ] = $email;
}
if ( $address !== null && $address !== "" ) {
$data[ "address" ] = $address;
}
if ( $phoneNumber !== null && $phoneNumber !== "" ) {
$data[ "phone_number" ] = $phoneNumber;
}
if ( $birthday !== null && $birthday !== "" ) {
$data[ "birthday" ] = date( "Y-m-d", strtotime( $birthday ) );
}
return Model::insert( BDTables::CONTACT, $data );
}
public static function deleteContact( int $id ) {
Model::delete( BDTables::CONTACT, [ "id" => $id ] );
}
public static function getAllContact(): array {
$contacts = [];
$req = BDD::instance()->prepare( "SELECT * FROM " . BDTables::CONTACT );
$req->execute();
foreach ( $req->fetchAll() as $c ) {
$contacts[] = new Contact( $c[ "id" ], $c[ "first_name" ], $c[ "last_name" ], $c[ "surname" ],
$c[ "email" ], $c[ "address" ], $c[ "phone_number" ], $c[ "birthday" ] );
}
return ( count( $contacts ) > 0 ? $contacts : null );
}
public static function search( string $query ) {
$result = [];
$words = explode( " ", cleanString( $query ) );
$q1 = $q2 = $q3 = $q4 = "SELECT * FROM `" . BDTables::CONTACT . "` WHERE ";
$lastKey = endKey( $words );
foreach ( $words as $key => $word ) {
$normal = self::getQuerySearch( $word, [ "first_name", "last_name", "surname" ] );;
$hard = self::getQuerySearch( $word, [ "email", "address", "phone_number" ] );
$q1 .= $normal;
$q2 .= $normal;
$q3 .= $hard;
$q4 .= $hard;
if ( $key != $lastKey ) {
$q1 .= " AND ";
$q2 .= " OR ";
$q3 .= " AND ";
$q4 .= " OR ";
}
}
$req1 = BDD::instance()->prepare( $q1 );
$req2 = BDD::instance()->prepare( $q2 );
$req3 = BDD::instance()->prepare( $q3 );
$req4 = BDD::instance()->prepare( $q4 );
$req1->execute();
$req2->execute();
$req3->execute();
$req4->execute();
$tmp1 = $req1->fetchAll();
$tmp2 = filterArrays( $tmp1, $req2->fetchAll() );
$tmp3 = filterArrays( $tmp1, filterArrays( $tmp2, $req3->fetchAll() ) );
$tmp4 = filterArrays( $tmp1, filterArrays( $tmp2, filterArrays( $tmp3, $req4->fetchAll() ) ) );
if ( count( $tmp1 ) > 0 || count( $tmp2 ) > 0 || count( $tmp3 ) > 0 || count( $tmp4 ) > 0 ) {
$result[ "1" ] = ( count( $tmp1 ) > 0 ? $tmp1 : null );
$result[ "2" ] = ( count( $tmp2 ) > 0 ? $tmp2 : null );
$result[ "3" ] = ( count( $tmp3 ) > 0 ? $tmp3 : null );
$result[ "4" ] = ( count( $tmp4 ) > 0 ? $tmp4 : null );
return $result;
}
return null;
}
private static function getQuerySearch( string $word, array $fields ): string {
$str = '';
$i = 0;
foreach ( $fields as $field ) {
if ( $i === 0 ) {
$str .= "(";
} else {
$str .= " OR ";
}
$str .= "`" . $field . "` LIKE '%" . $word . "%'";
$i++;
}
$str .= ')';
return $str;
}
/**
* @return string
*/
public function getFirstName(): string {
return $this->firstName;
}
/**
* @return string
*/
public function getLastName(): string {
return $this->lastName;
}
/**
* @return string
*/
public function getSurname() {
return $this->surname;
}
// Method
/**
* @return string
*/
public function getEmail() {
return $this->email;
}
// Static functions
/**
* @return string
*/
public function getAddress() {
return $this->address;
}
/**
* @return string
*/
public function getPhoneNumber() {
return $this->phoneNumber;
}
/**
* @return string
*/
public function getBirthday() {
return $this->birthday;
}
public function updateContact( array $data ) {
foreach ( $data as $key => $value ) {
$this->{$key} = $value;
}
Model::update( BDTables::CONTACT, $data, "id", $this->getId() );
}
/**
* @return int
*/
public function getId(): int {
return $this->id;
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -6,179 +6,180 @@ use PDO;
class Logs { class Logs {
const ERROR_LEVEL = [ const ERROR_LEVEL = [
1 => 'E_ERROR', 1 => 'E_ERROR',
2 => 'E_WARNING', 2 => 'E_WARNING',
4 => 'E_PARSE', 4 => 'E_PARSE',
8 => 'E_NOTICE', 8 => 'E_NOTICE',
16 => 'E_CORE_ERROR', 16 => 'E_CORE_ERROR',
32 => 'E_CORE_WARNING', 32 => 'E_CORE_WARNING',
64 => 'E_COMPILE_ERROR', 64 => 'E_COMPILE_ERROR',
128 => 'E_COMPILE_WARNING', 128 => 'E_COMPILE_WARNING',
256 => 'E_USER_ERROR', 256 => 'E_USER_ERROR',
512 => 'E_USER_WARNING', 512 => 'E_USER_WARNING',
1024 => 'E_USER_NOTICE', 1024 => 'E_USER_NOTICE',
2048 => 'E_STRICT', 2048 => 'E_STRICT',
4096 => 'E_RECOVERABLE_ERROR', 4096 => 'E_RECOVERABLE_ERROR',
8192 => 'E_DEPRECATED', 8192 => 'E_DEPRECATED',
16384 => 'E_USER_DEPRECATED', 16384 => 'E_USER_DEPRECATED',
32767 => 'E_ALL' 32767 => 'E_ALL'
]; ];
public $id; public $id;
public $level; public $level;
public $message; public $message;
public $file; public $file;
public $line; public $line;
public $date; public $date;
/** /**
* Logs constructor. * Logs constructor.
* *
* @param int|null $id * @param int|null $id
* @param string|null $level * @param string|null $level
* @param string|null $message * @param string|null $message
* @param string|null $file * @param string|null $file
* @param string|null $line * @param string|null $line
* @param string|null $date * @param string|null $date
*/ */
public function __construct( int $id = null, string $level = null, string $message = null, string $file = null, string $line = null, string $date = null ) { public function __construct( int $id = null, string $level = null, string $message = null, string $file = null,
if ( $id === null ) { string $line = null, string $date = null ) {
return; if ( $id === null ) {
} return;
$this->id = $id; }
$this->level = $level; $this->id = $id;
$this->message = $message; $this->level = $level;
$this->file = $file; $this->message = $message;
$this->line = $line; $this->file = $file;
$this->date = $date; $this->line = $line;
} $this->date = $date;
}
public static function insert( $level, $message, $file, $line, $date ) { public static function insert( $level, $message, $file, $line, $date ) {
Model::insert( BDTables::LOGS, [ Model::insert( BDTables::LOGS, [
'level' => $level, 'level' => $level,
'message' => $message, 'message' => $message,
'file' => $file, 'file' => $file,
'line' => $line, 'line' => $line,
'date' => date( "Y-m-d H:i:s", strtotime( $date ) ) 'date' => date( "Y-m-d H:i:s", strtotime( $date ) )
] ); ] );
} }
/** /**
* Retourne un tableau des derniers logs (limite en param) * Retourne un tableau des derniers logs (limite en param)
* *
* @param int $limit * @param int $limit
* *
* @return array * @return array
*/ */
public static function getLastLogs( int $limit ) { public static function getLastLogs( int $limit ) {
$req = BDD::instance()->prepare( 'SELECT * $req = BDD::instance()->prepare( 'SELECT *
FROM ' . BDTables::LOGS . ' FROM ' . BDTables::LOGS . '
ORDER BY date DESC ORDER BY date DESC
LIMIT :limit' ); LIMIT :limit' );
$req->bindValue( 'limit', $limit, PDO::PARAM_INT ); $req->bindValue( 'limit', $limit, PDO::PARAM_INT );
$req->execute(); $req->execute();
$return = []; $return = [];
foreach ( $req->fetchAll() as $l ) { foreach ( $req->fetchAll() as $l ) {
$log = new Logs( $l['id'], $l['level'], $l['message'], $l['file'], $l['line'], $l['date'] ); $log = new Logs( $l[ 'id' ], $l[ 'level' ], $l[ 'message' ], $l[ 'file' ], $l[ 'line' ], $l[ 'date' ] );
$return[] = $log; $return[] = $log;
} }
return $return; return $return;
} }
/** /**
* @return int * @return int
*/ */
public function getId() { public function getId() {
return $this->id; return $this->id;
} }
/** /**
* @param int $id * @param int $id
*/ */
public function setId( $id ) { public function setId( $id ) {
$this->id = $id; $this->id = $id;
} }
/** /**
* @return string * @return string
*/ */
public function getLevel() { public function getLevel() {
return $this->level; return $this->level;
} }
/** /**
* @param string $level * @param string $level
*/ */
public function setLevel( $level ) { public function setLevel( $level ) {
$this->level = $level; $this->level = $level;
} }
/** /**
* @return string * @return string
*/ */
public function getMessage() { public function getMessage() {
return htmlspecialchars( $this->message ); return htmlspecialchars( $this->message );
} }
/** /**
* @param string $message * @param string $message
*/ */
public function setMessage( $message ) { public function setMessage( $message ) {
$this->message = $message; $this->message = $message;
} }
/** /**
* @return string * @return string
*/ */
public function getFile() { public function getFile() {
return htmlspecialchars( $this->file ); return htmlspecialchars( $this->file );
} }
/** /**
* @param string $file * @param string $file
*/ */
public function setFile( $file ) { public function setFile( $file ) {
$this->file = $file; $this->file = $file;
} }
/** /**
* @return string * @return string
*/ */
public function getLine() { public function getLine() {
return htmlspecialchars( $this->line ); return htmlspecialchars( $this->line );
} }
/** /**
* @param string $line * @param string $line
*/ */
public function setLine( $line ) { public function setLine( $line ) {
$this->line = $line; $this->line = $line;
} }
/** /**
* @return string * @return string
*/ */
public function getDate() { public function getDate() {
return $this->date; return $this->date;
} }
/** /**
* @param string $date * @param string $date
*/ */
public function setDate( $date ) { public function setDate( $date ) {
$this->date = $date; $this->date = $date;
} }
/** /**
* Retourne le type d'erreur en string (label) * Retourne le type d'erreur en string (label)
* @return string * @return string
*/ */
public function getErrorLabel() { public function getErrorLabel() {
return htmlspecialchars( self::ERROR_LEVEL[ $this->level ] ); return htmlspecialchars( self::ERROR_LEVEL[ $this->level ] );
} }
} }
?> ?>

View File

@ -4,47 +4,63 @@ namespace CAUProject3Contact\Model;
class Model { class Model {
/** /**
* Crée une reqette d'insertion en base àpartir du nom de la table et d'un tableau associatif et l'exécute * Crée une reqette d'insertion en base àpartir du nom de la table et d'un tableau associatif et l'exécute
* *
* @param string $tableName * @param string $tableName
* @param array $data * @param array $data
* *
* @return int lastInsertId * @return int lastInsertId
*/ */
public static function insert( string $tableName, array $data ) { public static function insert( string $tableName, array $data ) {
$req = BDD::instance()->prepare( 'INSERT INTO ' . $tableName . ' (' . implode( ', ', array_keys( $data ) ) . ') $req = BDD::instance()->prepare( 'INSERT INTO ' . $tableName . ' (' . implode( ', ', array_keys( $data ) ) . ')
VALUES (' . ':' . implode( ', :', array_keys( $data ) ) . ')' ); VALUES (' . ':' . implode( ', :', array_keys( $data ) ) . ')' );
$req->execute( $data ); $req->execute( $data );
return BDD::lastInsertId(); return BDD::lastInsertId();
} }
/** /**
* Met à jour les données d'une ligne d'un table données * Met à jour les données d'une ligne d'un table données
* *
* @param string $tableName * @param string $tableName
* @param array $data * @param array $data
* @param string $idColumn * @param string $idColumn
* @param int $idValue * @param int $idValue
*/ */
public static function update( string $tableName, array $data, string $idColumn, int $idValue ) { public static function update( string $tableName, array $data, string $idColumn, int $idValue ) {
$reqStr = 'UPDATE ' . $tableName . ' SET '; $reqStr = 'UPDATE ' . $tableName . ' SET ';
$lastKey = endKey( $data ); $lastKey = endKey( $data );
foreach ( $data as $key => $value ) { foreach ( $data as $key => $value ) {
$reqStr .= $key . ' = :' . $key; $reqStr .= $key . ' = :' . $key;
if ( $key != $lastKey ) { if ( $key != $lastKey ) {
$reqStr .= ', '; $reqStr .= ', ';
} }
} }
$reqStr .= ' WHERE ' . $idColumn . ' = :' . $idColumn; $reqStr .= ' WHERE ' . $idColumn . ' = :' . $idColumn;
$data[ $idColumn ] = $idValue; $data[ $idColumn ] = $idValue;
//echo $reqStr; exit(); //echo $reqStr; exit();
$req = BDD::instance()->prepare( $reqStr );
$req->execute( $data );
}
public static function delete( string $tableName, array $conditions ) {
$reqStr = 'DELETE FROM ' . $tableName . ' WHERE ';
$lastKey = endKey( $conditions );
foreach ( $conditions as $key => $value ) {
$reqStr .= $key . ' = :' . $key;
if ( $key != $lastKey ) {
$reqStr .= ' AND ';
}
}
$req = BDD::instance()->prepare( $reqStr );
$req->execute( $conditions );
}
$req = BDD::instance()->prepare( $reqStr );
$req->execute( $data );
}
} }
?> ?>

View File

@ -1,3 +1,39 @@
<div> <div class="section scrollspy">
Bonjour 2
<div class="row">
<div class="col s12 main-container">
<table class="highlight centered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Surname</th>
<th>Email</th>
<th>Address</th>
<th>Phone Number</th>
<th>Birthday</th>
</tr>
</thead>
<tbody>
<?php
foreach ( $contacts as $contact ) {
echo "<tr>";
echo " <td>" . $contact->getFirstName() . "</td>";
echo " <td>" . $contact->getLastName() . "</td>";
echo " <td>" . ( $contact->getSurname() ? $contact->getSurname() : "" ) . "</td>";
echo " <td>" . ( $contact->getEmail() ? $contact->getEmail() : "" ) . "</td>";
echo " <td>" . ( $contact->getAddress() ? $contact->getAddress() : "" ) . "</td>";
echo " <td>" . ( $contact->getPhoneNumber() ? $contact->getPhoneNumber() : "" ) . "</td>";
echo " <td>" . ( $contact->getBirthday() ? date( "Y-m-d", strtotime( $contact->getBirthday() ) ) : "" ) . "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div> </div>
<script>
let contacts = <?= json_encode( $contacts ) ?>;
</script>

View File

@ -1,5 +1,32 @@
<script src="/js/jquery-3.2.1.min.js"></script> </div>
<script src="/js/javascript.js?v=<?= CAUProject3Contact\Config::SITE_JS_VERSION ?>"></script> </main>
<div id="modal" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Add new contact</h4>
<p>Test</p>
</div>
<div class="modal-footer">
<a class="waves-effect waves-green btn-flat">Validate</a>
<a class="waves-effect waves-red btn-flat">Cancel</a>
</div>
</div>
<footer class="page-footer blue">
<div class="footer-copyright">
<div class="container">
Made by <a class="blue-text text-lighten-3" target="_blank" href="https://www.sanchez-mathieu.fr">Mathieu
Sanchez</a>
</div>
</div>
</footer>
<script src="/js/jquery-3.3.1.min.js"></script>
<script async src="/js/materialize.min.js"></script>
<script async src="/js/javascript.js?v=<?= CAUProject3Contact\Config::SITE_JS_VERSION ?>"></script>
<link href="/css/materialize.min.css" rel="stylesheet">
<link href="/css/style.css?v=<?= CAUProject3Contact\Config::SITE_CSS_VERSION ?>" rel="stylesheet"> <link href="/css/style.css?v=<?= CAUProject3Contact\Config::SITE_CSS_VERSION ?>" rel="stylesheet">
</body> </body>

View File

@ -1,41 +1,66 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="fr"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="manifest" href="/manifest.json"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- <link rel="manifest" href="/manifest.json">-->
<meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" id="status-bar" content="white-translucent"> <meta name="apple-mobile-web-app-status-bar-style" id="status-bar" content="white-translucent">
<meta name="format-detection" content="telephone=no"> <meta name="format-detection" content="telephone=no">
<meta name="author" content="Eldotravo"> <meta name="author" content="Mathieu Sanchez">
<title><?= $this->head['title'] ?></title> <title><?= $this->head[ 'title' ] ?></title>
<meta name="description" content="<?= $this->head['description'] ?>"> <meta name="description" content="<?= $this->head[ 'description' ] ?>">
<meta property="og:title" content="<?= $this->head['title'] ?>"/> <meta property="og:title" content="<?= $this->head[ 'title' ] ?>"/>
<meta property="og:description" content="<?= $this->head['description'] ?>"/> <meta property="og:description" content="<?= $this->head[ 'description' ] ?>"/>
<meta property="og:url" content="https://<?= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ?>"/> <meta property="og:url" content="https://<?= $_SERVER[ 'SERVER_NAME' ] . $_SERVER[ 'REQUEST_URI' ] ?>"/>
<meta property="og:image" content="https://<?= $_SERVER['SERVER_NAME'] . \CAUProject3Contact\Config::FAVICON_PATH ?>"/> <meta property="og:image"
content="https://<?= $_SERVER[ 'SERVER_NAME' ] . \CAUProject3Contact\Config::FAVICON_PATH ?>"/>
<!-- <meta property="fb:app_id" content="1000452166691027" /> --> <!-- <meta property="fb:app_id" content="1000452166691027" /> -->
<link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700%7CRoboto+Condensed:400,700%7CMaterial+Icons' <link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700%7CRoboto+Condensed:400,700%7CMaterial+Icons'
rel='stylesheet' type='text/css'> rel='stylesheet' type='text/css'>
<link href="/css/theme.css?v=<?= CAUProject3Contact\Config::SITE_CSS_VERSION ?>" rel="stylesheet"> <link rel="image_src" href="<?= CAUProject3Contact\Config::FAVICON_PATH ?>"/>
<link href="/css/select2.css" rel="stylesheet"> <link rel="icon" type="image/ico" href="<?= CAUProject3Contact\Config::FAVICON_PATH ?>"/>
<link rel="image_src" href="<?php \CAUProject3Contact\Config::FAVICON_PATH ?>"/>
<link rel="icon" type="image/png" href="<?php \CAUProject3Contact\Config::FAVICON_PATH ?>"/>
<meta name="theme-color" content="#ffffff"> <meta name="theme-color" content="#ffffff">
<?php if ( isset( $this->head['robotNoIndex'] ) && $this->head['robotNoIndex'] == true ) { ?> <?php if ( isset( $this->head[ 'robotNoIndex' ] ) && $this->head[ 'robotNoIndex' ] == true ) { ?>
<meta name="robots" content="noindex"/> <meta name="robots" content="noindex"/>
<?php } ?> <?php } ?>
</head> </head>
<body> <body>
<nav class="blue" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" class="brand-logo">
<img src="/img/logo.png" alt="Logo of Your Contact" height="64px"/>
</a>
<ul class="right hide-on-med-and-down">
<li>
<a class="nav-search"><input type="text" placeholder="Search Contact" id="search" name="search"/></a>
</li>
<li data-position="bottom" data-tooltip="Add a new contact">
<a class="nav-add"><img class="add-contacts" src="/img/add-contacts.png" alt="Add contact"></a>
</li>
</ul>
<!-- <ul id="nav-mobile" class="sidenav">-->
<!-- <li><a href="#">Navbar Link</a></li>-->
<!-- </ul>-->
<!-- <a href="#" data-target="nav-mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a>-->
</div>
</nav>
<main>
<div class="container">

View File

@ -12,36 +12,36 @@ include( 'src/lib/mail/PHPMailerAutoload.php' );
*/ */
function formatURL( string $str, $encoding = 'utf-8' ) { function formatURL( string $str, $encoding = 'utf-8' ) {
$str = str_replace( "+", "_plus_", $str ); $str = str_replace( "+", "_plus_", $str );
$str = str_replace( "%", "_pourcent_", $str ); $str = str_replace( "%", "_pourcent_", $str );
$str = str_replace( "&", "_et_", $str ); $str = str_replace( "&", "_et_", $str );
//on remplace les apotrophes et espaces par des underscore //on remplace les apotrophes et espaces par des underscore
$str = str_replace( array( "'", " ", "," ), "_", $str ); $str = str_replace( array( "'", " ", "," ), "_", $str );
$str = str_replace( "__", "_", $str ); $str = str_replace( "__", "_", $str );
// transformer les caractères accentués en entités HTML // transformer les caractères accentués en entités HTML
$str = htmlentities( $str, ENT_NOQUOTES, $encoding ); $str = htmlentities( $str, ENT_NOQUOTES, $encoding );
// remplacer les entités HTML pour avoir juste le premier caractères non accentués // remplacer les entités HTML pour avoir juste le premier caractères non accentués
// Exemple : "&ecute;" => "e", "&Ecute;" => "E", "Ã " => "a" ... // Exemple : "&ecute;" => "e", "&Ecute;" => "E", "Ã " => "a" ...
$str = preg_replace( '#&([A-za-z])(?:acute|grave|cedil|circ|orn|ring|slash|th|tilde|uml);#', '\1', $str ); $str = preg_replace( '#&([A-za-z])(?:acute|grave|cedil|circ|orn|ring|slash|th|tilde|uml);#', '\1', $str );
// Remplacer les ligatures tel que : Œ, Æ ... // Remplacer les ligatures tel que : Œ, Æ ...
// Exemple "Å“" => "oe" // Exemple "Å“" => "oe"
$str = preg_replace( '#&([A-za-z]{2})(?:lig);#', '\1', $str ); $str = preg_replace( '#&([A-za-z]{2})(?:lig);#', '\1', $str );
// Supprimer tout le reste // Supprimer tout le reste
//$str = preg_replace('#&[^;]+;#', '', $str); //$str = preg_replace('#&[^;]+;#', '', $str);
$str = str_replace( array( "#", "&", "[", "^", ";", "]" ), '', $str ); $str = str_replace( array( "#", "&", "[", "^", ";", "]" ), '', $str );
//on passe tout en minuscule //on passe tout en minuscule
$str = strtolower( $str ); $str = strtolower( $str );
if ( substr( $str, - 1 ) == '_' ) { if ( substr( $str, -1 ) == '_' ) {
$str = substr( $str, 0, - 1 ); $str = substr( $str, 0, -1 );
} }
return $str; return $str;
} }
/** /**
@ -57,55 +57,55 @@ function formatURL( string $str, $encoding = 'utf-8' ) {
*/ */
function darkroom( $img, $to, $width = 0, $height = 0, $quality = 100, $useGD = true ) { function darkroom( $img, $to, $width = 0, $height = 0, $quality = 100, $useGD = true ) {
$dimensions = getimagesize( $img ); $dimensions = getimagesize( $img );
$ratio = $dimensions[0] / $dimensions[1]; $ratio = $dimensions[ 0 ] / $dimensions[ 1 ];
// Calcul des dimensions si 0 passé en paramètre // Calcul des dimensions si 0 passé en paramètre
if ( $width == 0 && $height == 0 ) { if ( $width == 0 && $height == 0 ) {
$width = $dimensions[0]; $width = $dimensions[ 0 ];
$height = $dimensions[1]; $height = $dimensions[ 1 ];
} else if ( $height == 0 ) { } else if ( $height == 0 ) {
$height = round( $width / $ratio ); $height = round( $width / $ratio );
} else if ( $width == 0 ) { } else if ( $width == 0 ) {
$width = round( $height * $ratio ); $width = round( $height * $ratio );
} }
if ( $dimensions[0] > ( $width / $height ) * $dimensions[1] ) { if ( $dimensions[ 0 ] > ( $width / $height ) * $dimensions[ 1 ] ) {
$dimY = $height; $dimY = $height;
$dimX = round( $height * $dimensions[0] / $dimensions[1] ); $dimX = round( $height * $dimensions[ 0 ] / $dimensions[ 1 ] );
} }
if ( $dimensions[0] < ( $width / $height ) * $dimensions[1] ) { if ( $dimensions[ 0 ] < ( $width / $height ) * $dimensions[ 1 ] ) {
$dimX = $width; $dimX = $width;
$dimY = round( $width * $dimensions[1] / $dimensions[0] ); $dimY = round( $width * $dimensions[ 1 ] / $dimensions[ 0 ] );
} }
if ( $dimensions[0] == ( $width / $height ) * $dimensions[1] ) { if ( $dimensions[ 0 ] == ( $width / $height ) * $dimensions[ 1 ] ) {
$dimX = $width; $dimX = $width;
$dimY = $height; $dimY = $height;
} }
// Création de l'image avec la librairie GD // Création de l'image avec la librairie GD
if ( $useGD ) { if ( $useGD ) {
$pattern = imagecreatetruecolor( $width, $height ); $pattern = imagecreatetruecolor( $width, $height );
$type = mime_content_type( $img ); $type = mime_content_type( $img );
switch ( substr( $type, 6 ) ) { switch ( substr( $type, 6 ) ) {
case 'jpeg': case 'jpeg':
$image = imagecreatefromjpeg( $img ); $image = imagecreatefromjpeg( $img );
break; break;
case 'gif': case 'gif':
$image = imagecreatefromgif( $img ); $image = imagecreatefromgif( $img );
break; break;
case 'png': case 'png':
$image = imagecreatefrompng( $img ); $image = imagecreatefrompng( $img );
break; break;
} }
imagecopyresampled( $pattern, $image, 0, 0, 0, 0, $dimX, $dimY, $dimensions[0], $dimensions[1] ); imagecopyresampled( $pattern, $image, 0, 0, 0, 0, $dimX, $dimY, $dimensions[ 0 ], $dimensions[ 1 ] );
imagedestroy( $image ); imagedestroy( $image );
imagejpeg( $pattern, $to, $quality ); imagejpeg( $pattern, $to, $quality );
return true; return true;
} }
return true; return true;
} }
/** /**
@ -119,20 +119,20 @@ function darkroom( $img, $to, $width = 0, $height = 0, $quality = 100, $useGD =
* @return bool|void * @return bool|void
*/ */
function errorHandler( $errno, $errstr, $errfile, $errline ) { function errorHandler( $errno, $errstr, $errfile, $errline ) {
if ( ! ( error_reporting() & $errno ) ) { if ( !( error_reporting() & $errno ) ) {
// Ce code d'erreur n'est pas inclus dans error_reporting() // Ce code d'erreur n'est pas inclus dans error_reporting()
return; return;
} }
// Insertion des logs // Insertion des logs
\CAUProject3Contact\Model\Logs::insert( $errno, $errstr, $errfile, $errline, date( 'Y-m-d H:i:s' ) ); \CAUProject3Contact\Model\Logs::insert( $errno, $errstr, $errfile, $errline, date( 'Y-m-d H:i:s' ) );
ob_clean(); ob_clean();
new \CAUProject3Contact\Controller\Site\SiteError( 500 ); new \CAUProject3Contact\Controller\Site\SiteError( 500 );
/* Ne pas exécuter le gestionnaire interne de PHP */ /* Ne pas exécuter le gestionnaire interne de PHP */
return; return;
} }
/** /**
@ -141,87 +141,87 @@ function errorHandler( $errno, $errstr, $errfile, $errline ) {
*/ */
function getBrowser() { function getBrowser() {
$u_agent = $_SERVER['HTTP_USER_AGENT']; $u_agent = $_SERVER[ 'HTTP_USER_AGENT' ];
$bname = 'Unknown'; $bname = 'Unknown';
$platform = 'Unknown'; $platform = 'Unknown';
$ub = ""; $ub = "";
//First get the platform? //First get the platform?
if ( preg_match( '/android/i', $u_agent ) || preg_match( '/Android/i', $u_agent ) ) { if ( preg_match( '/android/i', $u_agent ) || preg_match( '/Android/i', $u_agent ) ) {
$platform = 'android'; $platform = 'android';
} else if ( preg_match( '/linux/i', $u_agent ) ) { } else if ( preg_match( '/linux/i', $u_agent ) ) {
$platform = 'linux'; $platform = 'linux';
} else if ( preg_match( '/macintosh|mac os x/i', $u_agent ) ) { } else if ( preg_match( '/macintosh|mac os x/i', $u_agent ) ) {
$platform = 'mac'; $platform = 'mac';
} else if ( preg_match( '/windows|win32/i', $u_agent ) ) { } else if ( preg_match( '/windows|win32/i', $u_agent ) ) {
$platform = 'windows'; $platform = 'windows';
} }
if ( strstr( $u_agent, 'mobile' ) || strstr( $u_agent, 'Mobile' ) ) { if ( strstr( $u_agent, 'mobile' ) || strstr( $u_agent, 'Mobile' ) ) {
$platform .= ' mobile'; $platform .= ' mobile';
} }
// Next get the name of the useragent yes seperately and for good reason // Next get the name of the useragent yes seperately and for good reason
if ( preg_match( '/MSIE/i', $u_agent ) && ! preg_match( '/Opera/i', $u_agent ) ) { if ( preg_match( '/MSIE/i', $u_agent ) && !preg_match( '/Opera/i', $u_agent ) ) {
$bname = 'Internet Explorer'; $bname = 'Internet Explorer';
$ub = "MSIE"; $ub = "MSIE";
} else if ( preg_match( '/Edge/i', $u_agent ) ) { } else if ( preg_match( '/Edge/i', $u_agent ) ) {
$bname = 'Microsoft Edge'; $bname = 'Microsoft Edge';
$ub = "Edge"; $ub = "Edge";
} else if ( preg_match( '/Trident/i', $u_agent ) ) { } else if ( preg_match( '/Trident/i', $u_agent ) ) {
$bname = 'Internet Explorer'; $bname = 'Internet Explorer';
$ub = "rv"; $ub = "rv";
} else if ( preg_match( '/Firefox/i', $u_agent ) ) { } else if ( preg_match( '/Firefox/i', $u_agent ) ) {
$bname = 'Mozilla Firefox'; $bname = 'Mozilla Firefox';
$ub = "Firefox"; $ub = "Firefox";
} else if ( preg_match( '/Chrome/i', $u_agent ) ) { } else if ( preg_match( '/Chrome/i', $u_agent ) ) {
$bname = 'Google Chrome'; $bname = 'Google Chrome';
$ub = "Chrome"; $ub = "Chrome";
} else if ( preg_match( '/Safari/i', $u_agent ) ) { } else if ( preg_match( '/Safari/i', $u_agent ) ) {
$bname = 'Apple Safari'; $bname = 'Apple Safari';
$ub = "Safari"; $ub = "Safari";
} else if ( preg_match( '/Opera/i', $u_agent ) ) { } else if ( preg_match( '/Opera/i', $u_agent ) ) {
$bname = 'Opera'; $bname = 'Opera';
$ub = "Opera"; $ub = "Opera";
} else if ( preg_match( '/Netscape/i', $u_agent ) ) { } else if ( preg_match( '/Netscape/i', $u_agent ) ) {
$bname = 'Netscape'; $bname = 'Netscape';
$ub = "Netscape"; $ub = "Netscape";
} }
// finally get the correct version number // finally get the correct version number
// Added "|:" // Added "|:"
$known = array( 'Version', $ub, 'other' ); $known = array( 'Version', $ub, 'other' );
$pattern = '#(?<browser>' . join( '|', $known ) . ')[/|: ]+(?<version>[0-9.|a-zA-Z.]*)#'; $pattern = '#(?<browser>' . join( '|', $known ) . ')[/|: ]+(?<version>[0-9.|a-zA-Z.]*)#';
if ( ! preg_match_all( $pattern, $u_agent, $matches ) ) { if ( !preg_match_all( $pattern, $u_agent, $matches ) ) {
// we have no matching number just continue // we have no matching number just continue
} }
// see how many we have // see how many we have
$i = count( $matches['browser'] ); $i = count( $matches[ 'browser' ] );
if ( $i != 1 ) { if ( $i != 1 ) {
//we will have two since we are not using 'other' argument yet //we will have two since we are not using 'other' argument yet
//see if version is before or after the name //see if version is before or after the name
if ( strripos( $u_agent, "Version" ) < strripos( $u_agent, $ub ) ) { if ( strripos( $u_agent, "Version" ) < strripos( $u_agent, $ub ) ) {
$version = $matches['version'][0]; $version = $matches[ 'version' ][ 0 ];
} else { } else {
$version = $matches['version'][1]; $version = $matches[ 'version' ][ 1 ];
} }
} else { } else {
$version = $matches['version'][0]; $version = $matches[ 'version' ][ 0 ];
} }
// check if we have a number // check if we have a number
if ( $version == null || $version == "" ) { if ( $version == null || $version == "" ) {
$version = "?"; $version = "?";
} }
return array( return array(
'userAgent' => $u_agent, 'userAgent' => $u_agent,
'platform' => $platform, 'platform' => $platform,
'version' => $version, 'version' => $version,
'pattern' => $pattern, 'pattern' => $pattern,
'name' => $bname 'name' => $bname
); );
} }
/** /**
@ -231,15 +231,15 @@ function getBrowser() {
* @return int * @return int
*/ */
function getLimitWord( $string, $limit ) { function getLimitWord( $string, $limit ) {
$i = $limit; $i = $limit;
if ( ! isset( $string ) || empty( $string ) ) { if ( !isset( $string ) || empty( $string ) ) {
return 0; return 0;
} }
while ( $i > 0 && $string[ $i ] != ' ' ) { while ( $i > 0 && $string[ $i ] != ' ' ) {
$i --; $i--;
} }
return $i; return $i;
} }
/** /**
@ -329,38 +329,38 @@ function email(array $destinataires, string $subject, string $body, string $aute
* @return bool * @return bool
*/ */
function rotateImage( string $file, int $angle, string $newName ) { function rotateImage( string $file, int $angle, string $newName ) {
// Initialisation variable pou test futur // Initialisation variable pou test futur
$image = null; $image = null;
$type = mime_content_type( $file ); $type = mime_content_type( $file );
// Création ressources en fonction de l'image // Création ressources en fonction de l'image
switch ( substr( $type, 6 ) ) { switch ( substr( $type, 6 ) ) {
case 'jpeg': case 'jpeg':
$image = imagecreatefromjpeg( $file ); $image = imagecreatefromjpeg( $file );
break; break;
case 'png': case 'png':
$image = imagecreatefrompng( $file ); $image = imagecreatefrompng( $file );
break; break;
} }
// Si format image non prit en charge // Si format image non prit en charge
if ( $image == null ) { if ( $image == null ) {
return false; return false;
} }
// Rotation de l'image // Rotation de l'image
$rotate = imagerotate( $image, $angle, 0 ); $rotate = imagerotate( $image, $angle, 0 );
// On recrée l'image au format de base // On recrée l'image au format de base
switch ( substr( $type, 6 ) ) { switch ( substr( $type, 6 ) ) {
case 'jpeg': case 'jpeg':
imagejpeg( $rotate, $file ); imagejpeg( $rotate, $file );
break; break;
case 'png': case 'png':
imagepng( $rotate, $file ); imagepng( $rotate, $file );
break; break;
} }
imagedestroy( $image ); imagedestroy( $image );
imagedestroy( $rotate ); imagedestroy( $rotate );
rename( $file, $newName ); rename( $file, $newName );
return true; return true;
} }
/** /**
@ -369,34 +369,38 @@ function rotateImage( string $file, int $angle, string $newName ) {
* @return array * @return array
* Clean toutes les strings dans array en récursif, et filtre pour n'avoir qu'un espaces entre chaque mot * Clean toutes les strings dans array en récursif, et filtre pour n'avoir qu'un espaces entre chaque mot
*/ */
function cleanArray( array $data ) { function cleanArray( array $data ): array {
if ( ! empty( $data ) ) { if ( !empty( $data ) ) {
foreach ( $data as $key => $donnée ) { foreach ( $data as $key => $value ) {
switch ( gettype( $donnée ) ) { switch ( gettype( $value ) ) {
case 'string': case 'string':
if ( ! empty( $donnée ) ) { if ( !empty( $str ) ) {
$new_string = ''; $data[ $key ] = cleanString( $value );
foreach ( explode( ' ', trim( $donnée ) ) as $str ) { }
if ( ! empty( $str ) ) { break;
if ( $new_string != '' ) { case 'array':
$new_string .= ' '; if ( !empty( $value ) ) {
} $data[ $key ] = cleanArray( $value );
$new_string .= $str; }
} break;
} }
$data[ $key ] = $new_string; }
} }
break;
case 'array':
if ( ! empty( $donnée ) ) {
$data[ $key ] = cleanArray( $donnée );
}
break;
}
}
}
return $data; return $data;
}
function cleanString( string $str ): string {
$newStr = '';
foreach ( explode( ' ', trim( $str ) ) as $word ) {
if ( !empty( $word ) && $word != '' ) {
if ( $newStr != '' ) {
$newStr .= ' ';
}
$newStr .= $word;
}
}
return $newStr;
} }
/** /**
@ -405,9 +409,27 @@ function cleanArray( array $data ) {
* @return mixed * @return mixed
*/ */
function endKey( $array ) { function endKey( $array ) {
end( $array ); end( $array );
return key( $array ); return key( $array );
}
function filterArrays( $array1, $array2 ): array {
$newArray = [];
foreach ( $array2 as $item2 ) {
$add = true;
foreach ( $array1 as $item1 ) {
if ( $item2[ "id" ] == $item1[ "id" ] ) {
$add = false;
}
}
if ( $add ) {
$newArray[] = $item2;
}
}
return $newArray;
} }
?> ?>

View File

@ -23,27 +23,27 @@
* @param string $classname The name of the class to load * @param string $classname The name of the class to load
*/ */
function PHPMailerAutoload( $classname ) { function PHPMailerAutoload( $classname ) {
//Can't use __DIR__ as it's only in PHP 5.3+ //Can't use __DIR__ as it's only in PHP 5.3+
$filename = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'class.' . strtolower( $classname ) . '.php'; $filename = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'class.' . strtolower( $classname ) . '.php';
if ( is_readable( $filename ) ) { if ( is_readable( $filename ) ) {
require $filename; require $filename;
} }
} }
if ( version_compare( PHP_VERSION, '5.1.2', '>=' ) ) { if ( version_compare( PHP_VERSION, '5.1.2', '>=' ) ) {
//SPL autoloading was introduced in PHP 5.1.2 //SPL autoloading was introduced in PHP 5.1.2
if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) ) { if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) ) {
spl_autoload_register( 'PHPMailerAutoload', true, true ); spl_autoload_register( 'PHPMailerAutoload', true, true );
} else { } else {
spl_autoload_register( 'PHPMailerAutoload' ); spl_autoload_register( 'PHPMailerAutoload' );
} }
} else { } else {
/** /**
* Fall back to traditional autoload for old PHP versions * Fall back to traditional autoload for old PHP versions
* *
* @param string $classname The name of the class to load * @param string $classname The name of the class to load
*/ */
function __autoload( $classname ) { function __autoload( $classname ) {
PHPMailerAutoload( $classname ); PHPMailerAutoload( $classname );
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//FR" "http://www.w3.org/TR/html4/loose.dtd"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//FR" "http://www.w3.org/TR/html4/loose.dtd">
<html> <html>
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head> </head>
<body class="body" style="background-color: whitesmoke !important;padding: 40px 0;line-height: 22px;width: 100%;"> <body class="body" style="background-color: whitesmoke !important;padding: 40px 0;line-height: 22px;width: 100%;">
<div class="contain" <div class="contain"

13
static/css/materialize.min.css vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,55 +1,37 @@
html, body, div, span, applet, object, iframe, main {
h1, h2, h3, h4, h5, h6, p, blockquote, pre, background: #F1F1F1;
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
} }
/* HTML5 display-role reset for older browsers */ .nav-add {
article, aside, details, figcaption, figure, padding-top: 12px;
footer, header, hgroup, menu, nav, section { height: 64px;
display: block;
} }
body { img.add-contacts {
line-height: 1; height: 40px;
cursor: pointer;
} }
ol, ul { .row .col.s12.main-container {
list-style: none; background: #FFF;
padding: 10px;
border-radius: 5px;
} }
blockquote, q { #search {
quotes: none; background: white;
border: none;
border-radius: 7px;
height: 40px;
width: 200px;
transition: all 0.3s;
padding-left: 10px;
} }
blockquote:before, blockquote:after, #search:hover {
q:before, q:after { width: 350px;
content: '';
content: none;
} }
table { #search:focus {
border-collapse: collapse; width: 500px;
border-spacing: 0;
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
} }

BIN
static/img/add-contacts.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
static/img/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
static/img/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

View File

@ -0,0 +1,74 @@
let working = false;
let lastQuery = null;
let displayContacts = (contacts) => {
let tbody = $("table tbody");
for (let contact of contacts) {
tbody.append(`
<tr>
<td>${(contact["first_name"] ? contact["first_name"] : (contact["firstName"] ? contact["firstName"] : ""))}</td>
<td>${(contact["last_name"] ? contact["last_name"] : (contact["lastName"] ? contact["lastName"] : ""))}</td>
<td>${(contact["surname"] ? contact["surname"] : "")}</td>
<td>${(contact["email"] ? contact["email"] : "")}</td>
<td>${(contact["address"] ? contact["address"] : "")}</td>
<td>${(contact["phone_number"] ? contact["phone_number"] : (contact["phoneNumber"] ? contact["phoneNumber"] : ""))}</td>
<td>${(contact["birthday"] ? new Date(contact["birthday"]).toLocaleDateString() : "")}</td>
</tr>
`);
}
};
$(document).ready(() => {
let modal = $('.modal');
modal.modal();
let search = (query) => {
if (query.length >= 3) {
working = true;
$.ajax({
url: "/api/contact/search",
method: "POST",
data: {
query: query
},
success: function (data) {
$("table tbody").empty();
for (let i = 0; i < 4; i++) {
if (data && data.result && data.result[i.toString()] && data.result[i.toString()].length > 0) {
displayContacts(data.result[i.toString()]);
}
}
working = false;
},
error: function (e) {
working = false;
}
});
} else {
$("table tbody").empty();
displayContacts(contacts);
}
};
$(document).on("input", "#search", () => {
let query = $("#search").val();
if (!working) {
search(query);
} else {
lastQuery = query;
}
});
$(document).on("click", ".add-contacts", () => {
modal.open();
});
$("[data-tooltip]").tooltip();
});

File diff suppressed because one or more lines are too long

2
static/js/jquery-3.3.1.min.js vendored Normal file

File diff suppressed because one or more lines are too long

6
static/js/materialize.min.js vendored Normal file

File diff suppressed because one or more lines are too long