<?php
	$docroot = $_REQUEST['docroot'];
	$id_record =  $_REQUEST['id_record'];
	$id_module =  $_REQUEST['id_module'];
	$externalid =  $id_record;
	
	include_once($docroot."/core.php");	
	
	//Lettura parametri iniziali modulo
	$rs = $dbo->fetchArray( "SELECT module_dir,name FROM zz_modules WHERE id=\"".$id_module."\"" );
	$module_dir = $rs[0]['module_dir'];
	$module_name = strtolower($rs[0]['name']);	
	
	$module_name = $rs[0]['name'];
	
	
	/*
		GESTIONE UPLOAD
	*/
	
	
	
	if( $_REQUEST['op'] == 'link_file' ){
		
		if( $modules_info[$module_name]["permessi"] == 'rw' ):
				
			$dir_ok = true;
			
			$nome = save( $_REQUEST['nome_allegato'] );
			$filename = $_FILES['blob']['name'];
			$src = $_FILES['blob']['tmp_name'];
			$f = pathinfo( $filename );

			$dst_file = sanitizeFilename( $f['filename'].".".$f['extension'] );
			$dst_dir = $docroot."/files/".$module_name."/";
			$dst_dir = strtolower($dst_dir);
			
			//Se la destinazione non esiste la creo
			if( !is_dir($dst_dir) ){
				if( !mkdir($dst_dir) ){
					$dir_ok = false;
					array_push( $_SESSION['errors'], "Non hai i permessi per creare directory in files!" );
					//header( "Location: ".$rootdir."/editor.php?id_module=".$modules_info[$nome_modulo]['id']."&id_record=".$externalid );
					exit;
				}
			}


			//Creazione file fisico
			if( $dir_ok ){
				//Rinomino il file se non esiste gi�
				$f = pathinfo($dst_file);
				$i = 1;
				
				while( file_exists($dst_dir."/".$dst_file) ){
					$dst_file = $f['filename']."_".$i.".".$f['extension'];
					$i++;
				}
				
				if( move_uploaded_file( $src, $dst_dir."/".$dst_file) ){
					$rs = $dbo->query("INSERT INTO `zz_files`( nome, data, filename, module, externalid ) VALUES( \"".$nome."\", NOW(), \"".$dst_file."\", \"".$module_name."\", \"".$externalid."\" )");
					array_push( $_SESSION['infos'], "File caricato correttamente!" );
					//header( "Location: ".$rootdir."/editor.php?id_module=".$modules_info[$nome_modulo]['id']."&id_record=".$externalid );
					exit;
				}
				
				else{
					array_push( $_SESSION['errors'], "Errore durante il caricamento del file!" );
					//header( "Location: ".$rootdir."/editor.php?id_module=".$modules_info[$nome_modulo]['id']."&id_record=".$externalid );
					exit;
				}
			}else{
					array_push( $_SESSION['errors'], "Non sono riuscito a creare la directory!" );
			}
		else:
		//	array_push( $_SESSION['errors'], "Non hai permessi di scrittura per il modulo: ".$module_name );
		endif;
	}
?>