<?php


function filelist_xml_import( $nome_modulo_xml, $externalid, $label='Nuovo allegato:', $showpanel=1 ){
	global $dbo;
	global $docroot;
	global $rootdir;
	global $theme_path;
	global $permessi;
	global $modules_info;

	$dir_ok = true;

	$nome_modulo_old=$nome_modulo_xml;
	$nome_modulo_xml = "import_xml";


	//Visualizzo l'elenco di file già caricati
	$rs = $dbo->fetchArray("SELECT * FROM zz_files WHERE module=\"".$nome_modulo_xml."\" AND externalid=\"".$externalid."\"");
	
	echo "<a name='attachments'></a>\n";
	
	if ($showpanel == 1):
	
	echo "	<div class=\"panel-body\">\n";

	endif;
	
	if( sizeof($rs)>0 ){
		echo "<table class=\"table table-condensed table-hover table-bordered\" >\n";
		echo "<tr><th>Descrizione</th>\n";
		echo "<th>File</th>\n";
		echo "<th>Data</th></tr>\n";
	

		for( $i=0; $i<sizeof($rs); $i++ ){
			echo "<tr><td align='left'><span title=\"".htmlentities($rs[$i]['nome'], ENT_QUOTES, "UTF-8")."\">".$rs[$i]['nome']."</span></td>\n";
			echo "<td><a href=\"".$rootdir."/files/".strtolower($nome_modulo_xml)."/".$rs[$i]['filename']."\" title=\"".htmlentities($rs[$i]['nome'], ENT_QUOTES, "UTF-8")."\" target=\"_blank\">".$rs[$i]['filename']."</a></td>\n";
			echo "<td>".date("d/m/Y H:i", strtotime($rs[$i]['data']) )."</td>\n";
			}

		echo "</table>\n";
	}
	
	if ($showpanel == 1):
	echo "</div>\n";
	endif;
}


function filelist_xml( $nome_modulo_xml, $externalid, $label='Nuovo allegato:', $showpanel=1 ){
	global $dbo;
	global $docroot;
	global $rootdir;
	global $theme_path;
	global $permessi;
	global $modules_info;

	$dir_ok = true;

	$nome_modulo_old=$nome_modulo_xml;
	$nome_modulo_xml = get_var("Percorso XML");


	//Visualizzo l'elenco di file già caricati
	$rs = $dbo->fetchArray("SELECT * FROM zz_files WHERE module=\"".$nome_modulo_xml."\" AND externalid=\"".$externalid."\"");
	
	echo "<a name='attachments'></a>\n";
	
	if ($showpanel == 1):
	
	echo "	<div class=\"panel-body\">\n";

	endif;
	
	if( sizeof($rs)>0 ){
		echo "<table class=\"table table-condensed table-hover table-bordered\" >\n";
		echo "<tr><th>Descrizione</th>\n";
		echo "<th>File</th>\n";
		echo "<th>Data</th></tr>\n";
	

		for( $i=0; $i<sizeof($rs); $i++ ){
			echo "<tr><td align='left'><span title=\"".htmlentities($rs[$i]['nome'], ENT_QUOTES, "UTF-8")."\">".$rs[$i]['nome']."</span></td>\n";
			echo "<td><a href=\"".$rootdir."/files/".strtolower($nome_modulo_xml)."/".$rs[$i]['filename']."\" title=\"".htmlentities($rs[$i]['nome'], ENT_QUOTES, "UTF-8")."\" target=\"_blank\">".$rs[$i]['filename']."</a></td>\n";
			echo "<td>".date("d/m/Y H:i", strtotime($rs[$i]['data']) )."</td>\n";
			}

		echo "</table>\n";
	}
	
	if ($showpanel == 1):
	echo "</div>\n";
	endif;
}



/**
  * Funzione per creare la tabella di visualizzazione file e upload nuovo file
  * $nome_modulo	string		Nome del modulo di cui si sta creando il form e la visualizzazione
  * $url_params		string		Parametri da mettere nell'URL oltre a quelli per l'upload (ad esempio "&idintervento=$idintervento"
  *								per evitare che vengano persi dei parametri per il submit del form
  * $externalid		string		Id esterno, per sapere un determinato file di che record fa parte oltre che di che modulo
  */
function filelist_and_upload( $nome_modulo, $externalid, $label='Nuovo allegato:', $showpanel=1 ){
	global $dbo;
	global $docroot;
	global $rootdir;
	global $theme_path;
	global $permessi;
	global $modules_info;

	$dir_ok = true;

	


	/*
		GESTIONE DELETE
	*/
	if( $_GET['op']=='unlink_file' ){
		if( $modules_info[$nome_modulo]["permessi"] == 'rw' ){
			$filename = save($_GET['filename']);
			$rs = $dbo->fetchArray( "SELECT * FROM zz_files WHERE module=\"".$nome_modulo."\" AND id=\"".save($_GET['id'])."\" AND filename=\"".$filename."\"" );

			if( @unlink( $docroot."/files/".strtolower($nome_modulo)."/".$filename ) ){
				$query = "DELETE FROM zz_files WHERE module=\"".$nome_modulo."\"  AND id=\"".save($_GET['id'])."\" AND filename=\"".$filename."\"";
				if( $dbo->query($query) ){
					array_push( $_SESSION['infos'], $rs[0]['nome']." eliminato!" );
					header( "Location: ".$rootdir."/editor.php?id_module=".$modules_info[$nome_modulo]['id']."&id_record=".$externalid );
					exit;
				}
			}

			else{
				array_push( $_SESSION['errors'], "Errore durante l'eliminazione di files/".strtolower($nome_modulo)."/".$filename."!" );
				header( "Location: ".$rootdir."/editor.php?id_module=".$modules_info[$nome_modulo]['id']."&id_record=".$externalid );
				exit;
			}
		}
	}




	//Visualizzo l'elenco di file già caricati
	$rs = $dbo->fetchArray("SELECT * FROM zz_files WHERE module=\"".$nome_modulo."\" AND externalid=\"".$externalid."\"");
	
	
	echo "<a name='attachments'></a>\n";
	
	if ($showpanel == 1):
	echo "<div class=\"panel panel-primary\">\n";
	echo "	<div class=\"panel-heading\">\n";
	echo "		<h3 class=\"panel-title\">"._("Allegati")."</h3>\n";
	echo "	</div>\n";
	
	echo "	<div class=\"panel-body\">\n";

	endif;
	
	if( sizeof($rs)>0 ){
		echo "<table class=\"table table-condensed table-hover table-bordered\" >\n";
		echo "<tr><th>Descrizione</th>\n";
		echo "<th>File</th>\n";
		echo "<th>Data</th>\n";
		echo "<th style=\"width:5%;text-align:center;\" >#</th></tr>\n";

		for( $i=0; $i<sizeof($rs); $i++ ){
			echo "<tr><td align='left'><span title=\"".htmlentities($rs[$i]['nome'], ENT_QUOTES, "UTF-8")."\">".$rs[$i]['nome']."</span></td>\n";
			echo "<td><a href=\"".$rootdir."/files/".strtolower($nome_modulo)."/".$rs[$i]['filename']."\" title=\"".htmlentities($rs[$i]['nome'], ENT_QUOTES, "UTF-8")."\" target=\"_blank\">".$rs[$i]['filename']."</a></td>\n";
			echo "<td>".date("d/m/Y H:i", strtotime($rs[$i]['data']) )."</td>\n";
			echo "<td style=\"text-align:center;\"><a class=\"btn btn-sm btn-danger\" title=\"Elimina questo file...\" onclick=\"if( confirm('Vuoi eliminare questo file?') ){ location.href='".$rootdir."/editor.php?id_module=".$modules_info[$nome_modulo]['id']."&id_record=".$externalid."&op=unlink_file&id=".$rs[$i]['id']."&filename=".$rs[$i]['filename']."'; }\"><i class='fa fa-trash-o'></i></a></td></tr>\n";
		}

		echo "</table>\n";
	}
	
	echo "<br>\n";
	
	

	//Form per l'upload di un nuovo file
	
	
	echo "		<b>".$label."</b>\n";
	echo "			<div class='row'>\n";
	echo "				<div class='col-lg-4'>\n";
	echo "					<input type=\"text\" class=\"form-control\" placeholder=\"Inserisci un nome...\" name=\"nome_allegato\">\n";
	
	echo "					<input type=\"hidden\" class=\"form-control\" name=\"docroot\" value=\"".$docroot."\" >\n";
		
	echo "				</div>\n";
	
	echo "				<div class='col-lg-6'>\n";
	echo "					<input type=\"file\" class=\"inputtext\" id=\"blob\" name=\"blob\"><br><br>\n";
	echo "				</div>\n";
	
	echo "				<div class='col-lg-2 text-right'>\n";
	echo "					<button type='button' class='btn btn-success' id=\"upload_button\"  onclick=\"SaveFile();\" ><i class='fa fa-upload'></i> Carica</button>\n";
	echo "				</div>\n";
	echo "			</div>\n";
	
	
	
	echo "<script>\n";
	

	echo "function SaveFile(){\n";


	echo "if( $('#blob').val()=='' ){ alert('Devi selezionare un file con il tasto Sfoglia...'); return false;}\n";
	
	echo "if( $('input[name=nome_allegato]').val()=='' || $('input[name=nome_allegato]').val()=='Inserisci un nome...' ){\n";
	echo "alert('Devi inserire un nome per il file!'); return false;}\n";
	
	
	echo "var file_data = $('#blob').prop('files')[0];\n";
	
	echo "var form_data = new FormData();\n";
	echo "form_data.append('blob', file_data);\n";
	echo "form_data.append('nome_allegato', $('input[name=nome_allegato]').val() );\n";
	echo "form_data.append('docroot', $('input[name=docroot]').val() );\n";
	echo "form_data.append('op','link_file' );\n";
	echo "form_data.append('id_record','".$externalid."' );\n";
	echo "form_data.append('id_module',".$modules_info[$nome_modulo]['id']." );\n";
	
	echo "$.ajax({\n";
	  echo "url: '".$rootdir."/lib/actions.php', \n";
	  echo "cache: false,\n";
	  echo "type: 'post', \n";
	  echo "processData: false, \n";
	  echo "contentType: false, \n";
	  echo "dataType : 'html', \n";
	  echo "data: form_data, \n";
	  echo "success: function(data) {\n";
            //echo "alert(data)\n";
			echo "location.href = '".$rootdir."/editor.php?id_module=".$modules_info[$nome_modulo]['id']."&id_record=".$externalid."' \n";
      echo "},\n";
      echo "error: function() {\n";
            echo "alert('Error occured'+form_data);\n";
      echo"}\n";
	  
	echo "})\n";
	
	
	echo "};\n";
	echo "</script>\n";
	
	
	
	if ($showpanel == 1):
	echo "	</div>\n";
	echo "</div><br>\n";
	endif;
}



/**
  * Legge i plugins collegati al modulo in oggetto e restituisce un array nella forma:
  * $plugins[ 'nome_modulo' ] = '/path/dello/script/script.php';
*/
function get_plugins( $module, $position ){
	global $plugins;
	global $dbo;
	global $docroot;

	$q = "SELECT * FROM zz_modules_plugins WHERE idmodule_to=( SELECT id FROM zz_modules WHERE name=\"".$module."\" ) AND position=\"".$position."\"";
	$rs = $dbo->fetchArray($q);

	for( $i=0; $i<sizeof($rs); $i++ ){
		//Lettura modulo di origine
		$q2 = "SELECT parent, module_dir FROM zz_modules WHERE id='".$rs[$i]['idmodule_from']."' AND `enabled`=1";
		$rs2 = $dbo->fetchArray($q2);
		$module_dir = $rs2[0]['module_dir'];
		
		//Se c'è un altro livello sopra, devo mettere come prefisso anche quella directory
		if( $rs2[0]['parent'] != '0' ){
			$q3 = "SELECT module_dir FROM zz_modules WHERE id='".$rs2[0]['parent']."' AND `enabled`=1";
			$rs3 = $dbo->fetchArray($q3);
			$module_dir = $rs3[0]['module_dir']."/".$module_dir;
		}
		

		if( sizeof($rs2)>0 ){
			$script = $docroot."/modules/".$module_dir."/plugins/".$rs[$i]['script'];
			$plugins[ $rs[$i]['name'] ] = $script;
		}
	}

	return $plugins;
}
?>
