<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RequestStack;
use phpCAS;
use JeroenDesloovere\VCard\VCard as VCardFile;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
class CustomController extends AbstractController {
protected $isAuth = false;
protected $userEmail = '';
protected $uploadsDIR = __DIR__.'/../../public/uploads/';
protected $studentsCacheFile = __DIR__.'/../../public/uploads/'.'students.json';
protected function selectFromWhere($table, $opt_where = '', $order_by = " D_MODIFICATION desc " , $DBG = false):array {
$out = array();
if (!empty($table)) {
$RAW_QUERY = "select * from ".$table
. (!empty($opt_where) ? ' where '.$opt_where : '')
. (!empty($order_by) ? ' order by '.$order_by : '')
;
// echo(__METHOD__.' RAW_QUERY: '.$RAW_QUERY);
if ($DBG != false) {
echo(__METHOD__
. ': RAW_QUERY: '.$RAW_QUERY
);
}
$found = $this->selectRaw($RAW_QUERY, $DBG);
/*
if (count($found) == 1) {
$out = $found[0];
} else
// */
// {
$out = $found;
// }
}
if ($DBG != false) {
echo(__METHOD__
// . ': RAW_QUERY: '.$RAW_QUERY
.': out: '.var_export($out, true));
}
return $out;
}
public function selectViewWhere($v_name, $where, $get_all = false, $DBG = false) : array {
$out = array();
if (!empty($v_name) && !empty($where)) {
$RAW_QUERY = 'SELECT * FROM '.$v_name. ' where '. $where; // ' where IDE_DOSSIER='.$ide_dossier;
$found = $this->selectRaw($RAW_QUERY, $DBG);
if (count($found) > 0) {
if (!$get_all) {
$out = $found[0];
} else {
$out = $found;
}
}
}
return $out;
}
protected function getFromSite($site) {
$out = null;
if (strpos($site, "'") !== false) {
$site = str_replace("'", "''", $site); // NOTE: ORA-01756 escaping quote
}
$found = $this->selectViewWhere('V_SITE', "LOWER(SITE)='".strtolower($site)."'");
// echo(__METHOD__.' found: '.var_export($found, true)); // exit();
if (count($found) > 0
&& isset($found['ADRESSE'])
) {
$out = $found['ADRESSE'];
}
return $out;
}
protected function selectVcardStudentWhere($where = '') {
$out = null;
// $id_apprenant = isset($datas['id.Apprenant']) ? $datas['id.Apprenant'] : null;
if (isset($where)) {
$where = ' where '.$where;
}
$query = 'select * from vcard_student'. $where;
if (isset($_GET['DBG'])) {
echo(__METHOD__.': query:'.var_export($query, true));
}
$found = $this->selectRaw($query);
if (count($found) > 0) {
// $found = $found[0];
if (isset($found[0]['ID_VCARD'])) {
$out = $found;
}
}
return $out;
}
public function isNewQRCode($filename = '') {
$out = !is_null($filename)
&& file_exists($filename)
&& ((strpos(file($filename)[0], 'CREATOR')) != 0)
;
if (isset($_GET['DBG'])) {
echo(__METHOD__.': '.var_export($out, true));
}
return $out;
}
protected function getStudentVCardFromLogin($login) {
$out = null;
if (isset($login)) {
$found = $this->selectViewWhere('vcard_student', "commentaire like '%".'"login":"'.$login.'"%'."'");
if (isset($found['ID_VCARD'])) {
$out = $found;
}
}
if (isset($_GET['DBG'])) {
echo(__METHOD__.': out:'.var_export($out, true));
}
return $out;
}
public function generateQrCode($datas): string{
// set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__.'/../../vendor/phpqrcode');
// require_once('qrlib.php');
$out = '';
/*
$uri = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$uri .=(strpos('?', $uri) ? '?' : '&');
$dwnl = $uri . 'download=1';
// */
if (isset($datas['v_datas_card'])) {
$dwnl = $datas['download_url'];
$filename = 'phpqrcode/temp/image-qrcode-'.$datas['v_datas_card']['ID_VCARD'].'.png';
// QRcode::png($dwnl, $filename);
$out = (new QRCode)->render($dwnl);
}
return $out;
}
protected function selectRaw($RAW_QUERY, $DBG = false) : array {
$out = array();
if (!empty($RAW_QUERY)) {
$em = $this->getDoctrine()->getManager();
$statement = $em->getConnection()->prepare($RAW_QUERY);
// Set parameters
// $statement->bindValue('status', 1);
$res = $statement->execute();
$results = $res->fetchAllAssociative();
if (count($results) > 0) {
$out = $results;
}
}
if ($DBG) {
echo(__METHOD__
. ': SQL: '.$RAW_QUERY
.': out: '. var_export($out, true));
}
return $out;
}
public function testConnection($connection) {
// $conf = $connection->getConfiguration()->get('DATABASE_URL');
// echo(__METHOD__.' conf: '.var_export($conf, true)); exit();
$databaseUrl = $_ENV['DATABASE_URL'];
echo(var_export($databaseUrl));
$conn = oci_connect($connection->getUsername(), $connection->getPassword(), $connection->getHost().'/GRHV4'); // ('EASYID', '******', 'am-oracle-4/GRHV4');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM VCARD');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
echo(__METHOD__.': '
.'Connection: '. var_export($connection->getPassword(), true)
.'User: '. var_export($connection->getUsername(), true)
.'Host: '. var_export($connection->getHost(), true)
// .'Host: '. var_export($connection->getTnsname(), true)
);
exit();
}
protected function redirectToAuth($current_route = null) {
$args = array();
if (!empty($current_route)) {
$args['referer'] = $current_route;
}
$this->redirectToRoute('app_v_card_auth', $args, Response::HTTP_SEE_OTHER);
exit();
}
public function retrieveFromSession($session, $key) {
$out = null;
if (!empty($session)
&& !empty($key)
) {
$out = $session->get($key);
$this->storeInSession($session, null, $key);
}
return $out;
}
public function storeInSession($session, $value, string $key = '') : string {
$out = '';
if ($session != null) {
if (empty($key)) {
$key = md5(microtime());
}
$session->set($key, $value);
$out = $key;
}
return $out;
}
protected function deleteUploadedFile($filename) {
if (!empty($filename)) {
// TODO: get file path from key
// remove file
}
}
protected function uploadFile($filename = null, $target_dir = 'public/uploads/') {
$out = 0;
$out_file = '';
if (empty($filename)
&& isset($_FILES["fileToUpload"]["name"])
) {
$filename = basename($_FILES["fileToUpload"]["name"]);
}
$out_file = '/'.basename($target_dir).'/'.$filename;
$target_file = __DIR__.'/../../'.$target_dir.$filename; // basename($_FILES["fileToUpload"]["name"]);
// echo(__METHOD__.': '.$target_file);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if ($_FILES["fileToUpload"]["size"] > 15500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
// echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
// echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
$uploadOk = $out_file;
} else {
// echo "Sorry, there was an error uploading your file.";
$uploadOk = 0;
}
}
$out = $uploadOk;
return $out;
}
protected function addOptVcardFields($vcard, array $datas, $DBG = false) {
}
public function getVCardFileContent(array $datas, $DBG = false): string {
$out = '';
// echo(__METHOD__.': datas:' .var_export($datas,true)); exit();
// define vcard
$vcard = new VCardFile();
// define variables
$lastname = $datas['v_datas_card']['NOM'];
$firstname = $datas['v_datas_card']['PRENOM'];
$additional = '';
$prefix = '';
$suffix = '';
$service = // FALSE &&
isset($datas['personnel_datas']['SERVICE']) ? ', '. $datas['personnel_datas']['SERVICE'] : '';
// add personal data
$vcard->addName($lastname, $firstname, $additional, $prefix, $suffix);
// add work data
$vcard->addCompany('ENSAM'.$service);
// $vcard->addJobtitle('Personnel');
$title_items = json_decode($datas['v_datas_card']['TITRE']);
$t_item = implode(', ', $title_items);
/*
foreach ($title_items as $t_idx => $t_item) {
$vcard->addJobtitle($t_item);
// $vcard->addRole($t_item);
}
*/
$vcard->addJobtitle($t_item);
$vcard->addEmail($datas['v_datas_card']['EMAIL_PRO'], 'WORK');
$vcard->addPhoneNumber($datas['v_datas_card']['TEL_PRO'], 'PREF;WORK');
$tel_items = json_decode($datas['v_datas_card']['TEL']);
foreach($tel_items as $tel_idx => $tel_item) {
if ($tel_idx > 0) { // NOTE: first is PRO
$vcard->addPhoneNumber($tel_item, 'WORK');
}
}
$mail_items = json_decode($datas['v_datas_card']['EMAIL']);
foreach($mail_items as $mail_idx => $mail_item) {
if ($mail_idx > 0) { // NOTE: first is PRO
$vcard->addEmail($mail_item, 'WORK');
}
}
$vcard->addAddress(null, null, $datas['v_datas_card']['ADRESSE_PRO'], null, null, null, 'FRANCE');
$vcard->addLabel( $datas['v_datas_card']['ADRESSE_PRO'].' FRANCE');
$vcard->addURL('https://www.artsetmetiers.fr');
$ide_dossier = $datas['v_datas_card']['IDE_DOSSIER'];
// echo(__METHOD__.': '.var_export($datas['v_card'], true)); exit();
$custom_photo_file = $this->uploadsDIR.'photo_'.$ide_dossier.'.jpg';
if (isset($datas['v_datas_card']['AVEC_PHOTO']) && $datas['v_datas_card']['AVEC_PHOTO'] == 'oui'
|| isset($datas['v_card']) && (!is_array($datas['v_card'])) && ($datas['v_card'])->getavec_photo() == 'oui'
|| (isset($datas['v_card']) && (!is_array($datas['v_card'])) && ($datas['v_card'])->getavec_photo() != 'oui' && file_exists($custom_photo_file))
|| (isset($datas['v_datas_card']['AVEC_PHOTO']) && $datas['v_datas_card']['AVEC_PHOTO'] != 'oui' && file_exists($custom_photo_file))
) {
$photo_file = '/mnt/recadre/'.$ide_dossier.'.jpg';
if (( (isset($datas['v_datas_card']['AVEC_PHOTO'] ) && $datas['v_datas_card']['AVEC_PHOTO'] != 'oui') || (isset($datas['v_card']) && (!is_array($datas['v_card'])) && ($datas['v_card'])->getavec_photo() != 'oui')) && file_exists($custom_photo_file)) {
$photo_file = $custom_photo_file;
}
$vcard->addPhoto($photo_file);
}
// $vcard->addPhoto(__DIR__ . '/landscape.jpeg');
$this->addOptVcardFields($vcard, $datas, $DBG);
// return vcard as a string
$out = $vcard->getOutput();
if ($DBG !== false) {
echo(__METHOD__.':<br/>'.$out);
}
return $out;
}
protected function getStudentDatasFromMail($email = '', $DBG = false) {
$out = $found = null;
$found = $this->getStudentDatasById($email);
if ($DBG !== false) {
echo(__METHOD__.' found:'.var_export($found, true));
}
if (isset($found)
&& isset($found['email'])
) {
$out = $found;
}
return $out;
}
protected function getStudentDatasById($id = '') {
$out = null;
if (isset($id)) {
$file_datas = file_get_contents($this->studentsCacheFile);
if (isset($file_datas)) {
$js_datas = json_decode($file_datas, true);
if (count($js_datas) > 0
&& isset($js_datas[$id])
) {
$js_datas = $js_datas[$id];
// if (isset($js_datas['email'])) {
$out = $js_datas; // json_encode($js_datas);
// }
}
}
}
return $out;
}
protected function checkAuth($session, $previous = null) {
if (isset($session)) {
$is_auth = $session->get('is_auth');
$user_email = $session->get('user_email');
if (!$is_auth || !isset($user_email)) {
$session->set('previous', $previous);
header('Location: auth'); exit();
}
}
}
protected function getAuthCAS($request) : string {
$out = '';
// Load the settings from the central config file
require_once 'config_CAS.php';
// Load the CAS lib
// echo(__METHOD__.': phpcas_path: '.$phpcas_path); exit();
require_once $phpcas_path . '/CAS.php';
// Enable debugging
phpCAS::setLogger();
// Enable verbose error messages. Disable in production!
phpCAS::setVerbose(true);
// Initialize phpCAS
phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context, $client_service_name);
// For production use set the CA certificate that is the issuer of the cert
// on the CAS server and uncomment the line below
// phpCAS::setCasServerCACert($cas_server_ca_cert_path);
// For quick testing you can disable SSL validation of the CAS server.
// THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
// VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
phpCAS::setNoCasServerValidation();
// force CAS authentication
phpCAS::forceAuthentication();
// at this step, the user has been authenticated by the CAS server
// and the user's login name can be read with phpCAS::getUser().
// echo(__METHOD__.': authenticated!'); exit();
// logout if desired
if (isset($_REQUEST['logout'])) {
phpCAS::logout();
} else {
$session = $request->getSession();
$this->isAuth = true;
$out = $this->userEmail = phpCAS::getUser();
$session->set('is_auth', $this->isAuth);
$session->set('user_email', $this->userEmail);
}
// echo(__METHOD__.': Hello '.phpCAS::getUser());
return $out;
}
}