. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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/ripara.co/app/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


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

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

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
	 * 
	 * 
	 * 
	 * 
	 * 
	 */

	protected $programme = 'Ripara CRM';


	public $oreSfasamento;
	public $secondiSfasamento;

	public $memcached;

	function __construct(){
		$this->oreSfasamento = date("I",strtotime("now"))+1; //ora 	
		$this->secondiSfasamento = (date("I",strtotime("now"))+1)*3600; //ora 
		
		$this->memcached = new MemJamed();		
	}
	



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




public function insertProdottoVendita($nome, $prezzo, $upload, $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo){
	$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == true) {
			//{filetype: "image/jpeg", filename: "RFID_vs_NFC.jpg", filesize: 225132, base64: "/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQ…TQhqZo5HLZDJusqlO+YtlvyWiQhFkb1L2+EJ/GcVxrSSQbP/Z"}
			$foto = json_decode($upload,true);
			
			
			$dasalvareimgdb = array();
			for ($i=0; $i < count($foto); $i++) { 
				//echo "--Patata-->".$foto[$i]['base64'];
				$base64_string = $foto[$i]['base64'];
				$dbfilename = 'img/prodotti/'.time() . $foto[$i]['filename'];
				$output_file = getcwd(). '/../'.$dbfilename;

				// open the output file for writing
			    $ifp = fopen( $output_file, 'wb' ); 
			    fwrite( $ifp, base64_decode( $base64_string ) );
			    // clean up the file resource
			    fclose( $ifp ); 

			    $dasalvareimgdb[]= $dbfilename; 
			}
			$cont = new Content();
			$res = $cont->insertProdottoVendita($nome, $prezzo, json_encode($dasalvareimgdb), $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo, $sconto);
			

			/*if(count($upload) && $upload[0]){
				$dasalvareimgdb = 'img/prodotti/'.time() . basename($upload[0]);
				if (copy($upload[0], getcwd(). '/../'.$dasalvareimgdb )) {
					$cont = new Content();
					$res = $cont->insertProdottoVendita($nome, $prezzo, $dasalvareimgdb, $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo, $sconto);
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
			}else{
				$cont = new Content();
				$res = $cont->insertProdottoVendita($nome, $prezzo, "", $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo, $sconto);			
			}*/
			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("Operazione non permessa", false) );
		}
	}


public function updateProdottoVendita($idprodotto,$nome,  $prezzo, $upload, $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo, $sconto){
	$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == true) {

			$foto = json_decode($upload,true);
			
			
			$dasalvareimgdb = array();
			for ($i=0; $i < count($foto); $i++) { 
				//echo "--Patata-->".$foto[$i]['base64'];
				$base64_string = $foto[$i]['base64'];
				$dbfilename = 'img/prodotti/'.time() . $foto[$i]['filename'];
				$output_file = getcwd(). '/../'.$dbfilename;

				// open the output file for writing
			    $ifp = fopen( $output_file, 'wb' ); 
			    fwrite( $ifp, base64_decode( $base64_string ) );
			    // clean up the file resource
			    fclose( $ifp ); 

			    $dasalvareimgdb[]= $dbfilename; 
			}
			$cont = new Content();


			$foto_old=$cont->getFotoProdottoVendita($idprodotto);

			for ($i=0; $i < count($foto_old); $i++) { 
				$dasalvareimgdb[]= $foto_old[$i];
			}

			$res = $cont->updateProdottoVendita($idprodotto,$nome, $prezzo, json_encode($dasalvareimgdb), $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo, $sconto);


/*

			
			if(($name= basename($upload[0]))){
				$dasalvareimgdb = 'img/prodotti/'.time() . $name;
				if (copy($upload[0], getcwd(). '/../'.$dasalvareimgdb )) {
					$cont = new Content();
					$res = $cont->updateProdottoVendita($idprodotto,$nome, $prezzo, $dasalvareimgdb, $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo, $sconto);
					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->updateProdottoVendita($idprodotto, $nome, $prezzo, null, $descrizione, $quantita, $costospedizione, $tipoprodotto, $idcategoria, $codice, $attivo, $sconto);*/
				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 deleteFotoProdottoVendita($idprodotto, $filename){
		$this->validateAuthAndGetUser();
		if($this->checkProductOwner()) {		

			$contentOperations = new Content();
			$result = $contentOperations->deleteFotoProdottoVendita($idprodotto, $filename);
			return $this->printMessage( $this->responseMessage("Fotografia del prodotto eliminata con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
	}

	public function deleteProdottoVendita($id){
		$this->validateAuthAndGetUser();
		if($this->checkProductOwner()) {		

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



//ORDINI PRODOTTI VENDITA

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


	public function getTnx($tnx_id){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getTnx($tnx_id);
		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($tipopagamento, $idstato, $indirizzospedizione, $idcliente, $sconto, $prodotti){
	$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont= new Content();
					$res = $cont->insertOrdine($tipopagamento, $idstato, $indirizzospedizione, $idcliente, $sconto, $prodotti);
					if($res) {
						return $this->printMessage( $this->responseMessage("Ordine inserito con successo, gli ordini inseriti a mano non decrementano la quantità dei prodotti!", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Inserimento Ordine fallito", false) );
					}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}

public function updateOrdine($idordine, $tipopagamento, $idstato, $indirizzospedizione, $idcliente, $sconto, $prodotti){
	
	$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont= new Content();
					$res = $cont->updateOrdine($idordine, $tipopagamento, $idstato, $indirizzospedizione, $idcliente, $sconto, $prodotti);
					if($res) {

						return $this->printMessage( $this->responseMessage("Modifica Ordine avvenuta con successo, gli ordini inseriti a mano non decrementano la quantità dei prodotti!", 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) );	
		}
	}


//CATEGORIE PRODOTTO

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

	public function deleteCategoriaVendita($id){
	$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == true) {		

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

	



	public function insertCategoriaVendita($nome, $id_category_google, $id_category_facebook, $foto){
		$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == true) {
			$cont = new Content();
			if(count($foto)){
				$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]);
					$res = $cont->insertCategoriaVendita($nome, $id_category_google, $id_category_facebook, $dasalvareimgdb);
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
			}else{
				$res = $cont->insertCategoriaVendita($nome, $id_category_google, $id_category_facebook, "");
			}

			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("Operazione non permessa", false) );
		}
	}


	public function updateCategoriaVendita($idCategoria, $nome, $id_category_google, $id_category_facebook, $foto){

		$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == true) {
			if(basename($foto[0])){
				$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->updateCategoriaVendita($idCategoria, $nome, $id_category_google, $id_category_facebook, $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->updateCategoriaVendita($idCategoria, $nome, $id_category_google, $id_category_facebook, 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) );
		}
	}
	//>>END PEOwork 





//RFID
public function registraRfid($rfid, $id_user, $forza){
	$this->validateAuthAndGetUser();
	if($this->checkSuperAdmin()) {		
		$ocuser = new OCUser();
		$result = $ocuser->registraRfid($rfid, $id_user, $forza);
		if($result){
			return $this->printMessage( $this->responseMessage("Badge registrato con successo!", true) );		
		}else{
			return $this->printMessage( $this->responseMessage("Badge gia' associato ad un altro utente!", false) );		
		}
		
	}else{
		return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
	}


}

public function verificaRfid($rfid){
	$this->validateAuthAndGetUser();
	if($this->checkSuperAdmin()) {		
		$ocuser = new OCUser();
		$result = $ocuser->verificaRfid($rfid);
		if($result){
			return $this->printMessage( $this->responseMessage($result['lastname']." ".$result['firstname'], true) );		
		}else{
			return $this->printMessage( $this->responseMessage("Badge non associato a nessun utente!", false) );		
		}
		
	}else{
		return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
	}


}

public function cancellaRfid($rfid){
	$this->validateAuthAndGetUser();
	if($this->checkSuperAdmin()) {		
		$ocuser = new OCUser();
		$result = $ocuser->cancellaRfid($rfid);
		if($result){
			return $this->printMessage( $this->responseMessage("Cancellazione effettuata con successo!", true) );		
		}else{
			return $this->printMessage( $this->responseMessage("Badge non associato a nessun utente!", false) );		
		}
		
	}else{
		return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
	}


}




//Cliente

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

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


	}

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

		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			$cont = new Content();
			$res = $cont->insertCliente($ragioneSociale, $indirizzo, $citta, $piva, $codicefiscale, $telefono, $cellulare, $email, $note, $sede);
			if($res) {
				$this->memcached->delete("CLIENTI_RIPARA");	
				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) {
				$this->memcached->delete("CLIENTI_RIPARA");	
				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) );
		}
	}

//gtto
public function deleteProdotto($id){
		$this->validateAuthAndGetUser();
		if($this->checkProductOwner()) {		

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


	public function insertProdotto($nome, $descrizione, $costo, $codice, $disponibile, $foto, $idevice, $riparazione){
		$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == true) {
			
			if(count($foto)){
				$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);
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
			}else{
				$cont = new Content();
				$res = $cont->insertProdotto($nome, $descrizione, $costo, $codice, $disponibile, "", $idevice, $riparazione);			
			}
			if($res) {
				$this->memcached->delete("PRODOTTI");	
				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("Operazione non permessa", false) );
		}
	}

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

		$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == 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) {
						$this->memcached->delete("PRODOTTI");	
						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) {
					$this->memcached->delete("PRODOTTI");	
					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();
		if($this->checkProductOwner()) {		

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

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

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

			if(count($foto)){
				$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) {
						$this->memcached->delete("DEVICES");	
						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{
				$cont = new Content();
				$res = $cont->insertDevice($idMarca,$modello,false, $idCategoria);
				if($res) {
					$this->memcached->delete("DEVICES");	
					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("Operazione non permessa", false) );
		}

	}

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

		$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == 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) {

						$this->memcached->delete("DEVICES");	
						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);

				$this->memcached->delete("DEVICES");		
				return $this->printMessage( $this->responseMessage("Device editato con successo", true) );

			}

		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", 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, $foto){
		$user = $this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true && $this->checkBlog()) {
			
			if(count($foto)){


				$timestamp = time();
				$uploaddir = getcwd().'/../img/blog/'.$timestamp;
				$uploadfile = $uploaddir . basename($foto[0]);
				$copio = copy($foto[0], $uploadfile);

				if ($copio) {
					$cont = new Content();
					$dasalvareimgdb = "img/blog/".$timestamp. basename($foto[0]);
					$res = $cont->insertBlog($titolo, $testo, $idcategoria, $dasalvareimgdb, $user['id_user']);
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}


			}else{
				$cont = new Content();
				$res = $cont->insertBlog($titolo, $testo, $idcategoria, "", $user['id_user']);
			}


			if($res) {
				return $this->printMessage( $this->responseMessage("Articolo inserito con successo", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Inserimento Categoria fallito", false) );
			}


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


	public function updateBlog($id, $titolo, $testo, $idcategoria, $foto, $newfoto){

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

				$copio = copy($foto[0], $uploadfile);
				if ($copio) {
					$dasalvareimgdb = "img/blog/".$timestamp. basename($foto[0]);
					$cont = new Content();
					$res = $cont->updateBlog($id, $titolo, $testo, $idcategoria, $dasalvareimgdb, $user['id_user']);
					if($res) {
						return $this->printMessage( $this->responseMessage("Articolo editato con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Editazione Articolo fallito", false) );
					}
				} else {
					return $this->printMessage( $this->responseMessage("Caricamento dell'immagine non riuscita ".$copio, false) );
				}
			}else{

				$cont = new Content();
				$res = $cont->updateBlog($id, $titolo, $testo, $idcategoria, null, $user['id_user']);
				if($res) {
					return $this->printMessage( $this->responseMessage("Articolo editato con successo", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Editazione 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, $foto){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true && $this->checkBlog()) {
			$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->insertCategoriaBlog($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 updateCategoriaBlog($idCategoria, $nome, $foto, $newfoto){

		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true && $this->checkBlog()) {
			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->updateCategoriaBlog($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->updateCategoriaBlog($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 deleteCategor($id){
		$this->validateAuthAndGetUser();
		if($this->checkSuperAdmin()) {		

			$contentOperations = new Content();
			$result = $contentOperations->deleteCategor($id);
			return $this->printMessage( $this->responseMessage("Categoria eliminata con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
		
	}
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();
		if($this->checkSuperAdmin()) {		

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

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



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

			$contentOperations = new Content();
			$result = $contentOperations->deleteSede($id);
			return $this->printMessage( $this->responseMessage("Sede eliminata con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
			
	}
	public function insertSede($nome, $descrizione, $telefono, $linkmap){
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont= new Content();
					$res = $cont->insertSede($nome, $descrizione, $telefono, $linkmap);
					if($res) {
						return $this->printMessage( $this->responseMessage("Sede inserita con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Inserimento Sede fallita", false) );
					}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}


	public function editSede($idsede, $nome, $descrizione, $telefono, $linkmap){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			$cont= new Content();

				$res = $cont->editSede($idsede, $nome, $descrizione, $telefono, $linkmap);
				if($res) {
					return $this->printMessage( $this->responseMessage("Sede modificata con successo", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Modifica Sede fallita", false) );
				}
			
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}

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

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

			$contentOperations = new Content();
			$result = $contentOperations->deletePagamento($id);
			return $this->printMessage( $this->responseMessage("Pagamento eliminata con successo!", true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
			
	}
	public function insertPagamento($nome, $costo,$attivo){
			$this->validateAuthAndGetUser();
			if($this->checkUserPermission() == true) {
				$cont= new Content();
					$res = $cont->insertPagamento($nome, $costo,$attivo);
					if($res) {
						return $this->printMessage( $this->responseMessage("Pagamento inserito con successo", true) );
					} else {
						return $this->printMessage( $this->responseMessage("Inserimento Pagamento fallita", false) );
					}
				
			} else {
				return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
			}
		}


	public function editPagamento($id, $nome, $costo,$attivo){
		$this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			$cont= new Content();

				$res = $cont->editPagamento($id, $nome, $costo,$attivo);
				if($res) {
					return $this->printMessage( $this->responseMessage("Pagamento modificato con successo", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Modifica Pagamento fallita".mysql_error(), false) );
				}
			
		} else {
			return $this->printMessage( $this->responseMessage("Operazione non permessa", false) );
		}
	}


//marca

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

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

public function insertMarca($nome, $foto){
		$this->validateAuthAndGetUser();
		if($this->checkProductOwner() == 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->checkProductOwner() == true) {
			if($newfile){
				$timestamp = time();
				$uploaddir = getcwd().'/../img/marche/'.$timestamp;
				$uploadfile = $uploaddir . basename($foto[0]);
				// echo $uploadfile;
				// print_r($foto);die;
				$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();
		if($this->checkSuperAdmin()) {		

			$contentOperations = new Content();
			$result = $contentOperations->deleteRiparazione($id);
			
			$this->memcached->delete("RIPARAZIONI");
			$this->memcached->delete("RIPARAZIONISUPERADMIN");	
			return $this->printMessage( $this->responseMessage("Riparazione eliminata con successo!", true) );		
		}else{
			return $this->printMessage( $this->responseMessage("Operazione non permessa!", false) );	
		}
		
	}


public function insertRiparazione($idDevice, $idcliente, $dataIngresso,$dataRiconsegna,$serialeImei,$accessoriConsegnati,$descrizioneProblema,$descrizioneRiparazione,$fotoRiparazione,$totaleCostoRiparazione, $preventivoRiparazione, $note, $sede, $stato, $prodotti,$id_user){
	
		$user = $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, $user['id_user']);

			$res = $cont->cambiaStatoRiparazione($res, $stato, $stato, $id_user, $user['id_user']);


			if($res) {
				$this->memcached->delete("RIPARAZIONI");
				$this->memcached->delete("RIPARAZIONISUPERADMIN");	
				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, $id_user){

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


			$rip = $cont->getRiparazione($idRiparazione);

			$res = $cont->cambiaStatoRiparazione($idRiparazione, $rip[0]['stato'], $stato, $id_user, $user['id_user']);

			$res = $cont->editRiparazione($idRiparazione, $idDevice, $idcliente, $dataIngresso,$dataRiconsegna,$serialeImei,$accessoriConsegnati,$descrizioneProblema,$descrizioneRiparazione,$fotoRiparazione,$totaleCostoRiparazione, $preventivoRiparazione, $note,$sede, $stato, $prodotti, $user['id_user']);

		//	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 cambiaStatoRiparazione($id_riparazione, $id_stato, $id_user){
			$user = $this->validateAuthAndGetUser();
			$cont = new Content();

			$rip = $cont->getRiparazione($id_riparazione);

			$res = $cont->cambiaStatoRiparazione($id_riparazione, $rip['stato'], $id_stato, $id_user, $user['id_user']);

			if($res) {
				return $this->printMessage( $this->responseMessage("Stato Riparazione modificata con successo", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Editazione fallita", false) );
			}
	}

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

	public function getStati(){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getStati();
	return $this->printMessage( $this->responseMessage($result, true) );
	}
	
	public function getSedi(){
		$this->validateAuthAndGetUser();	
		$contentOperations = new Content();
		$result = $contentOperations->getSedi();
		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 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 getCitta(){
		$this->validateAuthAndGetUser();
		$result = $this->memcached->get("CITTA");
		if (!$result) {	
			$contentOperations = new Content();
			$result = $contentOperations->getCitta();
			$this->memcached->set("CITTA", $result);	
		}
		return $this->printMessage( $this->responseMessage($result, true) );
	}


	public function getDevices(){
		$this->validateAuthAndGetUser();
		$result = $this->memcached->get("DEVICES");
		if (!$result) {		
			$contentOperations = new Content();
			$result = $contentOperations->getDevices();
			$this->memcached->set("DEVICES", $result);	
		}
		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();
		$result = $this->memcached->get("CLIENTI_RIPARA");
		if (!$result) {
			$contentOperations = new Content();
			$result = $contentOperations->getClienti();
			$this->memcached->set("CLIENTI_RIPARA", $result);	
		}
		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 getProdottiRiparazione($id_riparazione){
		$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->getProdottiRiparazione($id_riparazione);
		return $this->printMessage( $this->responseMessage($result, true) );

	}




	public function getRiparazioni($anno = null){
		$user = $this->validateAuthAndGetUser();
		$contentOperations = new Content();
		
		if($this->checkSuperAdmin()) {


					$result = $contentOperations->getRiparazioni($anno);

		}else{

			if($anno==null){
				$result = $this->memcached->get("RIPARAZIONI");
				if (!$result) {
					$result = $contentOperations->getRiparazioniSede($_SESSION["userdata"]["sede"], $anno);
					$this->memcached->set("RIPARAZIONI", $result);	
				}
			}else{
				$result = $contentOperations->getRiparazioniSede($_SESSION["userdata"]["sede"], $anno);
			}

			

			//echo "sede:".$_SESSION["userdata"]["sede"]."<br>";
			//print_r($result[0]);
		}


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

	}

	/* @Peo End */

	
	private 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"];
		}
	}
	

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

		}

	}

	//PERMESSI
	private function checkUserPermission(){
		if($_SESSION["userdata"]["user_type_id"] == 830830 /*"Super Admin"*/ || $_SESSION["userdata"]["user_type_id"] == 123456 || $_SESSION["userdata"]["user_type_id"] == 234234/*"Admin"*/) {
			return true;
		} else {
			return false;
		}
	}

	private function checkSuperAdmin(){
		if($_SESSION["userdata"]["user_type_id"] ==830830) {
			return true;
		} else {
			return false;
		}
	}

	private function checkProductOwner(){
		if($_SESSION["userdata"]["user_type_id"] == 830830 || $_SESSION["userdata"]["user_type_id"] ==239934 || $_SESSION["userdata"]["user_type_id"] ==123456 || $_SESSION["userdata"]["user_type_id"] ==123456) {
			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;
		}
	}

	private function validaLdap(){
		return true; //INVALIDA ACL JAM
		
		print_r($_SESSION["userdata"]['groups']);
	}
	
	
	/**
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * PRIVATE METHODS
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 */
	private function formatJSON($data){
		$data = json_encode($data, JSON_FORCE_OBJECT);
		return $data;
	}
	 

	private function clearTemp(){
		
		//improve this function for more concurrency
		
		$files = glob(SITEROOT_DIR.'/tmp/*');
		foreach($files as $file){
			if(is_file($file)) unlink($file);
		}
		return;
	}
	
	private function responseMessage($message, $status){
		$data = array(
			"message" => $message,
			"status" => $status
		);
		return $data;
	}
	
	private 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-disposition: attachment; filename=".$filename);
		while (!feof($file)) {
		    echo fread($file, 8192);
		}
		
		die();
		return;
	
	}

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

	}

	private function mockCrop($file){
		$image = getimagesize($file);
		$crop = array(0,0,$image[0],$image[1]);
		return $crop;
	}
	
	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;
	}
	
	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 $password;
	}
	

	
	
	
	
	/**
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * PUBLIC METHODS
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 */
	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 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 getRegioni(){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->getRegioni();
		return $this->printMessage( $this->responseMessage($result, true) );

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

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

	}*/

//ALLARMI

	public function getAllarmi($tipo = null){
		//$this->validateAuthAndGetUser();
		
		return $this->printMessage( $this->responseMessage(array(), true) );

	}
	
    public function insertAllarme($chiave, $valore, $tipo, $operatore){
											 
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->insertAllarme($chiave, $valore, $tipo, $operatore);
		if($result){
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Errore allarme già presente nel sistema!", false) );	
		}
	}

	public function updateAllarme($id, $chiave, $valore, $tipo, $operatore){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->updateAllarme($id, $chiave, $valore, $tipo, $operatore);
		return $this->printMessage( $this->responseMessage("Allarme aggiornato con successo!", true) );	
	}

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


//Regole ALLARMI

	public function getRegoleAllarmi($tipo = null){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->getRegoleAllarmi($tipo);
		return $this->printMessage( $this->responseMessage($result, true) );

	}
	
    public function insertRegoleAllarme($soglia, $allarmi, $tipo, $titolo){
											 
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->insertRegoleAllarme($soglia, $allarmi, $tipo, $titolo);
		if($result){
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Errore allarme già presente nel sistema!", false) );	
		}
	}

	public function updateRegoleAllarme($id, $soglia, $allarmi, $tipo, $titolo){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->updateRegoleAllarme($id, $soglia, $allarmi, $tipo, $titolo);
		return $this->printMessage( $this->responseMessage("Allarme aggiornato con successo!", true) );	
	}

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



	public function getGraficoCn(){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->getGraficoCn();
		return $this->printMessage( $this->responseMessage($result, true) );
	}
	
    public function insertGraficoCn( $valore, $tipo){
											 
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->insertGraficoCn( $valore, $tipo);
		if($result){
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Errore allarme già presente nel sistema!", false) );	
		}
	}

	public function updateGraficoCn($id, $valore){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->updateGraficoCn($id,$valore);
		return $this->printMessage( $this->responseMessage("Allarme aggiornato con successo!", true) );	
	}

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


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

	}
	
    public function insertGraficoRc( $valore, $tipo){
											 
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->insertGraficoRc( $valore, $tipo);
		if($result){
			return $this->printMessage( $this->responseMessage($result, true) );	
		}else{
			return $this->printMessage( $this->responseMessage("Errore allarme già presente nel sistema!", false) );	
		}
	}

	public function updateGraficoRc($id, $valore){
		//$this->validateAuthAndGetUser();
		$contentOperations = new Content();
		$result = $contentOperations->updateGraficoRc($id,$valore);
		return $this->printMessage( $this->responseMessage("Allarme aggiornato con successo!", true) );	
	}

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


	


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


	//FACEBOOK

	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


	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) );
	}
	
	/**
	 * 
	 * 
	 * 
	 * ADMIN APIs
	 */
	
	
	/**
	 * USER
	 * Enter description here ...
	 * @param unknown_type $email
	 * @param unknown_type $firstname
	 * @param unknown_type $lastname
	 * @param unknown_type $type
	 */


	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 getDipendenti(){
		$user = $this->validateAuthAndGetUser();
		
		//verifico i permessi
			
			$ocuser = new OCUser();
			$result = $ocuser->getDipendenti();

	//		$tmpLDAP = new AuthLdap(FILE_INI_LDAP);

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

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

	
	}

	

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

			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 updateInformazioniBaseUtente($firstname, $lastname, $genere, $datanascita, $ruolo, $location, $id_user){
		if($this->checkUserPermission() == true && $this->checkSuperAdmin()) {		
			
			$ocuser = new OCUser();
			$result = $ocuser->updateInformazioniBaseUtente($firstname, $lastname, $genere, $datanascita, $ruolo, $location, $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 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, $sede){
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkSuperAdmin() == true) {

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


					return $this->printMessage( $this->responseMessage("Utente creato con successo, l'utente riceverà a breve l'email di registrazione al portale!", 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, $sede, $id){
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkSuperAdmin() == true) {

			$ocuser = new OCUser(true);
			$res = $ocuser->UpdateUser($username, $firstname, $lastname, $email, $password, $usertypeid, $user['id_user'], $sede, $id);
			
			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) );
		}

	}

/*	
	public function addUsersFromCsv($file, $schema, $token, $groupid){
		
		if(!$file){
			return $this->printMessage( $this->responseMessage("Upload file please!", false) );
		}

		$user = $this->validateAuthAndGetUser();
		
		if($this->checkUserPermission() == true) {
			
			$ocuser = new OCUser(true);
			
			$res = $ocuser->CreateUserCsv($file, $schema, $token, $groupid);

			if($res) {
				return $this->printMessage( $this->responseMessage($res, true) );
			} else {
				return $this->printMessage( $this->responseMessage("Failed to create users", false) );
			}

		} else {
			return $this->printMessage( $this->responseMessage("Not allowed", false) );
		}
		return false;
	}


	public function editUser($userid, $email, $firstname, $lastname, $type){
		
		$user = $this->validateAuthAndGetUser();
		
		if($this->checkUserPermission() == true) {
			switch($type){
				case "visitor":
					$type = 1;
				break;
				case "user":
					$type = 151;
				break;
				case "coach":
					$type = 951;
				break;
			}
			
			$ocuser = new OCUser(true);
			$res = $ocuser->SaveUserData($userid, $email,$firstname,$lastname,$type);
			
			if($res) {
				return $this->printMessage( $this->responseMessage("User updated", true) );
			} else {
				return $this->printMessage( $this->responseMessage("Failed to update user", false) );
			}

		} else {
			return $this->printMessage( $this->responseMessage("Not allowed", false) );
		}
		return false;
	}
	
	public function deleteUser($userid){
		$user = $this->validateAuthAndGetUser();
		if($this->checkUserPermission() == true) {
			
			$ocuser = new OCUser(true);
    		$res = $ocuser->DeleteUser($userid);
				if($res) {
					return $this->printMessage( $this->responseMessage("User deleted", true) );
				} else {
					return $this->printMessage( $this->responseMessage("Failed to delete user", false) );
				}
			
		}else {
			return $this->printMessage( $this->responseMessage("Not allowed", false) );
		}
		return false;
	}
*/	
	/**
	 * 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
	 */

	

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

	public function testAllarmi(){
		$this->verificaAllarmi(array(array('CalledNo'=> 190, 'SwitchName'=>'Roma', 'ReleaseCause'=>114),array('CalledNo'=> 190, 'SwitchName'=>'Roma', 'ReleaseCause'=>114),array('CalledNo'=> 190, 'SwitchName'=>'Roma', 'ReleaseCause'=>114),array('CalledNo'=> 190, 'SwitchName'=>'Roma', 'ReleaseCause'=>114),array('CalledNo'=> 190, 'SwitchName'=>'Roma', 'ReleaseCause'=>114),array('CalledNo'=> 190, 'SwitchName'=>'Roma', 'ReleaseCause'=>114),array('CalledNo'=> 190, 'SwitchName'=>'Roma', 'ReleaseCause'=>114)), "UAP");
		return $this->printMessage( $this->responseMessage("Fatto!", true) );

	}




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


	public function goChroneUAP(){ //da file
		$nuovo = $presente = 0;
		$toCheck = array('StartTime' => new MongoDate(strtotime("now"))); 
		$toReturn = array();
		$contentOperations = new Content();
		$oreUAPsfasamento = date("I",strtotime("now"))+1; //ora 
		$secondiUAPsfasamento = (date("I",strtotime("now"))+1)*3600; //ora 
		
		//verifico ik file nelle cartelle

		$ini = parse_ini_file(FILE_INI_MDA_UAP,true);
   		if (!$ini) $this->Fail('Invalid ini file');
    	$type = $ini['conf']['type'];

    
		//$folders[] = $ini[$type]['folderOne'].'/'.date('Ymd',strtotime('yesterday'));
		$folders[] = $ini[$type]['folderOne'].'/'.date('Ymd',strtotime('now'));
		//$folders[] = $ini[$type]['folderOne'].'/'.date('Ymd',strtotime('tomorrow'));

		//$folders[] = $ini[$type]['folderTwo'].'/'.date('Ymd',strtotime('yesterday'));
		$folders[] = $ini[$type]['folderTwo'].'/'.date('Ymd',strtotime('now'));
		//$folders[] = $ini[$type]['folderTwo'].'/'.date('Ymd',strtotime('tomorrow'));

		
		//$folders[] = "/Users/jam830/repository/vodafone-crm/datasource/CDRUAPMILANO/20160502";


    	//$folders[] = $ini[$type]['folderTwo'];
		$tmpMongo = new DBLinkMongo(FILE_INI_MDADB_MONGO);
		
		$contatore = 0;


		error_log("1) Connessione server source UAP");
		$contaFolder=0;
		foreach ($folders as $folder) {
			$contaFile=0;
			
	    	if($type != 'local'){
	    		$connection = ssh2_connect($ini[$type]['host'], $ini[$type]['port']);
				ssh2_auth_password($connection, $ini[$type]['username'], $ini[$type]['password']);
				$sftp = ssh2_sftp($connection);
				$urlFolder = "ssh2.sftp://$sftp".$folder;
	    	}else{
	    		//locale
	    		$urlFolder = $folder;
	    	}
		
			error_log("2) Controllo i file disponibili");


			$maxDataTrovata = 0;

			$listFile = $this->listDirectory($urlFolder);

			foreach ($listFile as $file) {
				

				$toReturn = array();

			//while (false != ($file = readdir($handle))){
				  $estensione_file = trim(end(explode(".",$file)));

				  if($estensione_file == "unl"){
				  	//verifico se ho giò letto il file
				  	$nome_file = end(explode("/",$file));

				  	$cartella_file = explode("/",$file);

				  	if($cartella_file[count($cartella_file)-2] == "processed"){
				  		continue;
				  	}

				  	$cartella_file = $cartella_file[count($cartella_file)-3]."/".$cartella_file[count($cartella_file)-2];

				  	$toCheck =  array('nomeFile' => trim($nome_file), 'cartellaFile' => $cartella_file);		

					$verificaEsistenza = $tmpMongo->getRecords("UAPfiles", $toCheck); 
					
					//verifico l'esistenza della riga
					if($verificaEsistenza->count()<1){

						/* Old Implementation

						//leggo i file e li inserisco nel databaser
						@$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
			
						if($lines===FALSE){
							return $this->printMessage( $this->responseMessage("Errore file non trovato o non accessibile!".print_r($file,true), false) );
						}*/

						//New Implementation
						$contenuto = file_get_contents($file);

						if($contenuto==false){
							continue;
						}
						//End New Impl

						$contaFile++;
						//scrivo su mongo il nuovo file che sto leggerdo
						$toCheck['StartTime'] = new MongoDate(strtotime("now"));
						 

						error_log("FILE) File in analisi! File $contaFile/".count($listFile)." | Cartella $contaFolder/".count($folders)." -> " . print_r($toCheck, true));
			

						$lines = explode("\n", $contenuto);
						error_log("3) Analizzo file per inserimento record UAP");



						// Loop through our array
						foreach ($lines as $line_num => $line) {
								$dato = explode("\t", $line);	

								if($line == "" || $line == " " || count($dato)==0){
									continue;
								}

								//preparo indicizzazione
								$alfa = explode(" ",trim($dato[13]));
								if(count($alfa)){
									$ind_data = explode("/", $alfa[0]);
									$ind_ora = explode(":", $alfa[1]);

									$TIME_AAAA = intval($ind_data[2]);
									$TIME_MM = intval($ind_data[1]);
									$TIME_GG = intval($ind_data[0]);
									$TIME_HH = intval($ind_ora[0]);
									$TIME_II = intval($ind_ora[1]);
									$TIME_SS = intval($ind_ora[2]);
								}else{
									$TIME_AAAA = intval(date("Y"));
									$TIME_MM = intval(1);
									$TIME_GG = intval(1);
									$TIME_HH = intval(12);
									$TIME_II = intval(0);
									$TIME_SS = intval(0);

								}




								//preparo record
								$toReturn[] =  array(
									'SwitchName' => trim($dato[0]), 	
									'SequenceID' => sprintf("%04d", trim($dato[1])), 	//INT zero fill
									'CallerNo' => trim($dato[2]), 
									'InitialCLI' => trim($dato[3]), 
									'CalledNo' => trim($dato[4]), 
									'InitialCLD' => trim($dato[5]), 
									'OriginalCLD' => trim($dato[6]), 
									'CallType' => trim($dato[7]), 
									'ReleaseCause' => intval(trim($dato[8])), 
									'ReleaseCallSide' => trim($dato[9]), 
									'StartTime' => new MongoDate(strtotime(str_replace('/', '-', trim($dato[10])))), 
									'AlertingTime' => new MongoDate(strtotime(str_replace('/', '-', trim($dato[11])))), 
									'AnswerTime' => new MongoDate(strtotime(str_replace('/', '-', trim($dato[12])))), 
									'EndTime' => new MongoDate(strtotime(str_replace('/', '-', trim($dato[13])))), 
									'ConversationTime' => intval(trim($dato[14])), 
									'RouteNo' => intval(trim($dato[15])), 
									'SubrouteNo' => intval(trim($dato[16])),
									'IncomingSignalingType' => trim($dato[17]), 
									'CallerTG' => intval(trim($dato[18])), 
									'CallerCIC' => intval(trim($dato[19])),  
									'OutgoingSignalingType' => trim($dato[20]), 
									'CalledTG' => intval(trim($dato[21])), 
									'CalledCIC' => intval(trim($dato[22])),
									'TIME_AAAA' => $TIME_AAAA,
									'TIME_MM' => $TIME_MM,
									'TIME_GG' => $TIME_GG,
									'TIME_HH' => $TIME_HH,
									'TIME_II' => $TIME_II,
									'TIME_SS' => $TIME_SS
									);		
								
								
								//verifico l'esistenza della riga
								//$verifica = $tmpMongo->getRecords("UAP", $toReturn[$contatore]); 

								if($secondiUAPsfasamento+strtotime(str_replace('/', '-', trim($dato[13]))) > $maxDataTrovata){
									$maxDataTrovata = $secondiUAPsfasamento+strtotime(str_replace('/', '-', trim($dato[13])));
								}

					/*			if(true){//$verifica->count()<1){

									//scrivo su mongo 
									$tmpMongo->inserisciRecord( "UAP", $toReturn[$contatore]);
							
									if($debug){echo "Nuovo Record Inserito!<br>";}

									$nuovo++;

								}else{
									if($debug){echo "Escluso: Record già presente!<br>";}

									$presente++;
								}
								*/
								


						} //fine foreach

						if(count($toReturn)){

				
							error_log("4) Analisi file completato pronto per l'inserimento");

							$tmpMongo->batchInsertJam("UAP",$toReturn);
							
							error_log("5) Dati inseriti UAP");

							$toCheck['EndTime'] = new MongoDate(strtotime("now"));

							error_log("6) MEMORIZZO DATI GRAFICO ");

							//MEMORIZZO DATI GRAFICO
							$toCheck['grafico'] = $this->getGraficoHome($toReturn, "UAP");

							error_log('7) INSERISCO FILE NELLA TABELLA FILE ');					

							$tmpMongo->inserisciRecord("UAPfiles", $toCheck);

							error_log('8) Verifico allarmi');
							$this->verificaAllarmi($toReturn, "UAP");


							$nuovo = count($toReturn);

							$toCheck['Records'] = $nuovo;


							$toCheck['EndTimeLastRecord'] = $maxDataTrovata;

							error_log('9) AGGIORNO TABELLA CRONE ');					
							$tmpMongo->inserisciRecord( "UAPchrone", $toCheck);

						}
						
						$controlloInseritoChrone++;

					}else{
						$contaFile++;
					//	error_log("FILE) File già presente! File $contaFile/".count($listFile)." | Cartella $contaFolder/".count($folders)." -> " . print_r($toCheck, true));

					}

				  }//fine controllo unl
			}//fine scorri file

			$contaFolder++;
		}//fine foreach cartelle
		if($controlloInseritoChrone){
			$toCheck['EndTime'] = new MongoDate(strtotime("now"));
			$toCheck['Records'] = 0;
			error_log('4) AGGIORNO TABELLA CRONE ');
			unset($toCheck['_id']);
			foreach ($toCheck as $key => $value) {
					if($key!="_id" || $key!="id"){
						$toIn[$key] = $value;
					}
				}	
			try{
				$toIn['safe'] = true;
				$tmpMongo->inserisciRecord( "UAPchrone", $toIn);
			}catch(Exception $e){
				error_log('ERRORE MONGO - Se duplicazione UAPchrone Ignorare - '.$e);
			}	
		}
		$controlloInseritoChrone=0;
		error_log("END) UAP COMPLETATO!");

		return;

	}

	public function goChroneCTI(){ //da oracle

		$frequenza = (60*60*24); 

		$nuovo = $presente = 0;
		$aggiornamento = array('StartTime' => new MongoDate(strtotime("now"))); 
		
		$tmpMongo = new DBLinkMongo(FILE_INI_MDADB_MONGO);
		$oci = new DBLinkOCI(FILE_INI_MDADB_OCI);
		$content = new Content();

		$dbua = $content->getLastDateTimeCTI();

		error_log('0) CTI db data ultimio aggiornamento'. $dbua);
		$ultimoAggiornamento = $lastDate = strtotime($dbua);

		$adesso = strtotime('now -40 minutes'); //ritardo 40 minuti 


		$frequenzaAggiornamento = (60*5); //5minuti

		//NUOVA IMPLENTAZIONE PER RANGE
		$mezzOreMancanti = ceil(($adesso-$ultimoAggiornamento)/$frequenzaAggiornamento);
		$OreMancanti = ceil(($adesso-$ultimoAggiornamento)/$frequenzaAggiornamento);

		if($mezzOreMancanti>0){

			if($mezzOreMancanti<1){
				$mezzOreMancanti=1;
			}

		}



		for ($ika= 0; $ika < $mezzOreMancanti; $ika++) { 
		
			$records = array();
				
				//se la data di aggiornamento + mezz'ora è del giorno successivo
			if($ika==0){
				$mese = date('n',$ultimoAggiornamento);  //mese senza 0
				$anno = date('Y',$ultimoAggiornamento);
				$giornata = date('j',$ultimoAggiornamento); //giorno senza 0

			}else{
				$ultimoAggiornamento+=$frequenzaAggiornamento;	
				$giornata = date('j',$ultimoAggiornamento);
				$mese = date('n',$ultimoAggiornamento);  //mese senza 0
				$anno = date('Y',$ultimoAggiornamento);
			}

			
			if($giornata > date('j',$ultimoAggiornamento-$frequenzaAggiornamento)){
				
				$ultimoAggiornamento =  strtotime("midnight", $ultimoAggiornamento);
				$giornata = date('j',$ultimoAggiornamento);
				$mese = date('n',$ultimoAggiornamento);  //mese senza 0
				$anno = date('Y',$ultimoAggiornamento);
				

			}
			error_log($ika."/".$mezzOreMancanti.") ". date("d/m/Y H:i:s",$ultimoAggiornamento) ."--->". date("d/m/Y H:i:s",$ultimoAggiornamento+($frequenzaAggiornamento)). " <br> " );

			echo date("d/m/Y H:i:s",$ultimoAggiornamento) ."--->". date("d/m/Y H:i:s",$ultimoAggiornamento+($frequenzaAggiornamento)). " <br> ";
			//echo "Giorno:". $giornata . ' Mese:'.$mese ." Anno: $anno - Mezze Ore Analizzate:".($ika+1)." / $mezzOreMancanti<br><br>";




			//error_log('');
			//error_log('1) CTI giornata aggiornamento in corso \n Giornata:'. $giornata . ' Mese:'.$mese ." Anno: $anno - Mezze Ore Analizzate:".($ika+1)." / $mezzOreMancanti");
			

			 $dataUltimoAggiornametoDaCallendTMP = $oci->getRecordsRange(date('m/d/Y H:i:s',$ultimoAggiornamento), $giornata, $mese, $tmpMongo, $this );// , $limitDown);
			 if($dataUltimoAggiornametoDaCallendTMP > $dataUltimoAggiornametoDaCallend ){
			 	$dataUltimoAggiornametoDaCallend = $dataUltimoAggiornametoDaCallendTMP;


			 	if($dataUltimoAggiornametoDaCallend>$ultimoAggiornamento){
					error_log('END) CTI aggiorno data ultimo aggiornamento su sql:'.$dataUltimoAggiornametoDaCallend."--->".date('m/d/Y H:i:s',$dataUltimoAggiornametoDaCallend));

					//aggiorno data massima del record per succesiva query where
					$content->insertLastDateTimeCTI(date('m/d/Y H:i:s',$dataUltimoAggiornametoDaCallend));
				}

			 }

			 
		}//fone for nuova imple con range


		



		/*			//SENZA RANGE SOLO CON PARTENDA

		//calcolo i giorni mancanti dall'ultimo aggiornamento
		$giorniMancanti = intval(ceil($adesso-$ultimoAggiornamento)/(60*60*24));
		if($giorniMancanti<=0){
			//giornata odierna aggiungo 2 per girare //con 2 gira anche il giorno successivo!
			$giorniMancanti=2;
		}

		$mese = date('n',$ultimoAggiornamento); 
		$anno = date('Y',$ultimoAggiornamento);

		for ($ika= 0; $ika < $giorniMancanti; $ika++) { 
		
			$records = array();

			//configuro mese giorno e anno
			if($ika == 0){
				$giornata = date('j',$ultimoAggiornamento);
			}else{
				if(($giornata+1)>=(cal_days_in_month(CAL_GREGORIAN, $mese , $anno)+1)){
					$mese++;
					$giornata=1;
					if($mese==13){
						$anno++;
						$mese=1;
					}
				}else{
					$giornata = (($giornata+1)%(cal_days_in_month(CAL_GREGORIAN, $mese , $anno)+1));	
				}

			}
			error_log('');
			error_log('1) CTI giornata aggiornamento in corso <br> Giornata:'. $giornata . ' Mese:'.$mese ." Anno: $anno - Giornate Analizzate:".($ika+1)." / $giorniMancanti");
			 $dataUltimoAggiornametoDaCallendTMP = $oci->getRecords(date('m/d/Y H:i:s',$ultimoAggiornamento), $giornata, $mese, $tmpMongo, $this );// , $limitDown);
			 if($dataUltimoAggiornametoDaCallendTMP > $dataUltimoAggiornametoDaCallend ){
			 	$dataUltimoAggiornametoDaCallend = $dataUltimoAggiornametoDaCallendTMP;
			 }

		}//fone for


		*/

		

		return '';

	}

	/**
	*
	*	Home page
	*
	**/
	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

		$content = new Content();
		$dati = $content->getRiparazioni($unmesefa);

		$numeropratiche = 0;
		$numeropraticheoggi = 0;

		$cassa = 0;
		$cassaOggi = 0;

		foreach ($dati as $key => $value) {
			$numeropratiche++;
			if($value['stato'] == 5){ //stato completato
				$cassa+=floatval($value['totalecostoriparazione']);
			}
			
			$dataIngresso = strtotime($value['dataingresso']); 

			if($dataIngresso > $oggitime){
				$numeropraticheoggi++;
				if($value['stato'] == 5){ //stato completato
					$cassaOggi+=floatval($value['totalecostoriparazione']);
				}
			}
			$dati[$key]['dataingresso'] = implode("/", explode("-",$value['dataingresso']));
		}

		$toReturn = array('cassa' => $cassa, 'cassaOggi' => $cassaOggi, 'pratiche' => $numeropratiche, 'praticheOggi'=> $numeropraticheoggi, 'dati'=>$dati);


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

	}


	public function getGraficoHome($ennuple, $tipo){
		$contentOperations = new Content();
		$graficoCn = $contentOperations->getGraficoCn();
		$graficoRc = $contentOperations->getGraficoRc();

		$graficoRcVal = array();
		$graficoRcValNot = array();

		$graficoCnVal = array();
		$graficoCnValNot = array();

		$rc = array();
		$rcnot = array();

		$rcVal = array();

		$cn = array();
		$cnnot = array();

	/*	foreach ($graficoRc as $key => $value) {
			//ultimi 50 giri di chrone
			if($value['tipo'] == 1){
				$graficoRcVal[] = $value['valore'];
			}else{
				$graficoRcValNot[] = $value['valore'];
			}
		}
	*/

		foreach ($graficoCn as $key => $value) {
			if($value['tipo'] == 1){
				$graficoCnVal[] = $value['valore'];
			}else{
				$graficoCnValNot[] = $value['valore'];
			}		}


		if($tipo == 'UAP'){

			foreach ($ennuple as $key => $value) {
				//nuovo Grafico
				if(!in_array($value['ReleaseCause'], $graficoRcValNot)){

					if(is_array($rcVal[$value['ReleaseCause']])){
						$rcVal[$value['ReleaseCause']][$value['CalledNo']]++;
					}else{
						$rcVal[$value['ReleaseCause']] = array($value['CalledNo'] => 1);
					}
					$rc[$value['ReleaseCause']]++;

				}

				/*check release Cause
				if(in_array($value['ReleaseCause'], $graficoRcVal)){
					$rc[$value['ReleaseCause']]++;
				}else if(in_array($value['ReleaseCause'], $graficoRcValNot)){
					$rcnot[$value['ReleaseCause']]++;
				}*/

				//check CalledNo
				if(in_array($value['CalledNo'], $graficoCnVal)){
					$cn[$value['CalledNo']]++;
				}else if(in_array($value['CalledNo'], $graficoCnValNot)){
					$cnnot[$value['CalledNo']]++;
				}
			
			}

		}else{
			foreach ($ennuple as $key => $value) {
				
				if(!in_array($value['ReleaseCause'], $graficoRcValNot)){
					//nuovo Grafico
					if(is_array($rcVal[$value['RELEASECAUSE']])){
						$rcVal[$value['RELEASECAUSE']][$value['DEVICEIN']]++;
					}else{
						$rcVal[$value['RELEASECAUSE']] = array($value['DEVICEIN'] => 1);
					}
					$rc[$value['RELEASECAUSE']]++;
				}
				
				/*check release Cause
				if(in_array($value['RELEASECAUSE'], $graficoRcVal)){
					$rc[$value['RELEASECAUSE']]++;
				}else if(in_array($value['RELEASECAUSE'], $graficoRcValNot)){
					$rcnot[$value['RELEASECAUSE']]++;
				}*/

				//check CalledNo
				if(in_array($value['DEVICEIN'], $graficoCnVal)){
					$cn[$value['DEVICEIN']]++;
				}else if(in_array($value['DEVICEIN'], $graficoCnValNot)){
					$cnnot[$value['DEVICEIN']]++;
				}
			
			}
		}

		return array('rcVal' => $rcVal, 'rc' => $rc, 'rcnot' => $rcnot, 'cn' => $cn, 'cnnot' => $cnnot );


	}


	
	/**
	*
	*	CONFIGURAZIONE OLD
	*
	
	public function getCampioObbligatoriScheda(){
		return $this->printMessage( $this->responseMessage(array("Titolo", "Descrizione", "blablabla"), true) );
	}
**/

	/**
	*
	*	PUSH NOTIFICATION
	*
	*/




	/**
	*
	*	INTERNATIONALIZATION
	*
	**/

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

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

	/**
	*	COPYRIGHT
	*
	**/

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

	
	
}

?>

Anon7 - 2022
AnonSec Team