src/Controller/CustomController.php line 309

Open in your IDE?
  1. <?php 
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use phpCAS;
  8. use JeroenDesloovere\VCard\VCard as VCardFile;
  9. use chillerlan\QRCode\QRCode;
  10. use chillerlan\QRCode\QROptions;
  11. class CustomController extends AbstractController {
  12.     protected $isAuth false;
  13.     protected $userEmail '';
  14.     protected $uploadsDIR __DIR__.'/../../public/uploads/';
  15.     protected $studentsCacheFile __DIR__.'/../../public/uploads/'.'students.json';
  16.     protected function selectFromWhere($table$opt_where ''$order_by " D_MODIFICATION desc " $DBG false):array {
  17.         $out = array();
  18.     if (!empty($table)) {
  19.         $RAW_QUERY "select * from ".$table
  20.             . (!empty($opt_where) ? ' where '.$opt_where '')
  21.             . (!empty($order_by) ? ' order by '.$order_by '')
  22.             ;
  23.         // echo(__METHOD__.' RAW_QUERY: '.$RAW_QUERY);
  24.         if ($DBG != false) {
  25.             echo(__METHOD__
  26.             ': RAW_QUERY: '.$RAW_QUERY
  27.             );
  28.         }
  29.         $found $this->selectRaw($RAW_QUERY$DBG);
  30.         /*
  31.         if (count($found) == 1) {
  32.             $out = $found[0];
  33.         } else 
  34.         // */
  35.         // {
  36.             $out $found;
  37.         // }
  38.     }
  39.     if ($DBG != false) {
  40.         echo(__METHOD__
  41.             // . ': RAW_QUERY: '.$RAW_QUERY
  42.             .': out: '.var_export($outtrue));
  43.     }
  44.     return $out;
  45.     }
  46.     public function selectViewWhere($v_name$where$get_all false$DBG false) : array {
  47.     $out = array();
  48.     if (!empty($v_name) && !empty($where)) {
  49.             $RAW_QUERY 'SELECT * FROM '.$v_name' where '$where// ' where IDE_DOSSIER='.$ide_dossier; 
  50.         $found $this->selectRaw($RAW_QUERY$DBG);
  51.         if (count($found) > 0) {
  52.             if (!$get_all) { 
  53.                 $out $found[0];
  54.             } else {
  55.                 $out $found;
  56.             }
  57.         }
  58.     }
  59.     return $out;
  60.     }
  61.     protected function getFromSite($site) {
  62.         $out null;
  63.         if (strpos($site"'") !== false) {
  64.             $site str_replace("'""''"$site); // NOTE: ORA-01756 escaping quote
  65.         }
  66.         $found $this->selectViewWhere('V_SITE'"LOWER(SITE)='".strtolower($site)."'");
  67.         // echo(__METHOD__.' found: '.var_export($found, true)); //  exit();
  68.     if (count($found) > 0
  69.         && isset($found['ADRESSE'])
  70.     ) {
  71.             $out $found['ADRESSE'];
  72.         }
  73.     return $out;
  74.     }
  75. protected function selectVcardStudentWhere($where '') {
  76.     $out null;
  77.     // $id_apprenant = isset($datas['id.Apprenant']) ? $datas['id.Apprenant'] : null;
  78.     if (isset($where)) {
  79.         $where ' where '.$where;
  80.     }
  81.         $query  'select * from  vcard_student'$where;
  82.         if (isset($_GET['DBG'])) {
  83.             echo(__METHOD__.': query:'.var_export($querytrue));
  84.         }
  85.         $found $this->selectRaw($query);
  86.         if (count($found) > 0) {
  87.             // $found = $found[0];
  88.             if (isset($found[0]['ID_VCARD'])) {
  89.                 $out $found;
  90.             }
  91.         }
  92.     
  93.     return $out;
  94. }
  95.     public function isNewQRCode($filename '') {
  96.         $out = !is_null($filename)
  97.             && file_exists($filename)
  98.             && ((strpos(file($filename)[0], 'CREATOR')) != 0
  99.             ;
  100.     if (isset($_GET['DBG'])) {
  101.         echo(__METHOD__.': '.var_export($outtrue));
  102.     }
  103.     return $out;
  104.     }
  105.     protected function getStudentVCardFromLogin($login) {
  106.         $out null;
  107.         if (isset($login)) {
  108.             $found $this->selectViewWhere('vcard_student'"commentaire like '%".'"login":"'.$login.'"%'."'");
  109.             if (isset($found['ID_VCARD'])) {
  110.                 $out $found;
  111.             }
  112.         }
  113.         if (isset($_GET['DBG'])) {
  114.             echo(__METHOD__.': out:'.var_export($outtrue));
  115.         
  116.         }
  117.         return $out;
  118.     }
  119.     public function generateQrCode($datas): string{
  120.     // set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__.'/../../vendor/phpqrcode');
  121.     // require_once('qrlib.php');
  122.     $out '';
  123. /*
  124.     $uri = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
  125.     $uri .=(strpos('?', $uri) ? '?' : '&');
  126.         
  127.     $dwnl = $uri . 'download=1';
  128. // */
  129.     if (isset($datas['v_datas_card'])) {
  130.     $dwnl $datas['download_url'];
  131.     $filename 'phpqrcode/temp/image-qrcode-'.$datas['v_datas_card']['ID_VCARD'].'.png';
  132.     // QRcode::png($dwnl, $filename);
  133.     $out = (new QRCode)->render($dwnl);
  134.     }
  135.     return $out;
  136.     }
  137.    protected function selectRaw($RAW_QUERY$DBG false) : array {
  138.         $out = array();
  139.         if (!empty($RAW_QUERY)) {
  140.             $em $this->getDoctrine()->getManager();
  141.             $statement $em->getConnection()->prepare($RAW_QUERY);
  142.             // Set parameters 
  143.             // $statement->bindValue('status', 1);
  144.             $res $statement->execute();
  145.             $results $res->fetchAllAssociative();
  146.             if (count($results) > 0) {
  147.                 $out $results;
  148.             }
  149.         }
  150.     if ($DBG) {
  151.         echo(__METHOD__
  152.             ': SQL: '.$RAW_QUERY
  153.             .':   out: 'var_export($outtrue));
  154.     }
  155.     return $out;
  156.     }
  157.     public function testConnection($connection) {
  158.     // $conf = $connection->getConfiguration()->get('DATABASE_URL');
  159.     // echo(__METHOD__.' conf: '.var_export($conf, true)); exit();
  160.     $databaseUrl $_ENV['DATABASE_URL'];
  161.     echo(var_export($databaseUrl));
  162. $conn oci_connect($connection->getUsername(), $connection->getPassword(), $connection->getHost().'/GRHV4'); // ('EASYID', '******', 'am-oracle-4/GRHV4');
  163. if (!$conn) {
  164.     $e oci_error();
  165.     trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
  166. }
  167. $stid oci_parse($conn'SELECT * FROM VCARD');
  168. oci_execute($stid);
  169. echo "<table border='1'>\n";
  170. while ($row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
  171.     echo "<tr>\n";
  172.     foreach ($row as $item) {
  173.         echo "    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "") . "</td>\n";
  174.     }
  175.     echo "</tr>\n";
  176. }
  177. echo "</table>\n";
  178. echo(__METHOD__.': '
  179.     .'Connection: 'var_export($connection->getPassword(), true)
  180.     .'User: 'var_export($connection->getUsername(), true)
  181.     .'Host: 'var_export($connection->getHost(), true)
  182.     // .'Host: '. var_export($connection->getTnsname(), true)
  183. ); 
  184. exit();
  185.     }
  186.     protected function redirectToAuth($current_route null) {
  187.         $args = array();
  188.         if (!empty($current_route)) {
  189.             $args['referer'] = $current_route;
  190.         }
  191.         $this->redirectToRoute('app_v_card_auth'$argsResponse::HTTP_SEE_OTHER);
  192.         exit();
  193.     }
  194.     public function retrieveFromSession($session$key) {
  195.         $out null;
  196.     if (!empty($session)
  197.         && !empty($key)
  198.     ) {
  199.         $out $session->get($key);
  200.         $this->storeInSession($sessionnull$key);
  201.     }
  202.     return $out;
  203.     }
  204.     public function storeInSession($session$valuestring $key '') : string {
  205.         $out '';
  206.     if ($session != null) {
  207.         if (empty($key)) {
  208.             $key md5(microtime());
  209.         }
  210.         $session->set($key$value);
  211.         $out $key;
  212.     }
  213.     return $out;
  214.     }
  215.     protected function deleteUploadedFile($filename) {
  216.         if (!empty($filename)) {
  217.         // TODO: get file path from key
  218.         //      remove file
  219.     }
  220.     }
  221.     protected function uploadFile($filename null$target_dir 'public/uploads/') {
  222.         $out 0;
  223.         $out_file '';
  224.         if (empty($filename)
  225.             && isset($_FILES["fileToUpload"]["name"])
  226.         ) {
  227.             $filename =  basename($_FILES["fileToUpload"]["name"]);
  228.         }
  229.         $out_file =  '/'.basename($target_dir).'/'.$filename;
  230.         $target_file __DIR__.'/../../'.$target_dir.$filename;  // basename($_FILES["fileToUpload"]["name"]);
  231. // echo(__METHOD__.': '.$target_file);
  232.         $uploadOk 1;
  233.         $imageFileType strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
  234.         // Check if image file is a actual image or fake image
  235.         if(isset($_POST["submit"])) {
  236.             $check getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  237.             if($check !== false) {
  238.                 echo "File is an image - " $check["mime"] . ".";
  239.                 $uploadOk 1;
  240.             } else {
  241.                 echo "File is not an image.";
  242.                 $uploadOk 0;
  243.             }
  244.         }
  245.         if ($_FILES["fileToUpload"]["size"] > 15500000) {
  246.             echo "Sorry, your file is too large.";
  247.             $uploadOk 0;
  248.         }
  249.         // Allow certain file formats
  250.         if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
  251.             && $imageFileType != "gif" ) {
  252.             // echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  253.             $uploadOk 0;
  254.         }
  255.         // Check if $uploadOk is set to 0 by an error
  256.         if ($uploadOk == 0) {
  257.             // echo "Sorry, your file was not uploaded.";
  258.             // if everything is ok, try to upload file
  259.         } else {
  260.             if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
  261.                 // echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  262.                 $uploadOk $out_file;
  263.             } else {
  264.                 // echo "Sorry, there was an error uploading your file.";
  265.                 $uploadOk 0
  266.             }
  267.         }
  268.         $out $uploadOk;
  269.         return $out;
  270.     }
  271.     protected function addOptVcardFields($vcard, array $datas$DBG false) {
  272.     }
  273.     public function getVCardFileContent(array $datas$DBG false): string {
  274.     $out '';
  275.      // echo(__METHOD__.': datas:' .var_export($datas,true)); exit();
  276. // define vcard
  277. $vcard = new VCardFile();
  278. // define variables
  279. $lastname $datas['v_datas_card']['NOM'];
  280. $firstname $datas['v_datas_card']['PRENOM'];
  281. $additional '';
  282. $prefix '';
  283. $suffix '';
  284. $service // FALSE && 
  285.         isset($datas['personnel_datas']['SERVICE']) ? ', '$datas['personnel_datas']['SERVICE'] : '';
  286. // add personal data
  287. $vcard->addName($lastname$firstname$additional$prefix$suffix);
  288. // add work data
  289. $vcard->addCompany('ENSAM'.$service);
  290. // $vcard->addJobtitle('Personnel');
  291. $title_items json_decode($datas['v_datas_card']['TITRE']);
  292. $t_item implode(', '$title_items);
  293. /*
  294. foreach ($title_items as $t_idx => $t_item) {
  295.     $vcard->addJobtitle($t_item);
  296.     // $vcard->addRole($t_item);
  297. }
  298. */
  299.     $vcard->addJobtitle($t_item);
  300. $vcard->addEmail($datas['v_datas_card']['EMAIL_PRO'], 'WORK');
  301. $vcard->addPhoneNumber($datas['v_datas_card']['TEL_PRO'], 'PREF;WORK');
  302. $tel_items json_decode($datas['v_datas_card']['TEL']);
  303. foreach($tel_items as $tel_idx => $tel_item) {
  304.     if ($tel_idx 0) { // NOTE: first is PRO
  305.         $vcard->addPhoneNumber($tel_item'WORK');
  306.     }
  307. }
  308. $mail_items json_decode($datas['v_datas_card']['EMAIL']);
  309. foreach($mail_items as $mail_idx => $mail_item) {
  310.     if ($mail_idx 0) { // NOTE: first is PRO
  311.         $vcard->addEmail($mail_item'WORK');
  312.     }
  313. }
  314. $vcard->addAddress(nullnull$datas['v_datas_card']['ADRESSE_PRO'], nullnullnull'FRANCE');
  315. $vcard->addLabel$datas['v_datas_card']['ADRESSE_PRO'].' FRANCE');
  316. $vcard->addURL('https://www.artsetmetiers.fr');
  317. $ide_dossier $datas['v_datas_card']['IDE_DOSSIER'];
  318. // echo(__METHOD__.': '.var_export($datas['v_card'], true)); exit();
  319. $custom_photo_file $this->uploadsDIR.'photo_'.$ide_dossier.'.jpg';
  320. if (isset($datas['v_datas_card']['AVEC_PHOTO']) && $datas['v_datas_card']['AVEC_PHOTO'] == 'oui'
  321.     || isset($datas['v_card']) && (!is_array($datas['v_card'])) && ($datas['v_card'])->getavec_photo() == 'oui'
  322.     || (isset($datas['v_card']) && (!is_array($datas['v_card'])) && ($datas['v_card'])->getavec_photo() != 'oui' && file_exists($custom_photo_file))
  323.     || (isset($datas['v_datas_card']['AVEC_PHOTO']) && $datas['v_datas_card']['AVEC_PHOTO'] != 'oui' && file_exists($custom_photo_file))
  324. ) {
  325.     $photo_file '/mnt/recadre/'.$ide_dossier.'.jpg';
  326.     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)) {
  327.         $photo_file $custom_photo_file;
  328.     }
  329. $vcard->addPhoto($photo_file);
  330. }
  331. // $vcard->addPhoto(__DIR__ . '/landscape.jpeg');
  332.     $this->addOptVcardFields($vcard$datas$DBG);
  333. // return vcard as a string
  334.     $out $vcard->getOutput();
  335.     if ($DBG !== false) {
  336.         echo(__METHOD__.':<br/>'.$out);
  337.     }
  338.     return $out;
  339.     }
  340.     protected function getStudentDatasFromMail($email ''$DBG false) {
  341.         $out $found null;
  342.         $found $this->getStudentDatasById($email);
  343.         if ($DBG !== false) {
  344.             echo(__METHOD__.' found:'.var_export($foundtrue));
  345.         }
  346.         if (isset($found)
  347.             && isset($found['email'])
  348.         ) {
  349.             $out $found;
  350.         }
  351.         return $out;
  352.     }
  353.     protected function getStudentDatasById($id '') {
  354.         $out null;    
  355.         if (isset($id)) {
  356.             $file_datas file_get_contents($this->studentsCacheFile);
  357.         if (isset($file_datas)) {
  358.             $js_datas json_decode($file_datastrue);
  359.             if (count($js_datas) > 0
  360.                  && isset($js_datas[$id])
  361.             ) {
  362.                 $js_datas $js_datas[$id];
  363.                 // if (isset($js_datas['email'])) {
  364.                     $out $js_datas// json_encode($js_datas);
  365.                 // }
  366.             }
  367.         }
  368.         }
  369.         return $out;
  370.     }
  371.     protected function checkAuth($session$previous null) {
  372.         if (isset($session)) {
  373.             $is_auth $session->get('is_auth');
  374.             $user_email $session->get('user_email');
  375.             if (!$is_auth || !isset($user_email)) {
  376.                 $session->set('previous'$previous);
  377.                 header('Location: auth'); exit();
  378.             }
  379.         }
  380.     }
  381.     protected function getAuthCAS($request) : string {
  382.     $out '';
  383.     // Load the settings from the central config file
  384. require_once 'config_CAS.php';
  385. // Load the CAS lib
  386.     // echo(__METHOD__.': phpcas_path: '.$phpcas_path); exit();
  387. require_once $phpcas_path '/CAS.php';
  388. // Enable debugging
  389. phpCAS::setLogger();
  390. // Enable verbose error messages. Disable in production!
  391. phpCAS::setVerbose(true);
  392. // Initialize phpCAS
  393. phpCAS::client(CAS_VERSION_2_0$cas_host$cas_port$cas_context$client_service_name);
  394. // For production use set the CA certificate that is the issuer of the cert
  395. // on the CAS server and uncomment the line below
  396. // phpCAS::setCasServerCACert($cas_server_ca_cert_path);
  397. // For quick testing you can disable SSL validation of the CAS server.
  398. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  399. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  400. phpCAS::setNoCasServerValidation();
  401.         // force CAS authentication
  402.         phpCAS::forceAuthentication();
  403. // at this step, the user has been authenticated by the CAS server
  404. // and the user's login name can be read with phpCAS::getUser().
  405. //    echo(__METHOD__.': authenticated!'); exit();
  406. // logout if desired
  407. if (isset($_REQUEST['logout'])) {
  408.     phpCAS::logout();
  409. } else {
  410.     $session $request->getSession();
  411.     $this->isAuth true;
  412.     $out =  $this->userEmail phpCAS::getUser();
  413.     $session->set('is_auth'$this->isAuth);
  414.     $session->set('user_email'$this->userEmail);
  415. }
  416.     // echo(__METHOD__.': Hello '.phpCAS::getUser());
  417.     return $out;
  418.     }
  419. }