. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
| Server IP : 52.223.31.75 / Your IP : 172.31.32.98 [ Web Server : Apache/2.4.66 () OpenSSL/1.0.2k-fips PHP/7.4.33 System : Linux ip-172-31-14-81.eu-central-1.compute.internal 4.14.281-212.502.amzn2.x86_64 #1 SMP Thu May 26 09:52:17 UTC 2022 x86_64 User : apache ( 48) PHP Version : 7.4.33 Disable Function : NONE Domains : 4 Domains MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : OFF Directory : /var/www/sapere/app/ |
Upload File : |
<?php
require 'vendor/autoload.php';
use PayPalCheckoutSdk\Orders\OrdersGetRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
switch($_SESSION["userdata"]["user_type_id"]){
case "830830": include "app/components/admin/api.class.php"; break;
case "550550": include "app/components/centri/api.class.php"; break;
case "1": include "app/components/studenti/api.class.php"; break;
case "2": include "app/components/centri/api.class.php"; break;//include "app/components/affiliati/api.class.php"; break;
case "3": include "app/components/formatori/api.class.php"; break;
case "4": include "app/components/supervisori/api.class.php"; break;
case "5": include "app/components/editors/api.class.php"; break;
case "6": include "app/components/tutor/api.class.php"; break;
}
class MemJamed{
/*
*
* MEMCACHED
*
*/
function __construct(){
$pwd =getcwd();
if(!file_exists($pwd."/cache/")){
mkdir($pwd."/cache/",0777);
}
}
public function get($key){
return false;
$pwd =getcwd();
$file=$pwd."/cache/".$key.".bjam";
if(file_exists($file)){
return file_get_contents($file);
}else{
return false;
}
}
public function set($key, $value){
return false;
$pwd =getcwd();
$file=$pwd."/cache/".$key.".bjam";
if(file_exists($file)){
unlink($file);
}
return file_put_contents($file, $value);
}
public function delete($key){
return false;
$pwd =getcwd();
$file=$pwd."/cache/".$key.".bjam";
return unlink($file);
}
}
class API {
/**
*
*
*
*
*
*
*/
public $oreSfasamento;
public $secondiSfasamento;
/*
*
* MEMCACHED
*
*/
public $memcached;
protected $session;
function __construct(){
$this->oreSfasamento = date("I",strtotime("now"))+1; //ora
$this->secondiSfasamento = (date("I",strtotime("now"))+1)*3600; //ora
$this->session = new OCSession();
/*
*
* MEMCACHED
*
*/
$this->memcached = new MemJamed();
/*try{
$this->memcached = new Memcached();
$this->memcached->addServer("127.0.0.1", 11211);
}catch(Exception $e){
$this->memcached = false;
echo "Sistema di cache non attivo o non funzionate!";
echo $e;
}*/
}
public function getInfoTableName(){
if($_SESSION['userdata'])
switch($_SESSION['userdata']['user_type_id']){
case "830830": return 'admin_user_info'; break;
case "550550": return 'centri_user_info'; break;
case "1": return 'studenti_user_info'; break;
case "2": return 'centri_user_info'; break;//return 'affiliati_user_info'; break;
case "3": return 'formatori_user_info'; break;
case "4": return 'supervisori_user_info'; break;
case "5": return 'editor_user_info'; break;
case "6": return 'tutor_user_info'; break;
default: return null;
}
}
/*** OLD FIRST IMPLE AP JAM ***/
public function storeFile($nome_file, $userid, $tipo){
if($this->checkSuperAdmin()) {
$tmpMongo = new DBLinkMongo(FILE_INI_MDADB_MONGO);
$tmpMongo->storeFileJAM( $nome_file, array( 'id_user' => $userid, 'tipo' => $tipo), array() );
return id_mongo;
}else{
return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );
}
}
// public function downloadFile($id)
// {
// if($this->checkSuperAdmin()) {
// $tmpMongo = new DBLinkMongo(FILE_INI_MDADB_MONGO);
// $file = $tmpMongo->getFileJAM($id);
// $finfo = finfo_open(FILEINFO_MIME_TYPE);
// $contentType = finfo_file($finfo, $file->getFilename());
// finfo_close($finfo);
// $nome_file = end(explode("/",$file->getFilename()));
// $this->downloadFilePrivate($file->getResource(), $nome_file, $contentType);
// }else{
// return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );
// }
// }
public function validateAuthAndGetUser(){
$isloggedin = Persistant::IsloggedIn();
if(!$isloggedin) {
return $this->printMessage( $this->responseLogout('Errore interno si prega di effettuare il logut e loggarsi di nuovo alla piattaforma!', false) );
} else {
//$_SESSION['id_session'] = session_id();
return Persistant::GetUserInfo();
}
}
protected function checkUserPermission(){
if($_SESSION["userdata"]["user_type_id"] == 830830 /*"Super Admin"*/ || $_SESSION["userdata"]["user_type_id"] == 123456/*"Admin"*/ || /*dipendente*/ $_SESSION["userdata"]["user_type_id"] ==456789|| /*CEP*/ $_SESSION["userdata"]["user_type_id"] ==987654 || $_SESSION["userdata"]["user_type_id"] ==236876) {
return true;
} else {
// if($this->validaLdap()){
// return true;
// }else{
return false;
//}
}
}
private function getDominio(){
$_domain = explode(".",$_SERVER['HTTP_HOST']);
return $_domain[1].".".$_domain[2];
}
private function checkSuperAdmin(){
if($_SESSION["userdata"]["user_type_id"] ==830830) {
return true;
} else {
// if($this->validaLdap()){
// return true;
// }else{
return false;
//}
}
}
private function formatJSON($data){
$data = json_encode($data, JSON_FORCE_OBJECT);
return $data;
}
protected function clearTemp(){
//improve this function for more concurrency
$files = glob(SITEROOT_DIR.'/www/api/tmp/*');
foreach($files as $file){
if(is_file($file)) unlink($file);
}
return;
}
protected function responseMessage($message, $status){
$data = array(
"message" => $message,
"status" => $status,
//"session_status" => session_id()
);
return $data;
}
protected function responseLogout($message, $status){
$data = array(
"message" => $message,
"status" => $status,
"logout" => true
//"session_status" => session_id()
);
return $data;
}
static function responseMessageStatic($message, $status){
$data = array(
"message" => $message,
"status" => $status,
//"session_status" => session_id()
);
header('Content-Type: application/json');
print( json_encode($data) );
die();
return;
}
protected function printMessage($message){
header('Content-Type: application/json');
print( json_encode($message) );
die();
return;
}
private function downloadFilePrivate($file, $filename, $contentType){
header("Content-Transfer-Encoding: binary");
header('Content-Type: '. $contentType);
header('Expires: 0');
header('Content-Length: ' . filesize($file));
header("Content-disposition: attachment; filename=".$filename);
while (!feof($file)) {
echo fread($file, 8192);
}
die();
return;
}
public function downloadFileUploaded($filename){
header("Content-Transfer-Encoding: binary");
$file=SITEROOT_DIR . "uploads/".$filename;
$handle = fopen($file, "r");
header('Content-Type: '. mime_content_type($file));
header('Expires: 0');
header('Content-Disposition: attachment; filename="'.$filename.'"');
//header('Content-Length: ' . filesize($file));
while (!feof($handle)) {
echo fread($handle, 8192);
}
die();
return;
}
public function aggiungiTag($valore, $id, $tabella){
if($this->checkUserPermission() == true) {
$cont = new Content();
$res = $cont->aggiungiTag($valore, $id, $tabella);
if(!$res){
return $this->printMessage( $this->responseMessage("Errore in fase di aggiungra dei tags", false) );
}
} else {
return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
}
}
public function ricercaTag($tag){
if($this->checkUserPermission() == true) {
$cont = new Content();
$res = $cont->ricercaTag($tag);
return $this->printMessage( $this->responseMessage($res, true) );
} else {
return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
}
}
public function downloadUploads($filename)
{
$arr=json_decode($filename);
for($i=0;$i<count($arr)-1;$i++)
{
$this->downloadFileUploaded($arr[$i]);
}
}
private function showFile($filename, $contentType){
header("Content-Transfer-Encoding: binary");
header('Content-Type: '. $contentType);
header('Expires: 0');
while (!feof($filename)) {
echo fread($filename, 8192);
}
die();
return;
}
private function detectImageType($filename){
if (!file_exists($filename)) throw new InvalidArgumentException('File "'.$filename.'" not found.');
switch ( strtolower( pathinfo( $filename, PATHINFO_EXTENSION ))) {
case 'jpeg':
case 'jpg':
return imagecreatefromjpeg($filename);
break;
case 'png':
return imagecreatefrompng($filename);
break;
case 'gif':
return imagecreatefromgif($filename);
break;
default:
throw new InvalidArgumentException('File "'.$filename.'" is not valid jpg, png or gif image.');
break;
}
}
//taglia immagine quadrata
private function mockCrop($file){
$image = getimagesize($file);
$crop = array(0,0,$image[0],$image[1]);
return $crop;
}
//array di coordinata e ti ritaglia
private function cropImage($file, $crop = null){
$targ_w = $targ_h = 150;
if (!file_exists($file)) throw new InvalidArgumentException('File "'.$file.'" not found.');
$img_r = $this->detectImageType($file);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
if(count($crop)) {
$size = getimagesize($file);
$x = 0;
$y = 0;
$w = $size[0];
$h = $size[1];
if($w > $h) $w = $h;
if($h > $w) $h = $w;
} else {
$crop = explode(",", $crop);
$x = $crop[0];
$y = $crop[1];
$w = $crop[2];
$h = $crop[3];
}
imagecopyresampled( $dst_r, $img_r, 0, 0, $x, $y, $targ_w, $targ_h, $w, $h);
$croppedImageTmpFile = tempnam(SITEROOT_DIR."www/api/tmp/",null);
imagejpeg($dst_r,$croppedImageTmpFile,100);
imagedestroy($dst_r);
return $croppedImageTmpFile;
}
//ridimensiona immagine
private function resizeImage($file, $width, $height){
$imageSize = getimagesize($file);
$imageWidth = $imageSize[1];
$imageHeight = $imageSize[0];
$resizedImage = imagecreatetruecolor($width,$height);
$image = imagecreatefromjpeg($file);
imagecopyresized ($resizedImage, $image, 0, 0, 0, 0, $width, $height, $imageWidth, $imageHeight);
$resizedImageTmpFile = tempnam(SITEROOT_DIR."www/api/tmp/",null);
imagejpeg($resizedImage,$resizedImageTmpFile,100);
imagedestroy($image);
return $resizedImageTmpFile;
}
private function getPath($path, $filename){
$user = $this->validateAuthAndGetUser();
$firstname = str_replace(" ", "-", $user["firstname"]);
$lastname = str_replace(" ", "-", $user["lastname"]);
$filename = str_replace(" ", "-", $filename);
return $path."/".$firstname."_".$lastname."_".$filename;
}
private function checkFileType($file){
//check content type against list of content types private
$info = pathinfo($file);
$basename = $info['basename'];
$ext = $info['extension'];
$acceptedFileType = array(
'doc' => 'application/msword',
'docm' => 'application/vnd.ms-word.document.macroenabled.12',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dot' => 'application/msword',
'dotm' => 'application/vnd.ms-word.template.macroenabled.12',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'pps' => 'application/vnd.ms-powerpoint',
'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'ppt' => 'application/vnd.ms-powerpoint',
'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pdf' => 'application/pdf',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'mp4' => 'video/mp4',
'mp4a' => 'audio/mp4',
'mp4s' => 'application/mp4',
'mp4v' => 'video/mp4'
);
if($acceptedFileType[$ext]) {
return true;
} else {
return false;
}
}
public function formatFileName($fileName) {
// Separare il nome del file dall'estensione
$pathInfo = pathinfo($fileName);
$name = $pathInfo['filename']; // Nome del file senza estensione
$extension = isset($pathInfo['extension']) ? $pathInfo['extension'] : ''; // Estensione (se presente)
// Rimuovere caratteri speciali tranne lettere, numeri e trattino basso
$name = preg_replace('/[^a-zA-Z0-9_]/', '', $name);
// Aggiungere data e ora in formato italiano (gg_mm_aaaa_ora_minuto_secondo)
$currentDateTime = date('d_m_Y-H_i_s');
// Comporre il nuovo nome del file
$newFileName = $name . '-' . $currentDateTime;
// Aggiungere nuovamente l'estensione se presente
if ($extension) {
$newFileName .= '.' . $extension;
}
return $newFileName;
}
public function generatePassword($username){
$random = rand(99999, 999999);
$username = preg_replace('/\s+/', '', $username);
$password = str_shuffle( strtolower( $username ).$random );
return substr($password, 0,10);
}
public function inviaEmail($email, $oggetto, $htmlbody, $txtbody ){
require_once SITEROOT_DIR.'/app/helpers/persistant.php';
require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
require_once SITEROOT_DIR.'/app/helpers/emailmessage.php';
//$ocuser = new OCUser(true);
// if (!is_int($res)) {
$emailMessage = new EmailMessage(FILE_INI_EMAIL);//
return $emailMessage->SendMessage($oggetto, $htmlbody, $txtbody, "piattaformasapere@".$this->getDominio(), $email);
// } else {
// return $this->printMessage( $this->responseMessage(false));
// }
}
// public function getDirContents($dir, &$results = array()) {
// $files = scandir($dir);
// foreach ($files as $key => $value) {
// $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
// if (!is_dir($path)) {
// $results[] = $path;
// } else if ($value != "." && $value != "..") {
// $this->getDirContents($path, $results);
// $results[] = $path;
// }
// }
// return $results;
// }
// public function compressImageFix() {
// $quality = 80;
// $results =$this->getDirContents('/Users/jam830/Downloads/lezione/');
// echo "File Trovati " .count($results). ";";
// for ($i=0; $i < count($results); $i++) {
// $sourcePath = $results[$i];
// $info = getimagesize($sourcePath);
// echo "elaboro:".$sourcePath." \n";
// if ($info === false) {
// continue; // non è un'immagine
// }
// $mime = $info['mime'];
// switch ($mime) {
// case 'image/jpeg':
// $image = imagecreatefromjpeg($sourcePath);
// imagejpeg($image, $sourcePath, $quality); // qualità da 0 (peggiore) a 100 (massima)
// imagedestroy($image);
// break;
// case 'image/png':
// $image = imagecreatefrompng($sourcePath);
// // In PNG la compressione è inversa: 0 (nessuna compressione), 9 (massima compressione)
// imagepng($image, $sourcePath, 6);
// imagedestroy($image);
// break;
// case 'image/webp':
// $image = imagecreatefromwebp($sourcePath);
// imagewebp($image, $sourcePath, $quality);
// imagedestroy($image);
// break;
// }
// }
// return "po";
// }
public function compressImage($sourcePath, $quality = 80, $maxWidth = 1080) {
$info = getimagesize($sourcePath);
$_destinationPath = explode(".", $sourcePath);
$_destinationPath[(count($_destinationPath)-2)].="_compress";
$destinationPath = implode(".",$_destinationPath);
if ($info === false) {
return false; // non è un'immagine
}
list($width, $height) = $info;
$mime = $info['mime'];
// Calcola le nuove dimensioni proporzionalmente
if ($width > $maxWidth) {
$newWidth = $maxWidth;
$newHeight = intval(($height / $width) * $newWidth);
} else {
// Non serve ridimensionare
$newWidth = $width;
$newHeight = $height;
}
switch ($mime) {
case 'image/jpeg':
$srcImage = imagecreatefromjpeg($sourcePath);
// Crea immagine ridimensionata
$dstImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($dstImage, $destinationPath, $quality); // qualità da 0 (peggiore) a 100 (massima)
break;
case 'image/png':
$srcImage = imagecreatefrompng($sourcePath);
$dstImage = imagecreatetruecolor($newWidth, $newHeight);
imagealphablending($dstImage, false);
imagesavealpha($dstImage, true);
imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// In PNG la compressione è inversa: 0 (nessuna compressione), 9 (massima compressione)
imagepng($dstImage, $destinationPath, 6);
break;
case 'image/webp':
$srcImage = imagecreatefromwebp($sourcePath);
// Crea immagine ridimensionata
$dstImage = imagecreatetruecolor($newWidth, $newHeight);
imagealphablending($dstImage, false);
imagesavealpha($dstImage, true);
imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagewebp($dstImage, $destinationPath, $quality);
break;
default:
return false; // formato non supportato
}
imagedestroy($srcImage);
imagedestroy($dstImage);
return $destinationPath;
}
public function zippami($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
//echo "Andromeda:".str_replace($source . '/', '', $file)."<br>";
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
$toRet= $zip->close();
return $toRet;
}
public function recuperaPassword($email){
require_once SITEROOT_DIR.'/app/helpers/persistant.php';
require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
require_once SITEROOT_DIR.'/app/helpers/emailmessage.php';
$ocuser = new OCUser(true);
$res = $ocuser->recuperaPassword($email, $this->generatePassword($email));
if (!is_int($res)) { //se non è un intero contiene la password
$emailMessage = new EmailMessage(FILE_INI_EMAIL);
//SEND EMAIL
//SendMessage($subject, $htmlbody, $txtbody, $from, $to, $cc='', $bcc='', $replacements=array(), $filelocation=null, $filename=null, $filetype=null)
//{
$htmlbody = "Gentile Utente, <br> ci è stato richiesto il recupero della password associato al tuo account, di seguito troverai le nuove crenziali di accesso. <br><br>In seguito al login potrai cambiare la tua password con due semplici click:<br>1. Cliccando su 'Anagrafica' nel menù laterale di sinistra<br>2. Successivamente cliccando su <b>Modifica password</b>.<br><br><br>Credenziali<br>***********<br>Username: $email<br>Password: $res<br><br>Grazie di averci preferito e buon lavoro.";
$txtbody = "Gentile Utente, \nci è stato richiesto il recupero della password associato al tuo account, di seguito troverai le nuove crenziali di accesso. \n\nIn seguito al login potrai cambiare la tua password con due semplici click:\n1. Cliccando su 'Anagrafica' nel menù laterale di sinistra\n2. Successivamente cliccando su 'Modifica password'.\n\n\nCredenziali\n***********\nUsername: $email\nPassword: $res\n\nGrazie di averci preferito e buon lavoro.";
$emailCK = $emailMessage->SendMessage("Richiesta di recupero password ", $htmlbody, $txtbody, "piattaformasapere@".$this->getDominio(), $email);
if($emailCK){
return $this->printMessage( $this->responseMessage("L'email contenente la nuova password è stata inviata!", true) );
}else{
return $this->printMessage( $this->responseMessage("Errore nel server di posta elettronica, riprovare in caso il problema persista, contattare l'amministratore!", false) );
}
} else {
if ($res==-1) {
return $this->printMessage( $this->responseMessage("Non è stato possibile trovare l'utente con questa email, si prega di verificare l'email e riprovare!", false) );
}else if ($res==-2) {
return $this->printMessage( $this->responseMessage("L'email contenente la nuova password è stata già inviata meno di 5 minuti fà, si prega di attendere 5 minuti e riprovare!", false) );
}else {
return $this->printMessage( $this->responseMessage("Errore interno del server!", false) );
}
}
}
/*
*
* METODI PUBBLICI PER REGIONI, PROVINCE, COMUNI
*
*/
public function getNazioni(){
//$this->validateAuthAndGetUser();
$result = $this->memcached->get("NAZIONI");
if (!$result) {
$contentOperations = new Content();
$result = $contentOperations->getNazioni();
$this->memcached->set("NAZIONI", $result);
}
return $this->printMessage( $this->responseMessage($result, true) );
}
public function getRegioni(){
//$this->validateAuthAndGetUser();
$result = $this->memcached->get("REGIONI");
if (!$result) {
$contentOperations = new Content();
$result = $contentOperations->getRegioni();
$this->memcached->set("REGIONI", $result);
}
return $this->printMessage( $this->responseMessage($result, true) );
}
public function getProvince(){
//$this->validateAuthAndGetUser();
$result = $this->memcached->get("PROV");
if (!$result) {
$contentOperations = new Content();
$result = $contentOperations->getProvince();
$this->memcached->set("PROV", $result);
}
return $this->printMessage( $this->responseMessage($result, true) );
}
public function getComuni($id_provicia){
//$this->validateAuthAndGetUser();
$result = $this->memcached->get("COMUNI");
if (!$result) {
$contentOperations = new Content();
$result = $contentOperations->getComuni($id_provicia);
$this->memcached->set("COMUNI", $result);
}
return $this->printMessage( $this->responseMessage($result, true) );
}
//---------------------WS-----------
public function getConnectionId(){
$id_user = $_SESSION["userdata"]["user_type_id"];
$contentOperations = new Content();
$id = $this->generatePassword($id_user);
$result = $contentOperations->setConnectionId($id);
return $this->printMessage( $this->responseMessage($id, true) );
}
public function clientConnesso($token, $connectionId){
$contentOperations = new Content();
$result = $contentOperations->setClientConnesso($token, $connectionId);
return $this->printMessage( $this->responseMessage($result, true) );
}
public function clientDisconnesso($connectionId){
$contentOperations = new Content();
$result = $contentOperations->setClientDisconnesso($connectionId);
return $this->printMessage( $this->responseMessage($result, true) );
}
public function clientMessage($connectionId, $message, $tipo){
$contentOperations = new Content();
$result = $contentOperations->setclientMessage($connectionId, $message, $tipo);
return $this->printMessage( $this->responseMessage($result, true) );
}
// public function getClientMessage($id_user){
// $contentOperations = new Content();
// $result = $contentOperations->getClientMessage($id_user);
// return $this->printMessage( $this->responseMessage($result, true) );
// }
// public function getClientMessage($id_user){
// $id_user = $this->QuoteInt($_SESSION["userdata"]["id_user"]);
// $q = "SELECT * FROM user_log WHERE id_user = id_user = $id_user";
// return $this->SafeFetchOne($q);
// }
//----FINE WS---------------
// public function setConfigurazioneEmail($host_email, $port_email,$username_email, $password_email, $nome_mittente_email, $email_mittente_email){
// if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {
// $con = new Content();
// $result = $con->setConfigurazioneEmail($host_email, $port_email,$username_email, $password_email, $nome_mittente_email, $email_mittente_email);
// return $this->printMessage( $this->responseMessage($result, true) );
// }else{
// return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );
// }
// }
// public function getConfigurazioneEmail(){
// if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {
// $con = new Content();
// $result = $con->getConfigurazioneEmail();
// return $this->printMessage( $this->responseMessage($result, true) );
// }else{
// return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );
// }
// }
public function getListaFilePrivate($tipo, $id, $sottocartelle=true){
$awsConfig = AWSCONFIG;
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($awsConfig);
$bucket = $awsConfig['bucket'];
// Use an Aws\Sdk class to create the S3Client object.
$s3 = $sdk->createS3();
// Use the high-level iterators (returns ALL of your objects).
$toRet = [];
try {
$results = $s3->getPaginator('ListObjects', [
'Bucket' => $bucket,
"Prefix" => $awsConfig['cliente']."/".$tipo."/".$id."/"
]);
foreach ($results as $result) {
foreach ($result['Contents'] as $object) {
$tr= explode("/", $object['Key']);
if(count($tr)>4){
if($sottocartelle){
$toRet[]= end($tr);
}
}else{
$toRet[]= end($tr);
}
//$toRet[]= /*$awsConfig['url'].*/end(explode("/", $object['Key']));
}
}
} catch (S3Exception $e) {
$toRet[]= $e->getMessage();
}
return $toRet;
}
public function getFile($tipo, $id, $filename, $visualizza = false){
$awsConfig = AWSCONFIG;
//$sdk = new Aws\Sdk($awsConfig);
//$bucket = $awsConfig['bucket'];
//$s3 = $sdk->createS3();
$keyname = $awsConfig['cliente']."/".$tipo."/".$id."/".$filename;
//echo $keyname;
$s3Client = new Aws\S3\S3Client([
//'profile' => 'default',
'credentials' => [
'key' => $awsConfig['credentials']['key'],
'secret' => $awsConfig['credentials']['secret']
],
'region' => $awsConfig['region'],
'version' => '2006-03-01'
]);
$cmd = $s3Client->getCommand('GetObject', [
'Bucket' => $awsConfig['bucket'],
'Key' => $keyname
]);
$request = $s3Client->createPresignedRequest($cmd, '+10 minutes');
$presignedUrl = (string)$request->getUri();
if($visualizza){
$curlSES=curl_init();
curl_setopt($curlSES,CURLOPT_URL,$presignedUrl);
curl_setopt($curlSES,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curlSES, CURLOPT_BINARYTRANSFER,1);
curl_setopt($curlSES,CURLOPT_HEADER, false);
$result=curl_exec($curlSES);
echo $result;
die;
//curl_close($curlSES);
//return $this->printMessage( $this->responseMessage($result, true) );
}else{
return $this->printMessage( $this->responseMessage($presignedUrl, true) );
}
}
private function get_http_response_code($url) {
$headers = get_headers($url);
return substr($headers[0], 9, 3);
}
public function deleteFileS3($tipo, $id, $nomefile){
$this->validateAuthAndGetUser();
if ($this->checkUserPermission() == true)
// && ($this->checkSuperAdmin()||$_SESSION["userdata"]["user_type_id"] ==123456))
{
$toRet = $this->deleteFileS3Private($tipo, $id, $nomefile);
if($toRet){
$toReturn = $this->getListaFilePrivate($tipo, $id);
return $this->printMessage($this->responseMessage($toReturn, true));
}else{
return $this->printMessage($this->responseMessage("File non cancellato!", false));
}
}
else
{
return $this->printMessage($this->responseMessage("Pemessi non sufficienti!", false));
}
}
public function deleteFileS3Private($tipo, $id,$nomefile){
// Create an SDK class used to share configuration across clients.
$awsConfig = AWSCONFIG;
$bucket = $awsConfig['bucket'];
$keyname = $awsConfig['cliente'];
$uploadLink = $keyname."/".$tipo."/".$id."/".$nomefile;
// Send a PutObject request and get the result object.
$sdk = new Aws\Sdk($awsConfig);
// Use an Aws\Sdk class to create the S3Client object.
$s3 = $sdk->createS3();
try {
$result = $s3->deleteObject(
array(
'Bucket'=>$bucket,
'Key' => $uploadLink,
)
);
//return print_r($result, true);//['ObjectURL'];
$this->printMessage($this->responseMessage("File cancellato con successo!", true));
}catch(Exception $e){
$this->printMessage($this->responseMessage("File non cancellato!", false));
}
//fine for
}
public function putVideoS3ToConvertPrivate($urllocalefile, $id_lezione){
// Separare il nome del file dall'estensione
$pathInfo = pathinfo($urllocalefile);
$name = $pathInfo['filename']; // Nome del file senza estensione
$extension = isset($pathInfo['extension']) ? $pathInfo['extension'] : ''; // Estensione (se presente)
//$urllocalefile_nopath = $nomefile_noext . "." . $extension;
$awsConfig = AWSCONFIG;
$bucket = $awsConfig['bucket'];
$keyname = $awsConfig['cliente'];
$uploadLink = $keyname."/video_da_elaborare/".$id_lezione.".".$extension;
// Send a PutObject request and get the result object.
$sdk = new Aws\Sdk($awsConfig);
// Use an Aws\Sdk class to create the S3Client object.
$s3 = $sdk->createS3();
try {
$result = $s3->putObject(
array(
'Bucket'=>$bucket,
'Key' => $uploadLink,
'SourceFile' => $urllocalefile
//'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
unlink($urllocalefile);
return $result['ObjectURL'];
}catch(Exception $e){
echo $e->getMessage();
$this->printMessage( $this->responseMessage($e, false) );
return false;//$e->getMessage() . PHP_EOL;
}
//fine for
}
private function getAccountLimit(){
$accountType= $_SESSION["userdata"]["account"];
$ocuser = new OCUser();
return $ocuser->getCentroAccountPermissions($accountType);
}
private function checkLimitFileCentroAccount($filename){
//se è un centro master o standar o un formatore
if($_SESSION["userdata"]["user_type_id"] == "550550" || $_SESSION["userdata"]["user_type_id"] == "2" || $_SESSION["userdata"]["user_type_id"] == "4"){
$permessi = $this->getAccountLimit();
if(!$permessi){
header('Content-Type: application/json');
$data = array(
"message" => "Non è stato possibile recuperare i permessi del tuo account, contatta l'amministratore di sistema!",
"status" => false
);
print( json_encode($data) );
die();
}else{
//verifico se filename è un video
$info = pathinfo($filename);
$ext = strtolower($info['extension']);
$videoExtensions = array('mp4', 'mp4a', 'mp4s', 'mp4v', 'mov', 'avi', 'wmv', 'flv', 'mkv', 'webm');
$tipofile = "";
if (in_array($ext, $videoExtensions)) {
$tipofile = "video";
} else {
$tipofile = "file";
}
if($permessi['max_numero_video'] == 0 && $tipofile = "video"){
header('Content-Type: application/json');
$data = array(
"message" => "Il tuo account non prevede l'upload di file video, contatta la segreteria per effettuare un upgrade del tuo account!",
"status" => false
);
print( json_encode($data) );
die();
}
}
$maxUploadSize = ( (int) $permessi['max_size_file'] )* 1024 * 1024;
if (isset($_SERVER["CONTENT_LENGTH"])) {
if ($_SERVER["CONTENT_LENGTH"] > ((int)ini_get('post_max_size') * 1024 * 1024) || $_SERVER["CONTENT_LENGTH"] > ((int)ini_get('upload_max_filesize') * 1024 * 1024)) {
header('Content-Type: application/json');
$data = array(
"message" => "I files caricati superano la dimensione massima di upload del singolo file di ".ini_get('upload_max_filesize')." o quella supportata dal sistema ".ini_get('post_max_size').". Prova a caricare un numero minore di file, puoi caricare al massimo ".ini_get('max_file_uploads')." files, nessun file caricato!",
"status" => false
);
print( json_encode($data) );
die();
}else if ( ( (int) $permessi['max_size_file'] )>0 && ($_SERVER["CONTENT_LENGTH"] > ((int) $permessi['max_size_file'] * 1024 * 1024) || $_SERVER["CONTENT_LENGTH"] > ((int) $permessi['max_size_file'] * 1024 * 1024))) {
header('Content-Type: application/json');
$data = array(
"message" => "I files caricati superano la dimensione massima di upload del singolo file di ".$permessi['max_size_file']." o quella supportata dalla tua tipologia di account ".$permessi['max_size_file'].". Prova a caricare un numero minore di file, puoi caricare al massimo ".$permessi['max_size_file']." files, nessun file caricato! Se hai bisogno di caricare dei file più grandi chiama subito la segreteria per effettuare un upgrade del tuo account!",
"status" => false
);
print( json_encode($data) );
die();
}
}
}
}
public function putFileS3Private($tipo, $id, $urllocalefile){
//verifica i limiti di upload in base al tipo di account del centro
$this->checkLimitFileCentroAccount(end(explode("/",$urllocalefile)));
$urllocalefile_nopath = $this->formatFileName( end(explode("/",$urllocalefile)) );
$awsConfig = AWSCONFIG;
$bucket = $awsConfig['bucket'];
$keyname = $awsConfig['cliente'];
$uploadLink = $keyname."/".$tipo."/".$id."/".$urllocalefile_nopath;
// Send a PutObject request and get the result object.
$sdk = new Aws\Sdk($awsConfig);
// Use an Aws\Sdk class to create the S3Client object.
$s3 = $sdk->createS3();
try {
$result = $s3->putObject(
array(
'Bucket'=>$bucket,
'Key' => $uploadLink,
'SourceFile' => $urllocalefile
//'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
unlink($urllocalefile);
return $result['ObjectURL'];
}catch(Exception $e){
echo $e->getMessage();
$this->printMessage( $this->responseMessage($e, false) );
return false;//$e->getMessage() . PHP_EOL;
}
//fine for
}
public function modificaPassword($oldpwd, $newpwd){
$user = $this->validateAuthAndGetUser();
//verifico i permessi
$ocuser = new OCUser();
$result = $ocuser->modificaPassword($user['id_user'], $oldpwd, $newpwd);
if($result) {
return $this->printMessage( $this->responseMessage("Password modificata con successo!", true) );
}else{
return $this->printMessage( $this->responseMessage('La password inserita non sembra essere corretta, verifica i tuoi dati e riprova!', false) );
}
}
private function checkUserProfile($user){
if($user){
switch($user['user_type_id']){
case "830830": return true; break;
case "550550": require_once SITEROOT_DIR. "/app/components/centri/api.class.php"; $api=new APICentri(); break;
case "1": require_once SITEROOT_DIR. "/app/components/studenti/api.class.php"; $api=new APIStudenti(); break;
case "2": require_once SITEROOT_DIR. "/app/components/centri/api.class.php"; $api=new APICentri(); break;//require_once SITEROOT_DIR. "/app/components/affiliati/api.class.php"; $api=new APIAffiliati(); break;
case "3": require_once SITEROOT_DIR. "/app/components/formatori/api.class.php"; $api=new APIFormatori(); break;
case "4": require_once SITEROOT_DIR. "/app/components/supervisori/api.class.php";$api=new APISupervisori(); break;
case "5": return true; break;
case "6": require_once SITEROOT_DIR. "/app/components/tutor/api.class.php";$api=new APITutor(); break;
}
return $api->checkAnagrafica($user['id_user']);
}
}
// public function checkAnagrafica(){
// $user = $this->validateAuthAndGetUser();
// switch($user['user_type_id']){
// case "830830": return $this->printMessage( $this->responseMessage(true, true) ); break;
// case "550550": $api=new APICentri(); break;
// case "1": $api=new APIStudenti(); break;
// case "2": $api=new APIAffiliati(); break;
// case "3": $api=new APIFormatori(); break;
// case "4": $api=new APISupervisori(); break;
// }
// return $this->printMessage( $this->responseMessage($api->checkAnagrafica($user['id_user']), true) );
// }
public function login($username, $password){
require_once SITEROOT_DIR.'/app/helpers/persistant.php';
require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
$isloggedin = Persistant::IsloggedIn();
if(!$isloggedin) {
$this->preLogout();
}
$ocuser = new OCUser(true);
$res = $ocuser->Login($username ,$password);
if ($res) {
$res['profile_check']=$this->checkUserProfile($res);
Persistant::SetUserInfo($res);
return $this->printMessage( $this->responseMessage($res, true) );
} else {
return $this->printMessage( $this->responseMessage("Credenziali non corrette si prega di riprovare!", false) );
}
}
public function verificaCertificato($codice_certificato){
// require_once SITEROOT_DIR.'/app/helpers/persistant.php';
require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
$ocuser = new OCUser(true);
$res = $ocuser->verificaCertificato($codice_certificato);
if ($res) {
$__data_esame = explode(" ",$res['data_esito']);
$_data_esame = explode("-",$__data_esame[0]);
$ore = explode(":",$__data_esame[1]);
$data_esito = $_data_esame[2]."/".$_data_esame[1]."/".$_data_esame[0]." ".$ore['0'].":".$ore[1];
return $this->printMessage( $this->responseMessage("Certificato valido emesso il ".$data_esito, true) );
}else{
return $this->printMessage( $this->responseMessage("Certificato non trovato!", false) );
}
}
public function verificaAttestato($codice_attestato){
// require_once SITEROOT_DIR.'/app/helpers/persistant.php';
require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
$ocuser = new OCUser(true);
$res = $ocuser->verificaAttestato($codice_attestato);
if ($res) {
$__data_esame = explode(" ",$res['data_esito']);
$_data_esame = explode("-",$__data_esame[0]);
$ore = explode(":",$__data_esame[1]);
$data_esito = $_data_esame[2]."/".$_data_esame[1]."/".$_data_esame[0]." ".$ore['0'].":".$ore[1];
return $this->printMessage( $this->responseMessage("Attestato valido emesso il ".$data_esito, true) );
}else{
return $this->printMessage( $this->responseMessage("Attestato non trovato!", false) );
}
}
public function verificaReport($codice){
// require_once SITEROOT_DIR.'/app/helpers/persistant.php';
require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
$ocuser = new OCUser(true);
$res = $ocuser->verificaReport($codice);
if ($res) {
// $data_in_italiano = new DateTime($res['data_report']);
// $data_in_italiano->setTimezone(new DateTimeZone('Europe/Rome'));
// $res['data_report'] = $data_in_italiano->format('d/m/Y H:i');
return $this->printMessage( $this->responseMessage("Report valido!", true) );
}else{
return $this->printMessage( $this->responseMessage("Report non trovato!", false) );
}
}
public function logout(){
$this->validateAuthAndGetUser();
$this->preLogout();
return $this->printMessage( $this->responseMessage("Logged out".session_id(), true) );
}
private function preLogout(){
$ocuser = new OCUser();
$res = $ocuser->Logout();
$_SESSION['user'] = "";
$_SESSION['id_user'] = "";
$_SESSION['user_type_id'] = "";
$_SESSION['userdata'] = "";
Persistant::logout();
}
}
?>