. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AnonSec Shell
AnonSec Shell
Server IP : 52.223.31.75  /  Your IP : 172.31.6.220   [ Reverse IP ]
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/davide/app/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www/davide/app/api.class.php
<?php 	

require 'vendor/autoload_p.php';

use PayPalCheckoutSdk\Orders\OrdersGetRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;

use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\ProductionEnvironment;

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 {
	
	/**
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * @author Angelo Pescatore
	 * @project GRAPJ
	 * 
	 * 
	 * 
	 * 
	 */
	
	
	
	
	
	protected $programme = 'GRAPJ';
	protected $awsAccessKey = 'AKIAJUBI752YQ3D4YE2A';
	protected $awsSecretKey = '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';
	protected $class = '../../app/resources/S3.php';
	protected $bucket = "asciiformazione";
	protected $amazon = "https://asciiformazione.s3.amazonaws.com/";	


	public $oreSfasamento;
	public $secondiSfasamento;

	/*
	 *
	 *	MEMCACHED
	 *
	 */

	public $memcached;


	function __construct(){
		$this->oreSfasamento = date("I",strtotime("now"))+1; //ora 	
		$this->secondiSfasamento = (date("I",strtotime("now"))+1)*3600; //ora 
		/*
		 *
		 *	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;
		}*/
	}
	


	

	


	/* 
	 *
	 * FUNZIONI DI MEMORIZZAZIONE SU MONGO DB
	 * 
	 */
	

	

	
	

	/*** 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 storeFileScheda($nome_file, $idScheda){

		$tmpMongo = new DBLinkMongo(FILE_INI_MDADB_MONGO);

		$id_mongo = $tmpMongo->storeFileScheda( $nome_file, $idScheda );

		if($id_mongo){
			return $id_mongo;
		}else{
			return false;
		}

	}



/*	public function getFile($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);

  			$this->showFile($file->getResource(), $contentType);


		}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) );

		}

	}

	/* 
	 *
	 * FUNZIONI DI SISTEMA PER VERIFICA TIPOLOGIA UTENTE 
	 * 
	 */
	
	protected function validateAuthAndGetUser(){
		$isloggedin = Persistant::IsloggedIn();
		if(!$isloggedin) {
			return $this->printMessage( $this->responseMessage('Authentication Error!', false) );
		} else {
			$session = $_SESSION;
			$userOps = new OCUser();

			$session['id_session'] = session_id();
			return $session["userdata"]; 
		}
	}

	public function validateAuthAndGetUserPublic(){
		$isloggedin = Persistant::IsloggedIn();
		if(!$isloggedin) {
			return $this->printMessage( $this->responseMessage('Authentication Error!', false) );
		} else {
			$session = $_SESSION;
			$userOps = new OCUser();

			$session['id_session'] = session_id();
			return $session["userdata"];
		}
	}

	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 checkBlog(){
		if($_SESSION["userdata"]["user_type_id"] ==234234 || $_SESSION["userdata"]["user_type_id"] ==830830) {
			return true;
		} else {
			return false;
		}
	}

	public function checkCentroPermission(){
		if($_SESSION["userdata"]["user_type_id"] ==236876) {
			return true;
		} else {
			return false;
		}
	}

	private function validaLdap(){
		return false; //INVALIDA ACL JAM
		
		print_r($_SESSION["userdata"]['groups']);
	}
	

	/* 
	 *
	 * FUNZIONI DI SISTEMA PER STAMPA JSON, GESTIONE FILE, MANIPOLAZIONI IMMAGINI (crop & resize)
	 * 
	 */


	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
		);
		return $data;
	}
	
	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;
	
	}
	//peo + jam//

	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;
	}
	
	
	
	/*this function is only used to verify new mime types
	private function generateUpToDateMimeArray($url){
	    $s=array();
	    foreach(@explode("\n",@file_get_contents($url))as $x)
	        if(isset($x[0])&&$x[0]!=='#'&&preg_match_all('#([^\s]+)#',$x,$out)&&isset($out[1])&&($c=count($out[1]))>1)
	            for($i=1;$i<$c;$i++)
	                $s[]='&nbsp;&nbsp;&nbsp;\''.$out[1][$i].'\' => \''.$out[1][0].'\''; 
	    return @sort($s)?'$mime_types = array(<br />'.implode($s,',<br />').'<br />);':false;
	}
*/
	
	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;
		}

	}
	
	private 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 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)) {
    		$emailMessage = new EmailMessage(true);

			//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 sul tuo nome 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 sul tuo nome 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, "info@".$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) );
	    	}

		}
	}


	public function recuperaPasswordCentro($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->recuperaPasswordCentro($email, $this->generatePassword($email));

    	if ($res) {
    		$emailMessage = new EmailMessage(true);

			//SEND EMAIL
			//SendMessage($subject, $htmlbody, $txtbody, $from, $to, $cc='', $bcc='', $replacements=array(), $filelocation=null, $filename=null, $filetype=null)
			//{
			$htmlbody = "Gentile Centro Ascii, <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 sul tuo nome 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>Link: <a href='https://centri.asciiformazione.it'>https://centri.asciiformazione.it</a> <br><br>Grazie di averci preferito e buon lavoro.";

			$txtbody = "Gentile Centro Ascii, \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 sul tuo nome nel menù laterale di sinistra\n2. Successivamente cliccando su 'Modifica password'.\n\n\nCredenziali\n***********\nUsername: $email\nPassword: $res\n\n Link: https://centri.asciiformazione.it \n\nGrazie di averci preferito e buon lavoro.";


			$emailCK = $emailMessage->SendMessage("Richiesta di recupero password ", $htmlbody, $txtbody, "info@".$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 MENU
	 * 
	 */


	public function getMenu($user_type_id = 294911, $parent = -1){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->getMenu($user_type_id, $parent);
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkUserPermission() == true) {
			return $this->printMessage( $this->responseMessage($result, true) );
		}else{
				return $this->printMessage( $this->responseMessage("non loggato", false) );
		}

	}

	public function pagamento($valore){
		$contentPagamento = new Content();
		$result = $contentPagamento->pagamento($valore);
		return $this->printMessage( $this->responseMessage($result, true) );
	}

	/* 
	 *
	 * 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) );
	}

	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) );

		}
		
	}


	private function getListaFilePrivate($tipo, $id){
		
		if($this->checkUserPermission() == true && $this->checkUserPermission()) {	

			$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) {
			           $toRet[]= /*$awsConfig['url'].*/end(explode("/", $object['Key']));
			        }
			    }
			} catch (S3Exception $e) {
			    $toRet[]= $e->getMessage();
			}
			
			
			return $toRet;

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
		
	}
	public function getFile($tipo, $id, $filename){
		
		if($this->checkUserPermission() == true && $this->checkUserPermission()) {	
			$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',
			    '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();

		    return $this->printMessage( $this->responseMessage($presignedUrl, true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}


		
	}

	private function get_http_response_code($url) {
	    $headers = get_headers($url);
	    return substr($headers[0], 9, 3);
	}





	public function getCertificatoCentroProva(){
		if($this->checkCentroPermission() == true) {	
			$idcentro = $_SESSION["userdata"]['idcentro'];
			$path_logo = "/var/www/ascii/generator_pdf/loghi_centri/".$idcentro.".png";

			$codice_centro= "ETC-".$utente['idcentro']."IT";  
			$nome_file_certificato= "certificato_".$codice_centro."_"."TEST";

	        $path_word = "/var/www/ascii/generator_pdf/dattilografia_universal/word/";
	        $path_tmp = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/word/";
	        $url_qr_code_image = $path_word."media/image3.png";
	        $url_tmp_qr_code_image = $path_tmp."media/image3.png";	
	        //copio logo centro per generazione
	        unlink($path_tmp."media/image1.png");
	        copy($path_logo, $path_tmp."media/image1.png");
			$documento = $path_word."document.xml";
	        $documento_tmp = $path_tmp."document.xml";
	        $doc = file_get_contents($documento);
			
	       
	        $data_esame_superato="DATA DI PROVA";
	        
	        $codice_certificato="NOCODE";
	        $link_verifica_certificato = "https://www.asciiformazione.it/verifica-certificato?code=".$codice_certificato;

	        $doc = str_replace("nome_cognome", "GENERAZIONE DI TEST", $doc);
	        $doc = str_replace("codice_fiscale", "codice fiscale", $doc);
	        $doc = str_replace("data_esame", $data_esame_superato, $doc);
	        $doc = str_replace("codice_certificato", $codice_certificato, $doc);
	        $doc = str_replace("codice_ce", $codice_centro, $doc);
	        $doc = str_replace("linkverificacert", $link_verifica_certificato, $doc);

	     
	        //genero codice qr
	        $qr_code_generato = file_get_contents('http://chart.apis.google.com/chart?chs=300x300&cht=qr&chld=L|0&chl=http://www.asciiformazione.it/verifica-certificato?code='.$codice_certificato);

	        //rimuovo old
	        unlink($url_tmp_qr_code_image);
	        unlink($documento_tmp);

	        

	        //aggiungo a certificato tmp
	        file_put_contents($url_tmp_qr_code_image, $qr_code_generato);
	        chown($url_tmp_qr_code_image, "ec2-user");
	        chmod($url_tmp_qr_code_image, 0775);
	        file_put_contents($documento_tmp, $doc);
	        chown($documento_tmp, "ec2-user");
	       	chmod($documento_tmp, 0775);

	        
	        //zip
	        // Enter the name of directory 
	        $pathdir = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/";  
	          
	        // Enter the name to creating zipped directory 
	        $zipcreated = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".zip"; 
	        $wordrename = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".docx"; 
	        $pdfrename = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".pdf"; 


	       	   
	        if(!$this->zippami($pathdir, $zipcreated)){
	        	return $this->printMessage($this->responseMessage("Errore nella generazione del certificato zip, si prega di riprovare!", false));
	        }
	      	
	        rename($zipcreated, $wordrename);

	        chown($wordrename, "ec2-user");
	       	chmod($wordrename, 0775);

	        unlink($nome_file_certificato.".zip");
	        //genera pdf
	        include SITEROOT_DIR.'/app/helpers/converterPdf.php';

	        $converter = new OfficeConverter($wordrename, null, "/var/www/ascii/generator_pdf/libreoffice/program/soffice.bin");
			$converter->convertTo($pdfrename); //generates pdf file in same directory as test-file.docx
		//	$converter->convertTo('output-file.html'); //generates html file in same directory as test-file.docx

			//to specify output directory, specify it as the second argument to the constructor
		//	$converter = new OfficeConverter($wordrename, $pathdir);

			chown($pdfrename, "ec2-user");
	       	chmod($pdfrename, 0775);

			if(!$converter){
				echo "Errore in conversione"; die;
			}
			
			unlink($wordrename);

			$type = pathinfo($pdfrename, PATHINFO_EXTENSION);
			$data = file_get_contents($pdfrename);
			$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
			unlink($pdfrename);
			return $this->printMessage($this->responseMessage($base64, true));

		}else{
			return $this->printMessage($this->responseMessage("Errore nella generazione del certificato, si prega di riprovare!", false));
		}	
		
	}

	public function deleteLogoCentro(){
		if($this->checkCentroPermission() == true) {	
			$idcentro = $_SESSION["userdata"]['idcentro'];
			$path_logo = "/var/www/ascii/generator_pdf/loghi_centri/".$idcentro.".png";
			if(unlink($path_logo)){
				return $this->printMessage($this->responseMessage("Logo cancellato correttamente!", true));
			}else{
				return $this->printMessage($this->responseMessage("Logo non cancellato!", false));
			}
		}else{
			return $this->printMessage($this->responseMessage("Non hai i permessi!", true));
		}
	}


	public function getLogoCentro(){
		if($this->checkCentroPermission() == true) {	
			$idcentro = $_SESSION["userdata"]['idcentro'];
			$path_logo = "/var/www/ascii/generator_pdf/loghi_centri/".$idcentro.".png";
			if(file_exists($path_logo)){
				$type = pathinfo($path_logo, PATHINFO_EXTENSION);
				$data = file_get_contents($path_logo);
				$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
				return $this->printMessage($this->responseMessage($base64, true));
			}else{
				return $this->printMessage($this->responseMessage("", true));
			}
		}else{
			return $this->printMessage($this->responseMessage("", true));
		}
	}

	public function cambiaLogoCentro($urllocalefile){
		if($this->checkCentroPermission() == true) {	
			$idcentro = $_SESSION["userdata"]['idcentro'];
			$path_logo = "/var/www/ascii/generator_pdf/loghi_centri/".$idcentro.".png";
			unlink($path_logo);
			if(copy($urllocalefile[0],$path_logo)){
				return $this->printMessage($this->responseMessage("Logo inserito correttamente!", true));
			}else{
				return $this->printMessage($this->responseMessage("Logo non copiato correttamente!", false));
			}
		}else{
			return $this->printMessage($this->responseMessage("", true));
		}

	}

	
	

	public function scaricaCertificatoDattilografia($idsessione, $idcliente,  $tipo, $force=false){
		$ocuser = new OCUser();
		$utente = $ocuser->checkSessionFrontend($idsessione,$idcliente,$tipo);
		if(count($utente)>0 && $utente[0]['dattilografia_success'] && $utente[0]['dattilografia_success_code']) {	
			$utente=$utente[0];
			$awsConfig = AWSCONFIG;
			//print_r($utente);die;
			if($tipo==1){
	          $idcliente=$utente['idclientedelcentro'];
	          $codice_centro= "ETC-".$utente['idcentro']."IT";  
	          $nome_file_certificato= "certificato_".$codice_centro."_".$idcliente;
	          $keyname = $awsConfig['cliente']."/clientidelcentro/".$idcliente."/".$nome_file_certificato.".pdf";
	        }else{
	          $codice_centro= "ETC-00001IT";
	          $idcliente=$utente['idcliente'];
	          $nome_file_certificato= "certificato_".$codice_centro."_".$idcliente;
	          $keyname = $awsConfig['cliente']."/clienti/".$idcliente."/".$nome_file_certificato.".pdf";
	        }
			

			$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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();


			// Check HTTP status code
			if(!$force){
				if ($this->get_http_response_code($presignedUrl)==200) {
					//se c'è il file lo mostro a video
				  	header("Location: $presignedUrl");
				  	die;
				}
			}
			//se non c'è il file su s3 genero   
			

			//recupero il logo del centro
			$path_logo = "/var/www/ascii/generator_pdf/loghi_centri/".$utente['idcentro'].".png";
			

			// if($tipo==1 && file_exists($path_logo)){ //è un centro e ha il logo
			// 	//se è un centro con il logo
		 //        $path_word = "/var/www/ascii/generator_pdf/dattilografia_centro/word/";
		 //        $path_tmp = "/var/www/ascii/generator_pdf/tmp_dattilografia_centro/word/";
		 //        $url_qr_code_image = $path_word."media/image3.png";
		 //        $url_tmp_qr_code_image = $path_tmp."media/image3.png";	
		 //        //copio logo centro per generazione
		 //        unlink($path_tmp."media/image1.png");
		 //        copy($path_logo, $path_tmp."media/image1.png");

		 //        // Enter the name of directory 
	  //       	$pathdir = "/var/www/ascii/generator_pdf/tmp_dattilografia_centro/";

			// }else{
			// 	//altrimenti
		 //        $path_word = "/var/www/ascii/generator_pdf/dattilografia/word/";
		 //        $path_tmp = "/var/www/ascii/generator_pdf/tmp_dattilografia/word/";
		 //        $url_qr_code_image = $path_word."media/image2.png";
		 //        $url_tmp_qr_code_image = $path_tmp."media/image2.png";
		 //        // Enter the name of directory 
	  //     		$pathdir = "/var/www/ascii/generator_pdf/tmp_dattilografia/";
			// }

			if($tipo==1 && file_exists($path_logo)){ //è un centro e ha il logo
				//se è un centro con il logo
		        $path_word = "/var/www/ascii/generator_pdf/dattilografia_universal/word/";
		        $path_tmp = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/word/";
		        $url_qr_code_image = $path_word."media/image3.png";
		        $url_tmp_qr_code_image = $path_tmp."media/image3.png";	
		        //copio logo centro per generazione
		        unlink($path_tmp."media/image1.png");
		        copy($path_logo, $path_tmp."media/image1.png");
		        chown($path_tmp."media/image1.png", "ec2-user");
	        	chmod($path_tmp."media/image1.png", 0775);

		        // Enter the name of directory 
	        	$pathdir = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/";

			}else{
				//altrimenti
		        $path_word = "/var/www/ascii/generator_pdf/dattilografia_universal/word/";
		        $path_tmp = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/word/";
		        $url_qr_code_image = $path_word."media/image3.png";
		        $url_tmp_qr_code_image = $path_tmp."media/image3.png";
		        //copio logo vuoto per generazione
		        unlink($path_tmp."media/image1.png");
		        $path_no_logo = "/var/www/ascii/generator_pdf/loghi_centri/nologo.png";
		        copy($path_no_logo, $path_tmp."media/image1.png");
		        chown($path_tmp."media/image1.png", "ec2-user");
	        	chmod($path_tmp."media/image1.png", 0775);
		        // Enter the name of directory 
	      		$pathdir = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/";
			}




			$documento = $path_word."document.xml";
	        $documento_tmp = $path_tmp."document.xml";
	        $doc = file_get_contents($documento);
			
	       
	        $data_esame_superato_=strtotime($utente["dattilografia_date_success"]);
	        switch (date( 'm', $data_esame_superato_ )) {
	        	case '01':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " GENNAIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '02':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " FEBBRAIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        
	        	case '03':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " MARZO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '04':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " APRILE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '05':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " MAGGIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '06':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " GIUGNO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '07':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " LUGLIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '08':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " AGOSTO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '09':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " SETTEMBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '10':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " OTTOBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '11':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " NOVEMBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '12':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " DICEMBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        
	        }
	        
	        $codice_certificato=$utente["dattilografia_success_code"];
	        $link_verifica_certificato = "https://www.asciiformazione.it/verifica-certificato?code=".$codice_certificato;

	        $doc = str_replace("nome_cognome", strtoupper($utente['ragionesociale']), $doc);
	        $doc = str_replace("codice_fiscale", strtoupper($utente['codicefiscale']), $doc);
	        $doc = str_replace("data_esame", $data_esame_superato, $doc);
	        $doc = str_replace("codice_certificato", $codice_certificato, $doc);
	        $doc = str_replace("codice_ce", $codice_centro, $doc);
	        $doc = str_replace("linkverificacert", $link_verifica_certificato, $doc);

	     	$qr_code_generato = false;
	        //genero codice qr
	        for ($i=0; $i < 10; $i++) { 
	        	if($qr_code_generato === false){
	        		$qr_code_generato = file_get_contents('http://chart.apis.google.com/chart?chs=300x300&cht=qr&chld=L|0&chl=http://www.asciiformazione.it/verifica-certificato?code='.$codice_certificato);
	        	}else{
	        		break;
	        	}
	        }
	        

	        //rimuovo old
	        unlink($url_tmp_qr_code_image);
	        unlink($documento_tmp);

	        

	        //aggiungo a certificato tmp
	        file_put_contents($url_tmp_qr_code_image, $qr_code_generato);
	        chown($url_tmp_qr_code_image, "ec2-user");
	        chmod($url_tmp_qr_code_image, 0775);
	        file_put_contents($documento_tmp, $doc);
	        chown($documento_tmp, "ec2-user");
	       	chmod($documento_tmp, 0775);

	        
	        //zip

	          
	          
	        // Enter the name to creating zipped directory 
	        $zipcreated = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".zip"; 
	        $wordrename = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".docx"; 
	        $pdfrename = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".pdf"; 


	       	   
	        if(!$this->zippami($pathdir, $zipcreated)){
	        	return $this->printMessage($this->responseMessage("Errore nella generazione del certificato zip, si prega di riprovare!", false));
	        }
	      	
	        rename($zipcreated, $wordrename);

	        chown($wordrename, "ec2-user");
	       	chmod($wordrename, 0775);

	        unlink($nome_file_certificato.".zip");
	        //genera pdf
	        include SITEROOT_DIR.'/app/helpers/converterPdf.php';

	        $converter = new OfficeConverter($wordrename, null, "/var/www/ascii/generator_pdf/libreoffice/program/soffice.bin");
			$converter->convertTo($pdfrename); //generates pdf file in same directory as test-file.docx
		//	$converter->convertTo('output-file.html'); //generates html file in same directory as test-file.docx

			//to specify output directory, specify it as the second argument to the constructor
		//	$converter = new OfficeConverter($wordrename, $pathdir);

			chown($pdfrename, "ec2-user");
	       	chmod($pdfrename, 0775);

			if(!$converter){
				echo "Errore in conversione"; die;
			}
			

			unlink($wordrename);

			
	        //upload s3
	        if($tipo){
      			$url = $this->putFileS3Private("clientidelcentro", $idcliente, $pdfrename);	
      		}else{
      			$url = $this->putFileS3Private("clienti", $idcliente, $pdfrename);	
      		}

      		$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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($presignedUrl){
				unlink($pdfrename);
				header("Location: $presignedUrl");
				die;
			}else{
				return $this->printMessage($this->responseMessage("Errore nella generazione del certificato, si prega di riprovare!", false));
			}			

		}else{

			echo '<h1>Non hai i permessi per accedere a questa risorsa oppure non hai superato ancora l\'esame, prova ad effettuare il logout ed effettuare nuovamente il login per poi riprovare!</h1>';die;

		}

	}

	public function scaricaCertificatoSicurezza($idsessione, $idcliente,  $tipo, $force=false){
		$ocuser = new OCUser();
		$utente = $ocuser->checkSessionFrontend($idsessione,$idcliente,$tipo);
		if(count($utente)>0 && $utente[0]['sicurezza_success']) {	
			$utente=$utente[0];
			$awsConfig = AWSCONFIG;
			//print_r($utente);die;
			/*if($tipo==1){
	          $idcliente=$utente['idclientedelcentro'];
	          $codice_centro= "ETC-".$utente['idcentro']."IT";  
	          $nome_file_certificato= "certificato_".$codice_centro."_".$idcliente;
	          $keyname = $awsConfig['cliente']."/clientidelcentro/".$idcliente."/".$nome_file_certificato.".pdf";
	        }else{*/
	          $codice_centro= "ITI-00001360";
	          $idcliente=$utente['idcliente'];
	          $nome_file_certificato= "certificato_".$codice_centro."_".$idcliente;
	          $keyname = $awsConfig['cliente']."/clienti/".$idcliente."/".$nome_file_certificato.".pdf";
	        //}
			

			$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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();


			// Check HTTP status code
			if(!$force){
				if ($this->get_http_response_code($presignedUrl)==200) {
					//se c'è il file lo mostro a video
				  	header("Location: $presignedUrl");
				  	die;
				}
			}
			//se non c'è il file su s3 genero   
			

			//recupero il logo del centro
			$path_logo = "/var/www/ascii/generator_pdf/loghi_centri/".$utente['idcentro'].".png";
			

		/*	if($tipo==1 && file_exists($path_logo)){ //è un centro e ha il logo
				//se è un centro con il logo
		        $path_word = "/var/www/ascii/generator_pdf/dattilografia_universal/word/";
		        $path_tmp = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/word/";
		        $url_qr_code_image = $path_word."media/image3.png";
		        $url_tmp_qr_code_image = $path_tmp."media/image3.png";	
		        //copio logo centro per generazione
		        unlink($path_tmp."media/image1.png");
		        copy($path_logo, $path_tmp."media/image1.png");
		        chown($path_tmp."media/image1.png", "ec2-user");
	        	chmod($path_tmp."media/image1.png", 0775);

		        // Enter the name of directory 
	        	$pathdir = "/var/www/ascii/generator_pdf/tmp_dattilografia_universal/";

			}else{*/
				//altrimenti
		        $path_word = "/var/www/ascii/generator_pdf/sicurezza_universal/word/";
		        $path_tmp = "/var/www/ascii/generator_pdf/tmp_sicurezza_universal/word/";
		        $url_qr_code_image = $path_word."media/image3.png";
		        $url_tmp_qr_code_image = $path_tmp."media/image3.png";
		        //copio logo vuoto per generazione
		        unlink($path_tmp."media/image1.png");
		        $path_no_logo = "/var/www/ascii/generator_pdf/loghi_centri/nologo.png";
		        copy($path_no_logo, $path_tmp."media/image1.png");
		        chown($path_tmp."media/image1.png", "ec2-user");
	        	chmod($path_tmp."media/image1.png", 0775);
		        // Enter the name of directory 
	      		$pathdir = "/var/www/ascii/generator_pdf/tmp_sicurezza_universal/";
//			}




			$documento = $path_word."document.xml";
	        $documento_tmp = $path_tmp."document.xml";
	        $doc = file_get_contents($documento);
			
	       
	        $data_esame_superato_=strtotime($utente["dattilografia_date_success"]);
	        switch (date( 'm', $data_esame_superato_ )) {
	        	case '01':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " GENNAIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '02':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " FEBBRAIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        
	        	case '03':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " MARZO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '04':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " APRILE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '05':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " MAGGIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '06':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " GIUGNO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '07':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " LUGLIO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '08':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " AGOSTO " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '09':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " SETTEMBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '10':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " OTTOBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '11':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " NOVEMBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        	case '12':
	        		$data_esame_superato=date( 'd', $data_esame_superato_ ). " DICEMBRE " .date( 'Y', $data_esame_superato_ );
	        		break;
	        
	        }
	        
	        $codice_certificato=$utente["sicurezza_success_code"];
	        $link_verifica_certificato = "https://www.formazione360.it/verifica-certificato?code=".$codice_certificato;

	        $doc = str_replace("nome_cognome", strtoupper($utente['ragionesociale']), $doc);
	        $doc = str_replace("codice_fiscale", strtoupper($utente['codicefiscale']), $doc);
	        $doc = str_replace("data_esame", $data_esame_superato, $doc);
	        $doc = str_replace("codice_certificato", $codice_certificato, $doc);
	        $doc = str_replace("codice_ce", $codice_centro, $doc);
	        $doc = str_replace("linkverificacert", $link_verifica_certificato, $doc);

	     	$qr_code_generato = false;
	        //genero codice qr
	        for ($i=0; $i < 10; $i++) { 
	        	if($qr_code_generato === false){
	        		$qr_code_generato = file_get_contents('http://chart.apis.google.com/chart?chs=300x300&cht=qr&chld=L|0&chl=http://www.formazione360.it/verifica-certificato?code='.$codice_certificato);
	        	}else{
	        		break;
	        	}
	        }
	        

	        //rimuovo old
	        unlink($url_tmp_qr_code_image);
	        unlink($documento_tmp);

	        

	        //aggiungo a certificato tmp
	        file_put_contents($url_tmp_qr_code_image, $qr_code_generato);
	        chown($url_tmp_qr_code_image, "ec2-user");
	        chmod($url_tmp_qr_code_image, 0775);
	        file_put_contents($documento_tmp, $doc);
	        chown($documento_tmp, "ec2-user");
	       	chmod($documento_tmp, 0775);

	        
	        //zip

	          
	          
	        // Enter the name to creating zipped directory 
	        $zipcreated = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".zip"; 
	        $wordrename = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".docx"; 
	        $pdfrename = "/var/www/ascii/generator_pdf/".$nome_file_certificato.".pdf"; 


	       	   
	        if(!$this->zippami($pathdir, $zipcreated)){
	        	return $this->printMessage($this->responseMessage("Errore nella generazione del certificato zip, si prega di riprovare!", false));
	        }
	      	
	        rename($zipcreated, $wordrename);

	        chown($wordrename, "ec2-user");
	       	chmod($wordrename, 0775);

	        unlink($nome_file_certificato.".zip");
	        //genera pdf
	        include SITEROOT_DIR.'/app/helpers/converterPdf.php';

	        $converter = new OfficeConverter($wordrename, null, "/var/www/ascii/generator_pdf/libreoffice/program/soffice.bin");
			$converter->convertTo($pdfrename); //generates pdf file in same directory as test-file.docx
		//	$converter->convertTo('output-file.html'); //generates html file in same directory as test-file.docx

			//to specify output directory, specify it as the second argument to the constructor
		//	$converter = new OfficeConverter($wordrename, $pathdir);

			chown($pdfrename, "ec2-user");
	       	chmod($pdfrename, 0775);

			if(!$converter){
				echo "Errore in conversione"; die;
			}
			

			unlink($wordrename);

			
	        //upload s3
	        /*if($tipo){
      			$url = $this->putFileS3Private("clientidelcentro", $idcliente, $pdfrename);	
      		}else{*/
      			$url = $this->putFileS3Private("clienti", $idcliente, $pdfrename);	
      		//}

      		$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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($presignedUrl){
				unlink($pdfrename);
				header("Location: $presignedUrl");
				die;
			}else{
				return $this->printMessage($this->responseMessage("Errore nella generazione del certificato, si prega di riprovare!", false));
			}			

		}else{

			echo '<h1>Non hai i permessi per accedere a questa risorsa oppure non hai superato ancora l\'esame, prova ad effettuare il logout ed effettuare nuovamente il login per poi riprovare!</h1>';die;

		}

	}

	private 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 docInglese($idsessione, $idcliente, $tipo){
		$ocuser = new OCUser();
		if(count($ocuser->checkSessionFrontend($idsessione,$idcliente,false))>0) {	
			$awsConfig = AWSCONFIG;
			
			//$sdk = new Aws\Sdk($awsConfig);
			//$bucket = $awsConfig['bucket'];
			
			//$s3 = $sdk->createS3();
			$keyname = $awsConfig['cliente']."/documentazione_corsi/inglese/ascii-formazione-inglese.zip";
			//echo $keyname;
			$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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();

			header("Location: $presignedUrl");
			die;
		    //return $this->printMessage( $this->responseMessage($presignedUrl, true) );

		}else{

			echo '<h1>Non hai i permessi per accedere a questa risorsa, prova ad effettuare il logout ed effettuare nuovamente il login per poi riprovare!</h1>';die;

		}


		
	}

	public function docSicurezza($idsessione, $idcliente, $tipo){
		$ocuser = new OCUser();
		if(count($ocuser->checkSessionFrontend($idsessione,$idcliente,$tipo))>0) {	
			$awsConfig = AWSCONFIG;

			$cont = new Content();
			//$res = $cont->setClienteSicurezza($idCliente);
			
			//$sdk = new Aws\Sdk($awsConfig);
			//$bucket = $awsConfig['bucket'];
			
			//$s3 = $sdk->createS3();
			$keyname = $awsConfig['cliente']."/documentazione_corsi/sicurezza/sicurezza.zip";
			//echo $keyname;
			$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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();

			header("Location: $presignedUrl");
			die;
		    //return $this->printMessage( $this->responseMessage($presignedUrl, true) );

		}else{

			echo '<h1>Non hai i permessi per accedere a questa risorsa, prova ad effettuare il logout ed effettuare nuovamente il login per poi riprovare!</h1>';die;

		}


		
	}

	public function docDattilografia($idsessione, $idcliente, $tipo){
		$ocuser = new OCUser();
		if(count($ocuser->checkSessionFrontend($idsessione,$idcliente,$tipo))>0) {	
			$awsConfig = AWSCONFIG;
			
			//$sdk = new Aws\Sdk($awsConfig);
			//$bucket = $awsConfig['bucket'];
			
			//$s3 = $sdk->createS3();
			$keyname = $awsConfig['cliente']."/documentazione_corsi/dattilografia/ASCII-FORMAZIONE-CORSO-DATTILOGRAFIA-ADDESTRAMENTO-PROFESSIONALE.pdf";
			//echo $keyname;
			$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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();

			header("Location: $presignedUrl");
			die;
		    //return $this->printMessage( $this->responseMessage($presignedUrl, true) );

		}else{

			echo '<h1>Non hai i permessi per accedere a questa risorsa, prova ad effettuare il logout ed effettuare nuovamente il login per poi riprovare!</h1>';die;

		}


		
	}

	public function docDSGA($idsessione, $idcliente, $tipo, $cartella=null){
		$ocuser = new OCUser();
		if(count($ocuser->checkSessionFrontend($idsessione,$idcliente,$tipo))>0) {	
			$awsConfig = AWSCONFIG;
			
			//$sdk = new Aws\Sdk($awsConfig);
			//$bucket = $awsConfig['bucket'];
			
			//$s3 = $sdk->createS3();
			if($caterlla){
				$keyname = $awsConfig['cliente']."/documentazione_corsi/dsga/".$cartella."/".$cartella.".pdf";
			}else{
				$keyname = $awsConfig['cliente']."/documentazione_corsi/dsga/Introduzione.pdf";
			}
			
			//echo $keyname;
			$s3Client = new Aws\S3\S3Client([
			    'profile' => 'default',
			    '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();

			header("Location: $presignedUrl");
			die;
		    //return $this->printMessage( $this->responseMessage($presignedUrl, true) );

		}else{

			echo '<h1>Non hai i permessi per accedere a questa risorsa, prova ad effettuare il logout ed effettuare nuovamente il login per poi riprovare!</h1>';die;

		}


		
	}

	public function getListaFile($tipo, $id){
		
		if($this->checkUserPermission() == true && $this->checkUserPermission()) {	

			$toRet = $this->getListaFilePrivate($tipo, $id);	
			
			return $this->printMessage( $this->responseMessage($toRet, true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
		
	}

	public function inviaRichiestaCrediti($titolo, $contenuto, $crediti){
		
		if($this->checkCentroPermission() == true) {	
			$idcentro = $_SESSION["userdata"]['idcentro'];
			require_once SITEROOT_DIR.'/app/helpers/emailmessage.php';
			include "app/components/centri/api.class.php";
			$contentCentri = new ContentCentri();

    		$emailMessage = new EmailMessage(true);
			$centro = $contentCentri->getCentro($idcentro)[0];
			$nusers=($centro['utenti_totali'])?$centro['utenti_totali']:0;
			$actnusers=($centro['utenti_attivati'])?$centro['utenti_attivati']:0;
			//print_r($centro);die;
			$htmlbody = "Numero Crediti Richiesti: <b>".$crediti."</b><br>";
			$htmlbody.= "Nome Centro: <b>".$centro['ragionesociale']."</b><br>";
			$htmlbody.= "Indirizzo Centro: <b>".$centro['indirizzo']." - ".$centro['citta']."</b><br>";
			$htmlbody.= "Email Centro: <b><a href='mailto:".$centro['email']."'>".$centro['email']."</a></b><br>";
			$htmlbody.= "Crediti Attualmente Disponibili: <b>".$centro['crediti_disponibili']."</b><br>";
			$htmlbody.= "Utenti Totali: <b>".$nusers."</b><br>";
			$htmlbody.= "Utenti Attivati: <b>".$actnusers."</b><br><br>";

			$htmlbody.= "Messaggio del cliente: <b>".$contenuto."</b><br><br>Buon Lavoro!";


			$emailCK = $emailMessage->SendMessage($titolo, $htmlbody, $htmlbody, "info@".$this->getDominio(), "info@".$this->getDominio());
			
			if($emailCK){
				return $this->printMessage( $this->responseMessage("L'email contenente le informazioni è 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) );
			}
			
			return $this->printMessage( $this->responseMessage($toRet, true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
		
	}


	public function putFileS3($tipo, $id, $urllocalefile){

		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true)
		{
			$toRet = $this->putFileS3Private($tipo, $id, $urllocalefile[0]);
			if($toRet){
				return $this->printMessage($this->responseMessage($toRet, true));
			}else{
				return $this->printMessage($this->responseMessage("File non caricato!", false));
			}
			
		}
		else
		{
			return $this->printMessage($this->responseMessage("Pemessi non sufficienti!", false));
		}
		
	}

	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));
		}
		
	}

	private 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'];
		
		}catch(Exception $e){
			
			return false;//$e->getMessage() . PHP_EOL;
		}
		//fine for
	}

	public function putFileS3Private($tipo, $id, $urllocalefile){
		// Create an SDK class used to share configuration across clients.

		/*	use Aws\Common\Exception\MultipartUploadException;
			use Aws\S3\MultipartUploader;
			use Aws\S3\S3Client;
		*/	

		$urllocalefile_nopath = 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'
				)
			);
			
			
			
			return $result['ObjectURL'];
		
		}catch(Exception $e){
			//echo $e->getMessage();
			
			return false;//$e->getMessage() . PHP_EOL;
		}
		//fine for
	}

	public function getFileClientedelcentro($idcliente){
		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true)
		{
			 $toRet = array("cliente"=>$this->getListaFilePrivate("clientidelcentro", $idcliente));//, "pratiche"=>array());	
				
			 return $this->printMessage( $this->responseMessage($toRet, true) );
			
		}
		else
		{
			return $this->printMessage($this->responseMessage("Permessi non sufficienti!", false));
		}
	}


	public function getFileCliente($idcliente){
		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true)
		{
			 $toRet = array("cliente"=>$this->getListaFilePrivate("clienti", $idcliente));//, "pratiche"=>array());	
				
			 return $this->printMessage( $this->responseMessage($toRet, true) );
			
		}
		else
		{
			return $this->printMessage($this->responseMessage("Permessi non sufficienti!", false));
		}
	}

	public function getFilePartner($idpartner){
		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true)
		{
			 $toRet = array("partner"=>$this->getListaFilePrivate("partner", $idpartner));//, "pratiche"=>array());	
				
			 return $this->printMessage( $this->responseMessage($toRet, true) );
			
		}
		else
		{
			return $this->printMessage($this->responseMessage("Permessi non sufficienti!", false));
		}
	}
	
	public function getFileCentri($idcentri){
		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true)
		{
			 $toRet = array("centri"=>$this->getListaFilePrivate("centri", $idcentri));//, "pratiche"=>array());	
				
			 return $this->printMessage( $this->responseMessage($toRet, true) );
			
		}
		else
		{
			return $this->printMessage($this->responseMessage("Permessi non sufficienti!", false));
		}
	}
	

	public function inviaComunicazioneMassiva($oggetto, $messaggio, $clienti)
	{
		$array_clienti = explode(",", $clienti);

		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true)
		{

			$cont = new Content();
			require_once SITEROOT_DIR.'/app/helpers/emailmessage.php';
			$emailMessage = new EmailMessage(true);

			$messaggio_utente= $messaggio;
			$conta=0;
			for ($i=0; $i < count($array_clienti); $i++) { 
				$email_cliente = $cont->getClienteEmail($array_clienti[$i]);

				if(!$email_cliente || $email_cliente==" "){
					continue;
				}

				if ($_SERVER['HTTP_HOST']=="admin.formazione-360.it") {
					$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>Formazione 360<br><br>Email: info@formazione-360.it<br>www.formazione-360.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto.' - Formazione 360.it', $messaggio_utente, $messaggio_utente,"info@formazione-360.it", $email_cliente);
					
			    }else if ($_SERVER['HTTP_HOST']=="admin.scuolabuona.it") {
					$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>Scuola Buona<br><br>Email: info@scuolabuona.it<br>www.scuolabuona.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto.' - Scuolabuona.it', $messaggio_utente, $messaggio_utente,"info@scuolabuona.it", $email_cliente);
					
			    }else if ($_SERVER['HTTP_HOST']=="admin.minerva-form.it") {
			    	//ascii
			    	$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>www.minerva-form.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto.' - Minerva-Form.it', $messaggio_utente, $messaggio_utente,"info@minerva-form.it", $email_cliente);
			    }else if ($_SERVER['HTTP_HOST']=="admin.sindacatosalerno.it") {
			    	//ascii
			    	$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>www.sindacatosalerno.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto.' - SindacatoSalerno.it', $messaggio_utente, $messaggio_utente,"info@sindacatosalerno.it", $email_cliente);
			    }else{
			    	
			    	$messaggio_utente.= "<br><br>ASCII Formazione<br>Via Irno 101, 84135 - Salerno<br>Email: info@asciiformazione.it<br>Tel. 089-98.49.407, 089-28.64.695";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto.' - ASCIIFormazione.it', $messaggio_utente, $messaggio_utente,"info@asciiformazione.it", $email_cliente);
			    }
    			$conta++;
			}
			$log.= "Email Totali inviate: " . $conta;

			file_put_contents(SITEROOT_DIR."/log/massive-email/"."log-".$_SERVER['HTTP_HOST']."-".date("Y-m-d H:i:s").".txt", $log);

			if($emailCK){
				return $this->printMessage( $this->responseMessage("L'email è 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) );
			}

			return $this->printMessage($this->responseMessage("bo", true));
						return $this->printMessage($this->responseMessage("Comunicazione non inviata!", false));

		}
		else
		{
			return $this->printMessage($this->responseMessage("Permessi non sufficienti!", false));
		}
		
	}

	public function inviaCorsoViaEmail($oggetto, $idcorso, $emails, $messaggioheader, $messaggiofooter)
	{
		if($messaggioheader=="MESSAGGIOHEADER"){
			$messaggioheader="";
		}

		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true)
		{
			

			require_once SITEROOT_DIR.'/app/helpers/emailmessage.php';
			include SITEROOT_DIR.'/app/components/corso/helper/content.php';
    		$emailMessage = new EmailMessage(true);
    		$emails = explode(",",$emails);

			$con = new ContentCorso();
			$cont = new Content();
			
			$ilcorso= $con->getCorso($idcorso);

			$corso = "<b>Titolo: </b>". $ilcorso['titolo']. "<br>". $ilcorso['descrizione']. "<br><br>";
			$corsoNo = "Titolo: ". $ilcorso['titolo']. "\n". $ilcorso['descrizione']. "\n\n";
			if($ilcorso['prezzo']){
				$corso.="<b>Prezzo: </b>".$ilcorso['prezzo']."<br><br>";
				$corsoNo.="Prezzo: ".$ilcorso['prezzo']."\n\n";
			}

			
			if($ilcorso['finalita']){
				$corso.="<b>Finalita: </b>".$ilcorso['finalita']."<br><br>";
				$corsoNo.="Finalita: ".$ilcorso['finalita']."\n\n";
			}
			if($ilcorso['programma']){
				$corso.="<b>Programma: </b>".$ilcorso['programma']."<br><br>";
				$corsoNo.="Programma: ".$ilcorso['programma']."\n\n";
			}
			if($ilcorso['destinatari']){
				$corso.="<b>Destinatari: </b>".$ilcorso['destinatari']."<br><br>";
				$corsoNo.="Destinatari: ".$ilcorso['destinatari']."\n\n";
			}
			if($ilcorso['contenuti']){
				$corso.="<b>Contenuti: </b>".$ilcorso['contenuti']."<br><br>";
				$corsoNo.="Contenuti: ".$ilcorso['contenuti']."\n\n";
			}
			if($ilcorso['caratteristiche']){
				$corso.="<b>Caratteristiche: </b>".$ilcorso['caratteristiche']."<br><br>";
				$corsoNo.="Caratteristiche: ".$ilcorso['caratteristiche']."\n\n";
			}
			if($ilcorso['durata']){
				$corso.="<b>Durata: </b>".$ilcorso['durata']."<br><br>";
				$corsoNo.="Durata: ".$ilcorso['durata']."\n\n";
			}

			$titolocorso = $ilcorso['titolo'];

			if(ABILITA_CORSO){
				$htmlbody = "Gentile Utente,<br>di seguito troverai le informazioni sul corso richiesto.<br> $messaggioheader<br><br> $corso<br><br>$messaggiofooter<br><br>";
			}else{
				$htmlbody = "Gentile Utente,<br>di seguito troverai le informazioni sul servizio richiesto.<br> $messaggioheader<br><br> $corso<br><br>$messaggiofooter<br><br>";
			}
			


			$messaggio_utente= $htmlbody;
			$conta=0;
			$titolocorso = $ilcorso['titolo'];

			for ($i=0; $i < count($emails); $i++) { 
				$email_cliente = $emails[$i];

				if(!$email_cliente || $email_cliente==" "){
					continue;
				}

				if ($_SERVER['HTTP_HOST']=="admin.formazione-360.it") {
					$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>Formazione 360<br><br>Email: info@formazione-360.it<br>www.formazione-360.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto." - Richiesta di informazione per il corso $titolocorso - Formazione 360.it", $messaggio_utente, $messaggio_utente,"info@formazione-360.it", $email_cliente);
					
			    }else if ($_SERVER['HTTP_HOST']=="admin.scuolabuona.it") {
					$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>Scuola Buona<br><br>Email: info@scuolabuona.it<br>www.scuolabuona.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto." - Richiesta di informazione per il corso $titolocorso - Scuolabuona.it", $messaggio_utente, $messaggio_utente,"info@scuolabuona.it", $email_cliente);
					
			    }else if ($_SERVER['HTTP_HOST']=="admin.minerva-form.it") {
			    	//ascii
			    	$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>www.minerva-form.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto." - Richiesta di informazione per il corso $titolocorso - Minerva-Form.it", $messaggio_utente, $messaggio_utente,"info@minerva-form.it", $email_cliente);
			    }else if ($_SERVER['HTTP_HOST']=="admin.sindacatosalerno.it") {
			    	//ascii
			    	$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>www.sindacatosalerno.it";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto." - Richiesta di informazione per il servizio $titolocorso - SindacatoSalerno.it", $messaggio_utente, $messaggio_utente,"info@sindacatosalerno.it", $email_cliente);
			    }else{
			    	
			    	$messaggio_utente.= "<br><br>ASCII Formazione<br>Via Irno 101, 84135 - Salerno<br>Email: info@asciiformazione.it<br>Tel. 089-98.49.407, 089-28.64.695";
	            			
					$emailCK = $emailMessage->SendMessage($oggetto." - Richiesta di informazione per il corso $titolocorso - ASCIIFormazione.it", $messaggio_utente, $messaggio_utente,"info@asciiformazione.it", $email_cliente);
			    }
			    $log.= "Email inviata a: ".$email_cliente;
    			$conta++;
			}
		//	var_dump($emailCK); die;
			$log.= "Email Totali inviate: " . $conta;

			file_put_contents(SITEROOT_DIR."/log/corso-email/"."log-".$_SERVER['HTTP_HOST']."-".date("Y-m-d H:i:s").".txt", $log);

			return $this->printMessage( $this->responseMessage("L'email contenente le informazioni è 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
		{
			return $this->printMessage($this->responseMessage("Comunicazione non inviata!", false));
		}
		
	}

	/* 
	 *
	 * METODO PUBBLICO CHE MOSTRA TUTTI I FILE PRESENTI IN UNA CARTELLA SPECIFICA (utile per slishow dinamiche)
	 * 
	 */

	public function getSlide(){
		$dir    = SITEROOT_DIR.'/www/images/slide-home-banner';

		$files = scandir($dir);
		$return = array();
		foreach ($files as $key => $value) {
			if($files[$key]!="." && $files[$key]!=".." && $files[$key]!=".DS_Store"){
				$return[] = $files[$key];
			}
		}

		return $this->printMessage( $this->responseMessage($return, true) );	
	}


	/* 
	 *
	 * METODI PUBBLICI PER IL LOGIN SOCIALE
	 * 
	 */

	public function getLinkButtonLoginFacebook(){
		require_once SITEROOT_DIR.'/app/resources/facebook-for-php-5-3/facebook.php';
		$facebook = new facebook(true);
		$loginUrl = $facebook->getLoginUrl();
		return $this->printMessage( $this->responseMessage($loginUrl, true) );

	}

	public function getLinkButtonLogoutFacebook(){
		require_once SITEROOT_DIR.'/app/resources/facebook-for-php-5-3/facebook.php';

		$loginUrl = $facebook->getLogOutUrl();
		return $this->printMessage( $this->responseMessage($loginUrl, true) );

	}


	public function getInformationFromFacebook($username, $password){
		require_once SITEROOT_DIR.'/app/helpers/persistant.php';
		require_once SITEROOT_DIR.'/app/helpers/ocuser.php';

   		//if is first registration from facebook
		require_once SITEROOT_DIR.'/app/resources/facebook-for-php-5-3/facebook.php';

		// Get User ID
		$user = $facebook->getUser();
		if ($user) {
		  try {
		    // Proceed knowing you have a logged in user who's authenticated.
		    $user_profile = $facebook->api('/me');
			return $this->printMessage( $this->responseMessage($user_profile, true) );
		  } catch (FacebookApiException $e) {
			return $this->printMessage( $this->responseMessage($facebook->getLoginUrl(), false) );
		  }
		}

	}
	
	//END FACEBOOK

	/* 
	 *
	 * METODI PUBBLICO PER IL LOGIN 
	 * 
	 */
	public function modificaPassword($oldpwd, $newpwd){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {

			$ocuser = new OCUser();
			$result = $ocuser->modificaPassword($user['id_user'], $oldpwd, $newpwd);

			return $this->printMessage( $this->responseMessage($result, $result) );
		}else{
			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );
		}
	}

	public function login($username, $password){
		require_once SITEROOT_DIR.'/app/helpers/persistant.php';
		require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
		$ocuser = new OCUser(true);
		$res = $ocuser->Login($username ,$password);
    	if ($res) {
        	for ($i=0; $i < 300; $i++) { 
        		$res['accessPage'][] = $i;
        	}

        	Persistant::SetLoginStatus(true);
        	Persistant::SetUserInfo($res);
        	$_SESSION['user'] = $res['id_user'];
        	return $this->printMessage( $this->responseMessage($res, true) );
    	} else {

    		/*check ldap
			$tmpLDAP = new AuthLdap(FILE_INI_LDAP);
	    	$resultldap = $tmpLDAP->checkLogin($username, $password);


	    	
	    	if($resultldap){

	    		$resultldap['groups'] = $ocuser->getGroupsUsersByIdLdap($resultldap['id_user']);
	    		

	    		if(count($resultldap['groups'])){
	    			//prendo le pagine a cui può accedere l'utente
	    			$resultldap['accessPage'] = $ocuser->getPagesFromGroups($resultldap['groups']);

	    			Persistant::SetLoginStatus(true);
		        	Persistant::SetUserInfo($resultldap);
		        	$_SESSION['user'] = $resultldap['id_user'];
		    		return $this->printMessage( $this->responseMessage($resultldap, true) );
	    		}else{
	    			return $this->printMessage( $this->responseMessage("Non disponi dei permessi per accedere al sistema!", false) );
	    		}

	    		
	    	}else{*/
				return $this->printMessage( $this->responseMessage("Credenziali non corrette si prega di riprovare!", false) );
	    	//}

		}
	}
	
	public function logout(){
		$this->validateAuthAndGetUser();
		$ocuser = new OCUser();
		$res = $ocuser->Logout();
		$_SESSION['user'] = "";
		$_SESSION['id_user'] = "";
		$_SESSION['user_type_id'] = "";
		$_SESSION['userdata'] = "";
		Persistant::SetAdminStatus(false);
		Persistant::SetLoginStatus(false);
		//$this->login(null,null);
		if(session_id()){
			forceDeleteSession(session_id());
		}
	

        return $this->printMessage( $this->responseMessage("Logged out".session_id(), true) );
	}


	public function loginCentro($username, $password){
		require_once SITEROOT_DIR.'/app/helpers/persistant.php';
		require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
		$ocuser = new OCUser(true);
		$res = $ocuser->LoginCentro($username ,$password);
    	if ($res) {
        	for ($i=0; $i < 300; $i++) { 
        		$res['accessPage'][] = $i;
        	}

        	Persistant::SetLoginStatus(true);
        	Persistant::SetUserInfo($res);
        	$_SESSION['user'] = $res['id_user'];
        	return $this->printMessage( $this->responseMessage($res, true) );
    	} else {

				return $this->printMessage( $this->responseMessage("Credenziali non corrette si prega di riprovare!", false) );
		}
	}
	
	public function logoutCentro(){
		$this->validateAuthAndGetUser();
		$ocuser = new OCUser();
		$res = $ocuser->LogoutCentro();
		$_SESSION['user'] = "";
		$_SESSION['id_user'] = "";
		$_SESSION['user_type_id'] = "";
		$_SESSION['userdata'] = "";
		Persistant::SetAdminStatus(false);
		Persistant::SetLoginStatus(false);
		//$this->login(null,null);
		if(session_id()){
			forceDeleteSession(session_id());
		}
	

        return $this->printMessage( $this->responseMessage("Logged out".session_id(), true) );
	}
	




	/* 
	 *
	 * METODI AMMINISTRAZIONE: UTENTI (con intergrazione LDAP)
	 * 
	 */
	
	
	/**
	 * USER
	 * Enter description here ...
	 * @param unknown_type $email
	 * @param unknown_type $firstname
	 * @param unknown_type $lastname
	 * @param unknown_type $type
	 */

	
	public function getLogLogin($iduser = null){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {

			$ocuser = new OCUser();
			$result = $ocuser->getLogLogin($iduser = null);

			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 getLogLoginHome($iduser = null){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {

			$ocuser = new OCUser();
			$result = $ocuser->getLogLoginHome($iduser = null);

			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 getUtenti(){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->getUtenti();

	//		$tmpLDAP = new AuthLdap(FILE_INI_LDAP);

	    	$resultldap = []; //$tmpLDAP->getAllUsers();

			return $this->printMessage( $this->responseMessage(array_merge($result, $resultldap), true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
	
	}

	public function getUtentiLdap($person){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			

			$tmpLDAP = new AuthLdap(FILE_INI_LDAP);

	    	$result = $tmpLDAP->getAllUsers($person);

	    	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 getUtenteInformazioni($id_user, $dal, $al){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->getUtenteInformazioni($id_user, $dal, $al);

			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 updateInformazioneUtente($informazioni, $id_user){
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->updateInformazioneUtente($informazioni, $id_user);

			return $this->printMessage( $this->responseMessage("Informazioni Aggiornate", true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
	}

	public function getPresenze($id_user, $dal, $al){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->getAllPresenze($id_user);//getPresenze($id_user, $dal, $al);

			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 postPresenze($id_user, $dal, $al){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->postPresenze($id_user, $dal, $al);

			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 postPresenzeRfid($token){
		$ocuser = new OCUser();
			$result = $ocuser->postPresenzeRfid(trim($token));
			if($result > 0){
				$status_bol = true;
			}else{
				$status_bol = false;
			}

			/*Result -> 
	
			-5 Non puoi uscire prima di 5 minuti
			-3 Utente non trovato
			-2 Inserimento nuova presenza non riuscita
			-1 Inserimento data di fine presenza non riuscita

			1 Inserimento data fine presenza riuscita
			2 Inserimento nuova presenza riuscita

			*/


			return $this->printMessage( $this->responseMessage($result, $status_bol) );
	
	}

	public function loginRfid($token){
		require_once SITEROOT_DIR.'/app/helpers/persistant.php';
		require_once SITEROOT_DIR.'/app/helpers/ocuser.php';
		$ocuser = new OCUser(true);
		unset($_SESSION); 
		session_destroy();
		
		$res = $ocuser->loginRfid(trim($token));

    	if ($res) {
        	for ($i=0; $i < 300; $i++) { 
        		$res['accessPage'][] = $i;
        	}

        	Persistant::SetLoginStatus(true);
        	Persistant::SetUserInfo($res);
        	$_SESSION['user'] = $res['id_user'];
        	$_SESSION['userdata'] = $res;
        	return $this->printMessage( $this->responseMessage($res, true) );
    	}else{
    		return $this->printMessage( $this->responseMessage($res, false) );
    	}
    } 	


	

	public function registraRfid($id_user, $rfid, $force){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->registraRfid($id_user, trim($rfid), $force);

			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 verificaRfid($rfid){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->verificaRfid(trim($rfid));

			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 cancellaRfid($rfid){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->cancellaRfid(trim($rfid));

			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 deletePresenza($id){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->deletePresenza($id);

			return $this->printMessage( $this->responseMessage($result, true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
	
	}

	
//Blog


	public function deleteBlog($id){
		$this->validateAuthAndGetUser();
		if($this->checkBlog()) {		

			$contentOperations = new Content();
			$result = $contentOperations->deleteBlog($id);
			return $this->printMessage( $this->responseMessage("Articolo del blog eliminato con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
		
	}
	public function insertBlog($titolo, $testo, $idcategoria, $logo, $link){
		$user = $this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true && $this->checkBlog()) {
			
			$cont = new Content();
			$res  = $cont->insertBlog($titolo, $testo, $idcategoria, $user['id_user'], $link);
			if ($res)
			{
				if($logo){

					$url = $this->putFileS3Private("pubblica/blog/articoli", $res, $logo);
					$check = $cont->aggiornaUrlArticoli($res, $url);

					return $this->printMessage($this->responseMessage($url, true));
				}else{
					return $this->printMessage($this->responseMessage($res, true));
				}
				
			} else {
				return $this->printMessage( $this->responseMessage("Inserimento Articolo fallito", false) );
			}


			
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}


	public function updateBlog($id, $titolo, $testo, $idcategoria, $logo, $link){

		$user = $this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true && $this->checkBlog()) {
			$cont = new Content();
			$res  = $cont->updateBlog($id, $titolo, $testo, $idcategoria, $user['id_user'], $link);
			if ($res)
			{
				if($logo){

					$url = $this->putFileS3Private("pubblica/blog/articoli", $res, $logo);
					$check = $cont->aggiornaUrlArticoli($res, $url);

					return $this->printMessage($this->responseMessage($url, true));
				}else{
					return $this->printMessage($this->responseMessage($res, true));
				}
				
			} else {
				return $this->printMessage( $this->responseMessage("Modifica Articolo fallito", false) );
			}

		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}
	

	//--------	

	public function deleteCategoriaBlog($id){
		$this->validateAuthAndGetUser();
		if($this->checkSuperAdmin()) {		

			$contentOperations = new Content();
			$result = $contentOperations->deleteCategoriaBlog($id);
			return $this->printMessage( $this->responseMessage("Categoria eliminata con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
		
	}



	public function insertCategoriaBlog($nome, $logo)
	{
		$this->validateAuthAndGetUser();
		
		if ($this->checkUserPermission() == true)
		{
			$cont = new Content();
			$res  = $cont->insertCategoriaBlog( $nome);
			if ($res)
			{
				if($logo){

					$url = $this->putFileS3Private("pubblica/blog/categorie", $res, $logo[0]);
					$check = $cont->aggiornaUrlCategoria($res, $url);

					return $this->printMessage($this->responseMessage($url, true));
				}else{
					return $this->printMessage($this->responseMessage($res, true));
				}
				
				

			}
			else
			{
				return $this->printMessage($this->responseMessage("Inserimento Categoria...", false));
			}
		}
		else
		{
			return $this->printMessage($this->responseMessage("Inserimento Categoria...\n Permesso negato!", false));
		}
	}
	
	public function updateCategoriaBlog($idcategoria, $nome,$logo)
	{
		$this->validateAuthAndGetUser();
		if ($this->checkUserPermission() == true){
				
			$cont = new Content();
			$cont->updateCategoriaBlog($idcategoria, $nome);
			
			if($logo){
				$url = $this->putFileS3Private("pubblica/blog/categorie", $idcategoria, $logo[0]);
				$check = $cont->aggiornaUrlCategoria($idcategoria, $url);

				return $this->printMessage($this->responseMessage($url, true));
			}else{
				return $this->printMessage($this->responseMessage($res, true));
			}

		}else{
			return $this->printMessage($this->responseMessage("Update Categoria...\n Permesso Negato!", false));
		}
	}





	
	public function getCategorieBlog(){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getCategorieBlog();
	return $this->printMessage( $this->responseMessage($result, true) );
	}

	public function getBlog($categoria_id = null){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getBlog($categoria_id);
	return $this->printMessage( $this->responseMessage($result, true) );
	}

	public function getCommenti($id_blog){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getCommenti($id_blog);
		return $this->printMessage( $this->responseMessage($result, true) );
	}

	public function removeCommento($id){
		$this->validateAuthAndGetUser();	
		if($this->checkBlog()) {
			$contentOperations = new Content();
			$result = $contentOperations->removeCommento($id);
			return $this->printMessage( $this->responseMessage("Commento cancellato con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
		
	}




	public function updateInformazioniBaseUtente($firstname, $lastname, $genere, $datanascita, $ruolo, $location, $id_user, $cellulare){
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->updateInformazioniBaseUtente($firstname, $lastname, $genere, $datanascita, $ruolo, $location, $id_user, $cellulare);

			return $this->printMessage( $this->responseMessage("Informazioni Aggiornate", true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
	}

	public function updateInformazioniContattoUtente($cellulare, $email, $linkedin, $whatsapp, $facetime, $skype, $id_user){
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->updateInformazioniContattoUtente($cellulare, $email, $linkedin, $whatsapp, $facetime, $skype, $id_user);

			return $this->printMessage( $this->responseMessage("Informazioni Aggiornate", true) );

		}else{

			return $this->printMessage( $this->responseMessage('Non hai i permessi per accedere a questa risorsa!', false) );

		}
	}

	public function updateFotoContattoUtente($avatar, $id_user){
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkSuperAdmin() == true || $user['id_user']==$id_user) {

			$ocuser = new OCUser();
			$res = $ocuser->updateFotoContattoUtente($avatar, $id_user);
			
			if($res) {
				return $this->printMessage( $this->responseMessage("Foto dell'Utente aggiornata con successo", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Ops! Foto non aggiornata!", false) );
			}

		} else {
			return $this->printMessage( $this->responseMessage("Non hai i permessi", false) );
		}

	}

	public function createUser($username, $firstname, $lastname, $email, $password, $usertypeid, $email_registrazione, $color){
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkSuperAdmin() == true) {

			$ocuser = new OCUser(true);
			$res = $ocuser->CreateUser($username, $firstname, $lastname, $email, $password, $usertypeid, $user['id_user'], $color);
			
			if($res) {
				if($email_registrazione){


					return $this->printMessage( $this->responseMessage("Utente creato con successo!", true) );
				}else{
					return $this->printMessage( $this->responseMessage("Utente creato con successo!", true) );
				}
			
			} else {
				return $this->printMessage( $this->responseMessage("Ops! Utente non creato!", false) );
			}

		} else {
			return $this->printMessage( $this->responseMessage("Non hai i permessi", false) );
		}

	}

	public function updateUser($username, $firstname, $lastname, $email, $password, $usertypeid, $email_registrazione, $id, $color){
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkSuperAdmin() == true) {

			$ocuser = new OCUser(true);
			$res = $ocuser->UpdateUser($username, $firstname, $lastname, $email, $password, $usertypeid, $user['id_user'], $id, $color);
			
			if($res) {

					return $this->printMessage( $this->responseMessage("Utente aggiornato con successo!", true) );
				
			
			} else {
				return $this->printMessage( $this->responseMessage("Ops! Utente non aggiornato!", false) );
			}

		} else {
			return $this->printMessage( $this->responseMessage("Non hai i permessi", false) );
		}

	}

	public function deleteUser($id){
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkSuperAdmin() == true) {

			$ocuser = new OCUser(true);
			$res = $ocuser->DeleteUser($id);
			
			if($res) {
				return $this->printMessage( $this->responseMessage("Utente eliminato con successo!", true) );
				
			} else {
				return $this->printMessage( $this->responseMessage("Ops! Utente non eliminato!", false) );
			}

		} else {
			return $this->printMessage( $this->responseMessage("Non hai i permessi", false) );
		}

	}


	/* 
	 *
	 * METODI AMMINISTRAZIONE: GRUPPI di Utenti 
	 * 
	 */


	/**
	 * GROUP
	 * Enter description here ...
	 * @param unknown_type $name
	 * @param unknown_type $description
	 */

	public function getGroups(){ 

		if($this->checkUserPermission() == true) {
			$ocuser = new OCUser(false);
			$res = $ocuser->getGroups();
			foreach ($res as $key => $value) {
				if($res[$akey]['permessi'])
				$res[$akey]['permessi'] = json_decode($res[$akey]['permessi'] );
			}
			return $this->printMessage( $this->responseMessage($res, true) );
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}

	public function getGroupUsersById($id){ 

		if($this->checkUserPermission() == true) {
			$ocuser = new OCUser(false);
			$res = $ocuser->getGroupUsersById($id);

			//get name of user ldap from groups assoctiation
			$ids = $ocuser->getGroupUsersIdsById($id, $res);

			return $this->printMessage( $this->responseMessage(array_merge($res,$ids), true) );
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}


	public function insertGroup($name, $description, $permessi){
		
		$permessi = json_encode(unserialize($permessi));


		if($this->checkUserPermission() == true) {
			$ocuser = new OCUser(false);
			$res = $ocuser->insertGroup($name, $description, $permessi);
			if($res) {
				return $this->printMessage( $this->responseMessage("Gruppo creato con successo", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Creazione del gruppo fallita", false) );
			}
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}
	
	public function editGroup($id, $name, $description, $permessi){

		$permessi = json_encode(unserialize($permessi));

		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			$ocuser = new OCUser(false);
			$res = $ocuser->editGroup($id,$name,$description, $permessi);
			if($res) {
				return $this->printMessage( $this->responseMessage("Gruppo editato con successo", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Editazione del gruppo fallita", false) );
			}
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}
	
	public function deleteGroup($id){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			$ocuser = new OCUser(false);
			$res = $ocuser->GroupDelete($id);
			if($res) {
				return $this->printMessage( $this->responseMessage("Gruppo cancellato con successo", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Cancellazione del gruppo non riuscita", false) );
			}
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}
	
	public function addUserToGroup($id_group, $id_user){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			$ocuser = new OCUser(false);

			if($ocuser->checkUserToGroup($id_group, $id_user)){
				return $this->printMessage( $this->responseMessage("Utente già presente nel gruppo", false) );
			}else{
				$res = $ocuser->addUserToGroup($id_group, $id_user);
				if($res) {
					return $this->printMessage( $this->responseMessage("Utente aggiunto con successo", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Utente non aggiunto operazione non riuscita", false) );
				}
			}

		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}

	public function removeUserFromGroup($id_group, $id_user){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			$ocuser = new OCUser(false);
			$res = $ocuser->removeUserFromGroup($id_group, $id_user);
			if($res) {
				return $this->printMessage( $this->responseMessage("Utente cancellato dal gruppo con successo", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Cancellazione del'utente dal gruppo non riuscita", false) );
			}
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}
	

	/**
	 * User to Group
	 * Function for CRUD user to GROUPS.
	 * @param unknown_type $description
	 */

	

	/* 
	 *
	 * METODI AMMINISTRAZIONE: INVIO EMAIL 
	 * 
	 */


	public function createEmail($subject, $description, $emailtypeid, $txt, $html){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {

			$email = new Emaildb();
			$storeEmail = $email->SaveEmail($subject, $description, $emailtypeid, $txt, $html);
			
			if($storeEmail == false){
				return $this->printMessage( $this->responseMessage("Email not created", false) );
			} else {
				return $this->printMessage( $this->responseMessage("Email created with id: ".$storeEmail, true) );
			}	
		}
	}

	public function sendEmailToGroup($emailid, $sender_userid, $dest_groupid ){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {

			$email = new OCMailer();

			//SEND EMAIL
			$emailCK = $email->SendEmail($emailid,$dest_groupid);
			
			if($emailCK){
				return $this->printMessage( $this->responseMessage("All emails send!", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Email: ".$emailid ." not send!", false) );
			}	
		}
	}

	public function sendEmailToUser($emailid, $sender_userid, $dest_userid){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {

			$email = new OCMailer();

			//SEND EMAIL
			$emailCK = $email->SendEmail($emailid,$dest_userid);
			
			if($emailCK){
				return $this->printMessage( $this->responseMessage("All emails send!", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Email: ".$emailid ." not send!", false) );
			}	
		}
	}
	
	/* 
	 *
	 * METODO PRIVATO CHE MOSTRA TUTTI I FILE DI UNA CARTELLA RICHIESTA
	 * 
	 */

	private function listDirectory($path){
	    if(!is_array($files)){
	    	$files = array();
	    }
	    $handle = @opendir($path);
	    if($handle){
		    while (false !== ($file = readdir($handle))) {
		        if ($file == '.' || $file == '..' || $file == '.DS_Store') continue;
		        if ( is_dir("$path/$file")) {
		            $files = array_merge($files,$this->listDirectory("$path/$file"));
		        } else {
		            $files[] = "$path/$file";
		        }
		    }
		    //ordino per nome
		 	sort($files,SORT_STRING);


		    closedir($handle);
		}else{
	    	$files = array();
		}
	    return $files;
	}




	/**
	*
	*	METODO INTERNATIONALIZATION stampa il contenuto di un file json presente in una cartella (utile per impostare lingue dinamiche)
	*
	**/

	public function getEN(){
		
		$languageFile = 'languages/en.json';
		$language = file_get_contents($languageFile);
		$language = json_decode($language, true);

		return $this->printMessage( $this->responseMessage($language, true) );
	}

	/**
	*
	*	METODO DATA DINAMICA COPYRIGHT
	*
	**/

	public function getCopyrightDate(){
		return $this->printMessage( $this->responseMessage(date("Y"), true) );
	}

///////// FINE DEL FILE ////////////// da qui in poi va in file diversi



	/* @Peo */
	//Cliente

	public function deleteCliente($id){
		$this->validateAuthAndGetUser();
		if($_SESSION["userdata"]["user_type_id"] ==830830 && $_SESSION["userdata"]["user_type_id"] ==123456) 
		{
			$contentOperations = new Content();
			$result = $contentOperations->deleteCliente($id);
			return $this->printMessage( $this->responseMessage("Cliente eliminato con successo!", true) );	
		}
		else
		{
			return $this->printMessage($this->responseMessage("Nessun Cliente trovato!", false));
		}
	}

	/*public function insertCliente($ragioneSociale, $indirizzo, $citta, $piva, $codicefiscale, $telefono, $cellulare, $email, $note, $sede, $filesname){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont = new Content();




				$id_cliente = $cont->insertCliente($ragioneSociale, $indirizzo, $citta, $piva, $codicefiscale, $telefono, $cellulare, $email, $note, $sede);

				error_log("Inserito cliente ". $id_cliente);

				$filesname= json_encode($filesname);
				foreach ($filesname as $key => $value) {
		    		$nome_file = getcwd() ."/../server/php/files/" . $value;
				error_log("Inserimanto file cliente ". $nome_file);

		    		$this->uploadFileClient($nome_file, $id_cliente);
				}
				
			/*	if(count($file_aggiunti)){
					$message.= "File Aggiunti " . implode(", ", $file_aggiunti) .  " | ";
				}
			
			*/

/*
				if($id_cliente) {
					return $this->getClienti();
				} else {
					return $this->printMessage( $this->responseMessage("Inserimento Cliente fallito", false) );
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}*/

		public function editCliente($idCliente, $ragioneSociale, $indirizzo, $citta, $piva, $codicefiscale, $telefono, $cellulare, $email, $note, $sede){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont = new Content();
				$res = $cont->editCliente($idCliente,$ragioneSociale, $indirizzo, $citta, $piva, $codicefiscale, $telefono, $cellulare, $email, $note, $sede);
				if($res) {
					return $this->printMessage( $this->responseMessage("Cliente editato con successo", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Editazione Cliente fallita", false) );
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

	private function includePayPal(){

		if ($_SERVER['HTTP_HOST']=="admin.formazione-360.it") {
			$prodenv_client_id = "AWeFj70K5eUPqWEbAGJvFN3qbCSiNUdXtSjZlGBcjInOGI5uMRKEo2vaOwmP89jhxUQtMoa2oY1svE9c";
	    	$prodenv_secret = "EABXfNp7lCc_z9sJFzCwjDP5Lvk4Pjewmeh4NqaHeKvCtXjNW2VEniIY_J21TOFyS29YvXfJFvtxC9xJ";
			
	    }else if ($_SERVER['HTTP_HOST']=="admin.scuolabuona.it") {
			$prodenv_client_id = "AWeFj70K5eUPqWEbAGJvFN3qbCSiNUdXtSjZlGBcjInOGI5uMRKEo2vaOwmP89jhxUQtMoa2oY1svE9c";
	    	$prodenv_secret = "EABXfNp7lCc_z9sJFzCwjDP5Lvk4Pjewmeh4NqaHeKvCtXjNW2VEniIY_J21TOFyS29YvXfJFvtxC9xJ";
			
	    }else if ($_SERVER['HTTP_HOST']=="admin.minerva-form.it") {
	    	//ascii
	    	$prodenv_client_id = "AY5-lVaIc6jrtYB-MzXaoiC0AXcxvZ2ld_GIOfIagfRK_F8P5KdqYp6V5jJIRrXSeakAd6uHrybYYeiL";
	    	$prodenv_secret = "EFEDLRlNqZO-A3xVCWciwIslrnkahAQl_HNA8hLbWLr3R-R8Vyre3HKC4ISsvemMs-oRfEKEqVpKmAO7";
	    }else{
	    	//ascii
	    	$prodenv_client_id = "AY5-lVaIc6jrtYB-MzXaoiC0AXcxvZ2ld_GIOfIagfRK_F8P5KdqYp6V5jJIRrXSeakAd6uHrybYYeiL";
	    	$prodenv_secret = "EFEDLRlNqZO-A3xVCWciwIslrnkahAQl_HNA8hLbWLr3R-R8Vyre3HKC4ISsvemMs-oRfEKEqVpKmAO7";
	    }
	    
	     
	    return new ProductionEnvironment($prodenv_client_id, $prodenv_secret);

		//return new ProductionEnvironment("AY5-lVaIc6jrtYB-MzXaoiC0AXcxvZ2ld_GIOfIagfRK_F8P5KdqYp6V5jJIRrXSeakAd6uHrybYYeiL", "EFEDLRlNqZO-A3xVCWciwIslrnkahAQl_HNA8hLbWLr3R-R8Vyre3HKC4ISsvemMs-oRfEKEqVpKmAO7");
      	/*return new SandboxEnvironment("AZsTSTLe9v8QY3h5j82mQV35yGJmFkKtkO9KeE8BkEwx0mYBf5jDCKIRBX5EBc1pYefPj8LGVQBXP1pC", "EBKEwhxfYtV_thrjtzuEOoWs0hdA47ukpPYptYHc6x0VB74Owc1_wawx9KKnwC1ywMQmnA2cosn93oIP");*/

	}

	public function getInfoPagamentoPayPal($orderID){
		
      $env= $this->includePayPal();
     
     //echo "mmmm";//46P72967F4191643Y
      $client = new PayPalHttpClient($env);
     
     
     try{
        $od =new OrdersGetRequest($orderID);
        /*$od =new OrdersCaptureRequest($orderID);*/
       /* echo "3)<br>";*/
        $response = $client->execute($od);

      /*echo "<pre>".  print_r($response, true)."</pre>";*/
      	$toRet = array();
        $corso = array("slug" => $response->result->purchase_units[0]->items[0]->sku,
                      "titolo" => $response->result->purchase_units[0]->items[0]->name,
                      "prezzo_original" => $response->result->purchase_units[0]->items[0]->unit_amount->value,
                      "prezzo" => "&euro; ". str_replace(".", ",", $response->result->purchase_units[0]->items[0]->unit_amount->value
                      ));
        $pagamento = array("status" => $response->result->status, // APPROVED
                           "statusCode" => $response->statusCode, //200
                           "date" => $response->result->create_time);

        $utente = array(
          "nome"=> $response->result->purchase_units[0]->shipping->name->full_name,
          "email" => $response->result->payer->email_address, 
          "id_user_paypal" => $response->result->payer->payer_id,
          "indirizzo"=> array(
                  "via" =>$response->result->purchase_units[0]->shipping->address->address_line_1, 
                  "area2" =>$response->result->purchase_units[0]->shipping->address->admin_area_2, 
                  "area1" =>$response->result->purchase_units[0]->shipping->address->admin_area_1, 
                  "codice_postale" =>$response->result->purchase_units[0]->shipping->address->postal_code, 
                  "codice_paese" =>$response->result->purchase_units[0]->shipping->address->country_code
                  )
             );

	      	$toRet['statuscode']        = intval($pagamento['statusCode']);
	        $toRet['status']        = $pagamento['status'];
	        $toRet['slug_corso']        =  $corso['slug'];
	        $toRet['titolo_corso']        =  $corso['titolo'];
	        $toRet['data_pagamento']        = $pagamento['date'];
	        $toRet['prezzo_vendita']        =  $corso['prezzo_original'];
	        $toRet['nome']        =  $utente['nome'];
	        $toRet['email']        =  $utente['email'];
	        $toRet['id_user_paypal']        =  $utente['id_user_paypal'];
	        $toRet['via']        =  $utente['indirizzo']['via'];
	        $toRet['area1']        =  $utente['indirizzo']['area1'];
	        $toRet['area2']        =  $utente['indirizzo']['area2'];
	        $toRet['codice_postale']        = $utente['indirizzo']['codice_postale'];
	        $toRet['codice_paese']        = $utente['indirizzo']['codice_paese'];
                         
 
       }catch (Exception $e){
        return $this->printMessage( $this->responseMessage($e, false) );	
       }
    	return $this->printMessage( $this->responseMessage($toRet, true) );	
	}


	public function aggiornaInfoPagamentoDaPayPal($orderID){
		
      $env= $this->includePayPal();
     
     //echo "mmmm";//46P72967F4191643Y
      $client = new PayPalHttpClient($env);
     
     
     try{
        $od =new OrdersGetRequest($orderID);
        /*$od =new OrdersCaptureRequest($orderID);*/
       /* echo "3)<br>";*/
        $response = $client->execute($od);

      /*echo "<pre>".  print_r($response, true)."</pre>";*/
      	$toRet = array();
        $corso = array("slug" => $response->result->purchase_units[0]->items[0]->sku,
                      "titolo" => $response->result->purchase_units[0]->items[0]->name,
                      "prezzo_original" => $response->result->purchase_units[0]->items[0]->unit_amount->value,
                      "prezzo" => "&euro; ". str_replace(".", ",", $response->result->purchase_units[0]->items[0]->unit_amount->value
                      ));
        $pagamento = array("status" => $response->result->status, // APPROVED
                           "statusCode" => $response->statusCode, //200
                           "date" => $response->result->create_time);

        if($pagamento['statusCode']=="201" || !$pagamento['status']){
        	$pagamento['status']=$response->result->status;
        }


        $utente = array(
          "nome"=> $response->result->purchase_units[0]->shipping->name->full_name,
          "email" => $response->result->payer->email_address, 
          "id_user_paypal" => $response->result->payer->payer_id,
          "indirizzo"=> array(
                  "via" =>$response->result->purchase_units[0]->shipping->address->address_line_1, 
                  "area2" =>$response->result->purchase_units[0]->shipping->address->admin_area_2, 
                  "area1" =>$response->result->purchase_units[0]->shipping->address->admin_area_1, 
                  "codice_postale" =>$response->result->purchase_units[0]->shipping->address->postal_code, 
                  "codice_paese" =>$response->result->purchase_units[0]->shipping->address->country_code
                  )
             );

	      	$toRet['statuscode']        = intval($pagamento['statusCode']);
	        $toRet['status']        = $pagamento['status'];
	        $toRet['slug_corso']        =  $corso['slug'];
	        $toRet['titolo_corso']        =  $corso['titolo'];
	        $toRet['data_pagamento']        = $pagamento['date'];
	        $toRet['prezzo_vendita']        =  $corso['prezzo_original'];
	        $toRet['nome']        =  $utente['nome'];
	        $toRet['email']        =  $utente['email'];
	        $toRet['id_user_paypal']        =  $utente['id_user_paypal'];
	        $toRet['via']        =  $utente['indirizzo']['via'];
	        $toRet['area1']        =  $utente['indirizzo']['area1'];
	        $toRet['area2']        =  $utente['indirizzo']['area2'];
	        $toRet['codice_postale']        = $utente['indirizzo']['codice_postale'];
	        $toRet['codice_paese']        = $utente['indirizzo']['codice_paese'];
            $cont= new Content();


            $res = $cont->updateOrdineConCode($orderID,$toRet['statuscode'], $toRet['status'], $toRet['slug_corso'], $toRet['titolo_corso'],$toRet['data_pagamento'], $toRet['prezzo_vendita']  , $toRet['nome'] , $toRet['email'], $toRet['id_user_paypal'],$toRet['via'] , $toRet['area1'], $toRet['area2'], $$toRet['codice_postale'], $$toRet['codice_paese']);         
            return $this->printMessage( $this->responseMessage("Ordine aggiornato correttamente!", true) );
 
       }catch (Exception $e){
        return $this->printMessage( $this->responseMessage($e, false) );	
       }
	}

	/*public function annullaPagamentoPayPal($orderID){
		
		$env= $this->includePayPal();
     
     //echo "mmmm";//46P72967F4191643Y
      $client = new PayPalHttpClient($env);
     
      
     try{
     	//TODO: RIGETTA DENARO
       // $od =new OrdersGetRequest($orderID);
       // $od =new OrdersCaptureRequest($orderID);
       
        $response = $client->execute($od);

      echo "<pre>".  print_r($response, true)."</pre>";
      	
      	$pagamento = array("status" => $response->result->status, // COMPLETED
                           "statusCode" => $response->statusCode, //200
                           "date" => $response->result->create_time);

        $contentOperations = new Content();
		$result = $contentOperations->memorizzaPagamento($pagamento['statusCode'], $pagamento['status'], $pagamento['date'], $orderID);
		 
        if($pagamento['status']=='ANNULLATED' && $result){
        	return true;
        }else{
        	return false;
        }

                         
 
       }catch (Exception $e){
          $toRet = [];
       }
    	return $this->printMessage( $this->responseMessage($toRet, true) );	
	}
*/
	public function confermaPagamentoPayPal($orderID){
		
    	
    	try{
			$env= $this->includePayPal();

		  	$client = new PayPalHttpClient($env);
		  
		    $od =new OrdersCaptureRequest($orderID);
		 
		    $response = $client->execute($od);

		    $email = $response->result->payer->email_address;
		    /*echo '<pre>'.print_r($response,true).'<pre>';*/

		    $pagamento = array("status" => $response->result->status, // COMPLETED
		                       "statusCode" => $response->statusCode //201
		                       );
		    /*print_r($print_r);*/
		    $contentOperations = new Content();
			$result = $contentOperations->memorizzaPagamento($pagamento['statusCode'], $pagamento['status'], $orderID, 'APPROVATO');

		    if($pagamento['status']=='COMPLETED' && $result){
		    	//invia email cliente

				require_once SITEROOT_DIR.'/app/helpers/email-aws.php';
				$emailMessage = new EmailAws(null);

				//INVIO EMAIL UTENTE FINALE
                $messaggio_utente.= "Gentile utente, ti informiamo che il tuo ordine e' in lavorazione.<br>";
                $messaggio_utente.=  "<h3>CODICE ORDINE: $orderID</h3>";
                $messaggio_utente.=  "<h3>STATO ORDINE: IN LAVORAZIONE</h3>";

                if ($_SERVER['HTTP_HOST']=="admin.formazione-360.it") {
					$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>Formazione 360<br><br>Email: info@formazione-360.it<br>www.formazione-360.it";
                			
					$emailCK = $emailMessage->SendMessage('Conferma Ordine - Formazione 360.it', $messaggio_utente, $messaggio_utente, "info@formazione-360.it", $email);
					
			    }else if ($_SERVER['HTTP_HOST']=="admin.scuolabuona.it") {
					$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>Scuola Buona<br><br>Email: info@scuolabuona.it<br>www.scuolabuona.it";
                			
					$emailCK = $emailMessage->SendMessage('Conferma Ordine - Scuolabuona.it', $messaggio_utente, $messaggio_utente, "info.scuolabuona.it", $email);
					
			    }else if ($_SERVER['HTTP_HOST']=="admin.minerva-form.it") {
			    	//ascii
			    	$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>www.minerva-form.it";
                			
					$emailCK = $emailMessage->SendMessage('Conferma Ordine - Minerva-Form.it', $messaggio_utente, $messaggio_utente, "info@minerva-form.it", $email);
			    }else if ($_SERVER['HTTP_HOST']=="admin.sindacatosalerno.it") {
			    	//ascii
			    	$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>www.sindacatosalerno.it";
                			
					$emailCK = $emailMessage->SendMessage('Conferma Ordine - SindacatoSalerno.it', $messaggio_utente, $messaggio_utente, "info@sindacatosalerno.it", $email);
			    }else{
			    	//ascii
			    	$messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>ASCII Formazione<br>Via Irno 101, 84135 - Salerno<br>Email: info@asciiformazione.it<br>Tel. 089-98.49.407, 089-28.64.695";
                			
					$emailCK = $emailMessage->SendMessage('Conferma Ordine - ASCIIFormazione.it', $messaggio_utente, $messaggio_utente, "info@asciiformazione.it", $email);
			    }

                

				if($emailCK){
					return $this->printMessage( $this->responseMessage("Pagamento ordine completato! Verificare su PayPal!", true) );	
				}else{
					return $this->printMessage( $this->responseMessage("Pagamento ordine completato! Verificare su PayPal! ATTENZIONE: Email cliente non inviata!", true) );	
				}
		    	
		    }else{
		    	return $this->printMessage( $this->responseMessage("Pagamento in stato ".$pagamento['status']."! Verificare su PayPal!", false) );	
		    }
		}catch(Exception $e){
			return $this->printMessage( $this->responseMessage("Pagamento non completato! Verificare su PayPal!", false) );	
		}

    	
	}

	public function testEmail(){
		require_once SITEROOT_DIR.'/app/helpers/email-aws.php';
		$emailMessage = new EmailAws(null);
		echo "ok";
		//INVIO EMAIL UTENTE FINALE
        $messaggio_utente.= "Gentile utente, ti informiamo che il tuo ordine è in lavorazione.<br>";
        $messaggio_utente.=  "<h3>CODICE ORDINE: $orderID</h3>";
        $messaggio_utente.=  "<h3>STATO ORDINE: IN LAVORAZIONE</h3>";
        $messaggio_utente.= "<br><br>Se hai bisogno di maggiorni informazioni, non esitare a contattarci!<br><br>Grazie per averci preferito!<br><br>ASCII Formazione<br>Via Irno 101, 84135 - Salerno<br>Email: info@asciiformazione.it<br>Tel. 089-98.49.407, 089-28.64.695";
        			
		//	$emailCK = $emailMessage->InviaEmail('TEST: Conferma Ordine - ASCIIFormazione.it', $messaggio_utente, $messaggio_utente, "@me.com");

			if($emailCK){
				return $this->printMessage( $this->responseMessage("Pagamento ordine completato! Verificare su PayPal!", true) );	
			}else{
				return $this->printMessage( $this->responseMessage("Pagamento ordine completato! Verificare su PayPal! ATTENZIONE: Email cliente non inviata!", true) );	
			}
	}

	//prodotto
	public function deleteProdotto($id){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->deleteProdotto($id);
			return $this->printMessage( $this->responseMessage("Prodotto eliminato con successo!", true) );	
		}

		public function insertProdotto($nome, $descrizione, $costo, $codice, $disponibile, $foto, $idevice, $riparazione){
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$timestamp = time();
				$uploaddir = getcwd().'/../img/prodotti/'.$timestamp;
				$uploadfile = $uploaddir . basename($foto[0]);

				$copio = copy($foto[0], $uploadfile);
				if ($copio) {
					$cont = new Content();
					$dasalvareimgdb = "img/prodotti/".$timestamp. basename($foto[0]);
					$res = $cont->insertProdotto($nome, $descrizione, $costo, $codice, $disponibile, $dasalvareimgdb, $idevice, $riparazione);
					if($res) {
						return $this->printMessage( $this->responseMessage("Prodotto inserito con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Inserimento Prodotto fallito", false) );
					}
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

		public function updateProdotto($id, $nome, $descrizione, $costo, $codice, $disponibile, $foto, $newfoto, $idevice, $riparazione){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				if($newfoto){
					$timestamp = time();
					$uploaddir = getcwd().'/../img/categorie/'.$timestamp;
					$uploadfile = $uploaddir . basename($foto[0]);

					$copio = copy($foto[0], $uploadfile);
					if ($copio) {
						$dasalvareimgdb = "img/categorie/".$timestamp. basename($foto[0]);
						$cont = new Content();
						$res = $cont->updateProdotto($id, $nome, $descrizione, $costo, $codice, $disponibile, $dasalvareimgdb, $idevice, $riparazione);
						if($res) {
							return $this->printMessage( $this->responseMessage("Prodotto editato con successo", true) );
						} else {
							return $this->printMessage( $this->responseMessage("Editazione Prodotto fallita", false) );
						}
					} else {
						return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
					}
				}else{
					$cont = new Content();
					$res = $cont->updateProdotto($id, $nome, $descrizione, $costo, $codice, $disponibile, null, $idevice, $riparazione);
					if($res) {
						return $this->printMessage( $this->responseMessage("Prodotto editato con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Editazione Prodotto fallita", false) );
					}
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

		public function getProdotto($iddevice = null){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getProdotto($iddevice);
			return $this->printMessage( $this->responseMessage($result, true) );
		}




	//Device

	public function deleteDevice($id){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->deleteDevice($id);
			return $this->printMessage( $this->responseMessage("Device eliminato con successo!", true) );	
		}

	public function insertDevice($idMarca,$modello,$foto, $idCategoria){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$timestamp = time();
				$uploaddir = getcwd().'/../img/device/'.$timestamp;
				$uploadfile = $uploaddir . basename($foto[0]);
				$copio = copy($foto[0], $uploadfile);
				if ($copio) {
					$cont = new Content();
					$dasalvareimgdb = "".$timestamp. basename($foto[0]);
					$res = $cont->insertDevice($idMarca,$modello,$dasalvareimgdb, $idCategoria);
					if($res) {
						return $this->printMessage( $this->responseMessage("Device inserita con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Inserimento Device fallito", false) );
					}
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}

		}

		public function editDevice($idDevice, $idMarca,$modello,$foto, $idCategoria, $newfoto){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				if($newfoto){
					$timestamp = time();
					$uploaddir = getcwd().'/../img/device/'.$timestamp;
					$uploadfile = $uploaddir . basename($foto[0]);

					$copio = copy($foto[0], $uploadfile);
					if ($copio) {
						$dasalvareimgdb = "".$timestamp. basename($foto[0]);
						$cont = new Content();
						$res = $cont->editDevice($idDevice, $idMarca,$modello,$dasalvareimgdb, $idCategoria);
						if($res) {
							return $this->printMessage( $this->responseMessage("Device editato con successo", true) );
						} else {
							return $this->printMessage( $this->responseMessage("Editazione Device fallita", false) );
						}
					} else {
						return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
					}
				}else{
					$cont = new Content();
					$res = $cont->editDevice($idDevice, $idMarca,$modello,false, $idCategoria);	
					return $this->printMessage( $this->responseMessage("Device editato con successo", true) );

				}

			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

	//Categor

	public function deleteCategor($id){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->deleteCategor($id);
			return $this->printMessage( $this->responseMessage("Categoria eliminata con successo!", true) );	
		}
	public function insertCategor($nome, $foto){
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$timestamp = time();
				$uploaddir = getcwd().'/../img/categorie/'.$timestamp;
				$uploadfile = $uploaddir . basename($foto[0]);
				$copio = copy($foto[0], $uploadfile);
				if ($copio) {
					$cont = new Content();
					$dasalvareimgdb = "img/categorie/".$timestamp. basename($foto[0]);
					$res = $cont->insertCategor($nome, $dasalvareimgdb);
					if($res) {
						return $this->printMessage( $this->responseMessage("Categoria inserita con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Inserimento Categoria fallito", false) );
					}
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}


		public function editCategor($idCategoria, $nome, $foto, $newfoto){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				if($newfoto){
					$timestamp = time();
					$uploaddir = getcwd().'/../img/categorie/'.$timestamp;
					$uploadfile = $uploaddir . basename($foto[0]);

					$copio = copy($foto[0], $uploadfile);
					if ($copio) {
						$dasalvareimgdb = "img/categorie/".$timestamp. basename($foto[0]);
						$cont = new Content();
						$res = $cont->editCategor($idCategoria, $nome, $dasalvareimgdb);
						if($res) {
							return $this->printMessage( $this->responseMessage("Categoria editata con successo", true) );
						} else {
							return $this->printMessage( $this->responseMessage("Editazione Categoria fallita", false) );
						}
					} else {
						return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
					}
				}else{
					$cont = new Content();
					$res = $cont->editCategor($idCategoria, $nome, null);
					if($res) {
						return $this->printMessage( $this->responseMessage("Categoria editata con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Editazione Categoria fallita", false) );
					}	
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

	public function deleteStat($id){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->deleteStat($id);
			return $this->printMessage( $this->responseMessage("Stato eliminato con successo!", true) );	
		}
	public function insertStat($nome, $descrizione){
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont= new Content();
					$res = $cont->insertStat($nome, $descrizione);
					if($res) {
						return $this->printMessage( $this->responseMessage("Stato inserito con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Inserimento Stato fallito", false) );
					}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}


		public function editStat($idstato, $nome, $descrizione){
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont= new Content();

					$res = $cont->editStat($idstato, $nome, $descrizione);
					if($res) {
						return $this->printMessage( $this->responseMessage("Stato modificato con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Modifica Stato fallito", false) );
					}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}


	//marca

	public function deleteMarca($id){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->deleteMarca($id);
			return $this->printMessage( $this->responseMessage("Marca eliminata con successo!", true) );	
		}

	public function insertMarca($nome, $foto){
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$timestamp = time();
				$uploaddir = getcwd().'/../img/marche/'.$timestamp;
				$uploadfile = $uploaddir . basename($foto[0]);
				//echo $uploaddir;
				$copio = copy($foto[0], $uploadfile);
				if ($copio) {
					$cont = new Content();
					$dasalvareimgdb = "img/marche/".$timestamp. basename($foto[0]);
					$res = $cont->insertMarca($nome, $dasalvareimgdb);
					if($res) {
						return $this->printMessage( $this->responseMessage("Operazione effettuata con successo!", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Operazione fallita!", false) );
					}
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

		public function editMarca($idMarca, $nome, $foto, $newfile){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				if($newfile){
					$timestamp = time();
					$uploaddir = getcwd().'/../img/marche/'.$timestamp;
					$uploadfile = $uploaddir . basename($foto[0]);

					$copio = copy($foto[0], $uploadfile);
					if ($copio) {
						$dasalvareimgdb = "img/marche/".$timestamp. basename($foto[0]);
						$cont = new Content();
						$res = $cont->editMarca($idMarca, $nome, $dasalvareimgdb);
						if($res) {
							return $this->printMessage( $this->responseMessage("Operazione effettuata con successo!", true) );
						} else {
							return $this->printMessage( $this->responseMessage("Operazione fallita!", false) );
						}
					} else {
						return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
					}
				}else{
					$cont = new Content();
					$res = $cont->editMarca($idMarca, $nome, false);
					if($res) {
						return $this->printMessage( $this->responseMessage("Operazione effettuata con successo!", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Operazione fallita!", false) );
					}	
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}


	//riparazione
	public function deleteRiparazione($id){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->deleteRiparazione($id);
			return $this->printMessage( $this->responseMessage("Riparazione eliminata con successo!", true) );	
		}


	public function insertRiparazione($idDevice, $idcliente, $dataIngresso,$dataRiconsegna,$serialeImei,$accessoriConsegnati,$descrizioneProblema,$descrizioneRiparazione,$fotoRiparazione,$totaleCostoRiparazione, $preventivoRiparazione, $note, $sede, $stato, $prodotti){
		
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont = new Content();
				$res = $cont->insertRiparazione($idDevice, $idcliente, $dataIngresso,$dataRiconsegna,$serialeImei,$accessoriConsegnati,$descrizioneProblema,$descrizioneRiparazione,$fotoRiparazione,$totaleCostoRiparazione, $preventivoRiparazione, $note, $sede, $stato, $prodotti);
				if($res) {
					return $this->printMessage( $this->responseMessage("Riparazione inserita con successo", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Inserimento Riparazione fallito", false) );
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

		public function editRiparazione($idRiparazione, $idDevice, $idcliente, $dataIngresso,$dataRiconsegna,$serialeImei,$accessoriConsegnati,$descrizioneProblema,$descrizioneRiparazione,$fotoRiparazione,$totaleCostoRiparazione, $preventivoRiparazione, $note,$sede, $stato, $prodotti){

			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont = new Content();
				$res = $cont->editRiparazione($idRiparazione, $idDevice, $idcliente, $dataIngresso,$dataRiconsegna,$serialeImei,$accessoriConsegnati,$descrizioneProblema,$descrizioneRiparazione,$fotoRiparazione,$totaleCostoRiparazione, $preventivoRiparazione, $note,$sede, $stato, $prodotti);
				if($res) {
					return $this->printMessage( $this->responseMessage("Riparazione editate con successo", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Editazione fallita", false) );
				}
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}
		public function getStati(){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getStati();
		return $this->printMessage( $this->responseMessage($result, true) );
		}

		public function getMarche(){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getMarche();
		return $this->printMessage( $this->responseMessage($result, true) );
		}
		public function getCategor(){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getCategor();
		return $this->printMessage( $this->responseMessage($result, true) );
		}
		public function getCitta(){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getCitta();
		return $this->printMessage( $this->responseMessage($result, true) );
		}
		public function getDevices(){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getDevices();
			return $this->printMessage( $this->responseMessage($result, true) );
		}
		public function getCliente($idCliente){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getCliente($idCliente);
			return $this->printMessage( $this->responseMessage($result, true) );
		}
		public function getClienti(){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getClienti();
			return $this->printMessage( $this->responseMessage($result, true) );
		}

		public function getRiparazione($id_riparazione){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->getRiparazione($id_riparazione);
			return $this->printMessage( $this->responseMessage($result, true) );

		}
	public function getRiparazioni(){
			$this->validateAuthAndGetUser();
			$contentOperations = new Content();
			$result = $contentOperations->getRiparazioni();
			return $this->printMessage( $this->responseMessage($result, true) );

		}

	public function getHome($rest=false){ //TODO jam

/*		$aggiornamento = strtotime("now - 1 month"); 
		$unmesefa = date("Y/m/d 00:00:01",$aggiornamento);
		$oggi = date("Y/m/d 00:00:01",strtotime("now"));
		$oggitime = strtotime($oggi);
*/	
//ci sono 17 istogrammini nei widget

		if($this->checkCentroPermission()){
			include "app/components/centri/api.class.php";
			$contentOperations = new ContentCentri();
			$result            = [];

			$result['crediti_disponibili']= $contentOperations->getCreditiCentro($_SESSION["userdata"]['idcentro']);
			$result['crediti_acquistati']= $contentOperations->getCreditiTotaliCentro($_SESSION["userdata"]['idcentro']);
			$result['ultimo_acquisto']= $contentOperations->getUltimoAcquisto($_SESSION["userdata"]['idcentro']);
			$result['utenti_attivati']= $contentOperations->getUtentiAttivatiCentro($_SESSION["userdata"]['idcentro']);
			$result['utenti_totali']= $contentOperations->getUtentiTotaliCentro($_SESSION["userdata"]['idcentro']);



			
			return $this->printMessage( $this->responseMessage($result, true) ); 
		

		}else{



			$content = new ContentPratica();


			$numeropratiche = $content->getPratiche(1,0); //mese
			
			if(!$numeropratiche)$numeropratiche=0;
			$numeropraticheanno = $content->getPratiche(0,1); //oggi
			if(!$numeropraticheanno)$numeropraticheanno=0;

			$datipratiche = $content->getDatiPraticheHome();


			$contentCli = new ContentCliente();


			$numeroclienti = $contentCli->getClientiHome(1,0); //mese
			if(!$numeroclienti)$numeroclienti=0;

			$numeroclientianno = $contentCli->getClientiHome(0,1); //oggi
			if(!$numeroclientianno)$numeroclientianno=0;

			$daticlienti = $contentCli->getDatiClienteHome();
						
				//$dati[$key]['datainizio'] = implode("/", explode("-",$value['datafine']));
			

			$toReturn = array('numeroclienti' => $numeroclienti, 'numeroclientianno' => $numeroclientianno, 'numeropratiche' => $numeropratiche, 'numeropraticheanno'=> $numeropraticheanno, 'datipratiche'=> $datipratiche, 'daticlienti'=> $daticlienti );

	//var_dump($toReturn);
			if($rest){
				return $toReturn; 
			}else{
				return $this->printMessage( $this->responseMessage($toReturn, true) ); 
			}
		}

	}

	/*ORDINI*/
	
	//ORDINI PRODOTTI VENDITA




	public function getOrdine($id){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getOrdine($id);
		return $this->printMessage( $this->responseMessage($result, true) );
	}

	public function getNumeroOrdiniNonLetti(){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getNumeroOrdiniNonLetti();
		return $this->printMessage( $this->responseMessage($result, true) );
	}

	public function getNumeroNotificheNonLetti(){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getNumeroNotificheNonLetti();
		return $this->printMessage( $this->responseMessage($result, true) );
	}


	public function getOrdini(){
			$this->validateAuthAndGetUser();	
			$contentOperations = new Content();
			$result = $contentOperations->getOrdini();
			return $this->printMessage( $this->responseMessage($result, true) );
		}

	public function insertOrdine($statuscode, $status, $slug_corso, $titolo_corso, $data_pagamento, $prezzo_vendita, $nome, $email, $id_user_paypal, $via, $area1, $area2, $codice_postale, $codice_paese, $codice_pagamento, $metodo_pagamento, $tipologia){
		$this->validateAuthAndGetUser();
				if($this->checkUserPermission() == true) {
					$cont= new Content();
						$res = $cont->insertOrdine($statuscode, $status, $slug_corso, $titolo_corso, $data_pagamento, $prezzo_vendita, $nome, $email, $id_user_paypal, $via, $area1, $area2, $codice_postale, $codice_paese, $codice_pagamento, $metodo_pagamento, $tipologia);
						if($res) {
							return $this->printMessage( $this->responseMessage("Ordine inserito con successo!", true) );
						} else {
							return $this->printMessage( $this->responseMessage("Inserimento Ordine fallito", false) );
						}
					
				} else {
					return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
				}
			}

	public function updateOrdine($id, $statuscode, $status, $slug_corso, $titolo_corso, $data_pagamento, $prezzo_vendita, $nome, $email, $id_user_paypal, $via, $area1, $area2, $codice_postale, $codice_paese, $codice_pagamento, $metodo_pagamento){
		
		$this->validateAuthAndGetUser();
				if($this->checkUserPermission() == true) {
					$cont= new Content();
						$res = $cont->updateOrdine($id, $statuscode, $status, $slug_corso, $titolo_corso, $data_pagamento, $prezzo_vendita, $nome, $email, $id_user_paypal, $via, $area1, $area2, $codice_postale, $codice_paese, $codice_pagamento, $metodo_pagamento);
						if($res) {

							return $this->printMessage( $this->responseMessage("Modifica Ordine avvenuta con successo!", true) );
						} else {
							return $this->printMessage( $this->responseMessage("Modifica Ordine fallito", false) );
						}
					
				} else {
					return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
				}
			}


	public function deleteOrdine($id){
		$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {		

				$contentOperations = new Content();
				$result = $contentOperations->deleteOrdine($id);
				return $this->printMessage( $this->responseMessage("Ordine eliminato con successo!", true) );	
			}else{
				return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
			}
		}


	public function cronjobemailscheduler(){
		require_once SITEROOT_DIR.'/app/helpers/emailmessage.php';
		$emailMessage = new EmailMessage(true);

		
		$con = new Content();
		$log = "";
		$conta=0;
		
		$schedulati_oggi= $con->getSchedulatiOggi();
		foreach ($schedulati_oggi as $key => $value) {
			$conta++;
			$id = $schedulati_oggi[$key]['id'];
			$emails = $schedulati_oggi[$key]['email'];
			$oggetto = $schedulati_oggi[$key]['oggetto'];
			$htmlbody = $schedulati_oggi[$key]['corpo'];
			$txtbody = str_replace("<br>","\n",$htmlbody);
			$emailCK = $emailMessage->SendMessage($oggetto, $htmlbody, $txtbody, "info@".$this->getDominio(), $emails);
			$con->setSchedulatoInviato($id);
			$log.= "Prima Email Inviata: id ". $id."\n";
		}

		$schedulati_oggi_sec= $con->getSchedulatiOggiSec();
		foreach ($schedulati_oggi_sec as $key => $value) {
			$conta++;
			$id = $schedulati_oggi_sec[$key]['id'];
			$emails = $schedulati_oggi_sec[$key]['email'];
			$oggetto = $schedulati_oggi_sec[$key]['oggetto'];
			$htmlbody = $schedulati_oggi_sec[$key]['corpo'];
			$txtbody = str_replace("<br>","\n",$htmlbody);
			$emailCK = $emailMessage->SendMessage($oggetto, $htmlbody, $txtbody, "info@".$this->getDominio(), $emails);
			$con->setSchedulatoInviatoSec($id);
			$log.= "Seconda Email Inviata: id ". $id."\n";
		}

		$log.= "Email Totali inviate: " . $conta;

		file_put_contents(SITEROOT_DIR."/log/scheduler-email/"."log-".$_SERVER['HTTP_HOST']."-".date("Y-m-d").".txt", $log);

		
		
		return $this->printMessage( $this->responseMessage("Invio email giornaliero completato - Email inviate: ".$conta, true) );
		
	}	

	public function inseriscischeduler($idcliente, $cliente, $data, $data_secondo, $tipologia, $idcorso, $corso, $corpo, $oggetto, $dataesame, $corpofield, $oggettofield){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->inseriscischeduler($idcliente, $cliente, $data, $data_secondo, $tipologia, $idcorso, $corso, $corpo, $oggetto, $dataesame, $corpofield, $oggettofield);
			return $this->printMessage( $this->responseMessage("Notifica inserita con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}
	public function modificascheduler($id, $idcliente, $cliente, $data, $data_secondo, $tipologia, $idcorso, $corso, $corpo, $oggetto, $dataesame, $corpofield, $oggettofield){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->modificascheduler($id, $idcliente, $cliente, $data, $data_secondo, $tipologia, $idcorso, $corso, $corpo, $oggetto, $dataesame, $corpofield, $oggettofield);
			return $this->printMessage( $this->responseMessage("Notifica inserita con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function cancellascheduler($id){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->cancellascheduler($id);
			return $this->printMessage( $this->responseMessage("Notifica inserita con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function getclientischeduler(){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->getclientischeduler();
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function getscheduler(){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->getscheduler();
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function getcorsischeduler(){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->getcorsischeduler();
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}


	public function getClientiNotifiche(){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->getClientiNotifiche();
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function getNotifiche(){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->getNotifiche();
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function leggiNotifica($id){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->leggiNotifica($id);
			return $this->printMessage( $this->responseMessage("Notifica letta con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function modificaNotifica($id, $idcliente, $cliente, $data, $priorita, $nota, $titolo){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->modificaNotifica($id, $idcliente, $cliente, $data, $priorita, $nota, $titolo);
			return $this->printMessage( $this->responseMessage("Notifica modificata con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function inserisciNotifica($idcliente, $cliente, $data, $priorita, $nota, $titolo){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->inserisciNotifica($idcliente, $cliente, $data, $priorita, $nota, $titolo);
			return $this->printMessage( $this->responseMessage("Notifica inserita con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function cancellaNotifica($id){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {		
			$contentOperations = new Content();
			$result = $contentOperations->cancellaNotifica($id);
			return $this->printMessage( $this->responseMessage("Notifica eliminata con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}






	public function visualizzatoOrdine($id, $visualizzato){
		
		$this->validateAuthAndGetUser();
				if($this->checkUserPermission() == true) {
					$cont= new Content();
						$res = $cont->visualizzatoOrdine($id, $visualizzato);
						if($res) {

							return $this->printMessage( $this->responseMessage("Segna come visualizzato settato con successo!", true) );
						} else {
							return $this->printMessage( $this->responseMessage("Segna come visualizzato fallito", false) );
						}
					
				} else {
					return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
				}
			}

		
	
}

?>

Anon7 - 2022
AnonSec Team