<?

/*
 * FlatImageGallery
 * Copyright (C) 2004-2007 Marco Segato
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the license, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
 */

/*
 * Blocco per FlatNuke (http://flatnuke.sourceforge.net) di Simone Vellei che
 * permette di creare automaticamente una galleria di immagini a partire da
 * quelle che ci sono nella directory dove e' presente questo file.
 *
 * Autore    Marco Segato  <segatom@users.sourceforge.net>
 * Website   http://marcosegato.altervista.org
 * Versione  0.8
 * Data      06/10/2007
 *
 */


// informazione per log
$zone = "Gallery";

// previene che il blocco sia eseguito direttamente e redirige a index.php
if (eregi("gallery.php",$_SERVER['PHP_SELF'])) {
	Header("Location: ../../index.php");
	die();
}

// configurazione flatnuke
include ("config.php");

// security declarations
$myforum      = getparam("myforum", PAR_COOKIE, SAN_FLAT);
$ip_indirizzo = getparam("REMOTE_ADDR", PAR_SERVER, SAN_NULL);
$mod          = getparam("mod",PAR_GET,SAN_FLAT);
$req          = getparam("REQUEST_URI", PAR_SERVER, SAN_NULL);

// configurazione galleria
$gallerycfgdir = "misc/gallery";										// directory
$galleryconf   = "misc/gallery/".str_replace("/","",$mod).".conf.xml";	// configurazione gallery
$gallerycomm   = "misc/gallery/".str_replace("/","",$mod).".comm.xml";	// commenti a galleria
$galleryfeed   = $gallerycfgdir."/".str_replace("/","_",$mod).".xml";	// rss feed

// colori
global $bgcolor2, $bgcolor3;

// opzione di sicurezza!
if(strstr($req,"myforum="))
	die(_NONPUOI);

// controlla se il web server ha le librerie GD
if(!function_exists("ImageJpeg")) {
	if(is_admin())
		print("<div align='center'>"._FIG_TXT_NOGD."</div><br />");
	$gd_flag = FALSE;
	//return; // se le librerie non sono installate, al posto della miniatura sara' visualizzata l'immagine originale rimpicciolita
} else $gd_flag = TRUE;

// controlla esistenza directory con file di configurazione in /misc, se non c'e' la crea
if(!file_exists($gallerycfgdir)) {
	mkdir($gallerycfgdir, 0777);
}

// controlla esistenza file di configurazione in /misc/gallery, se non c'e' lo crea
if(!file_exists($galleryconf)) {
	fnwrite($galleryconf, "<?xml version='1.0'?>\n<fig:columns>2</fig:columns>\n<fig:rows>3</fig:rows>\n<fig:dim-thumbs>175</fig:dim-thumbs>\n<fig:commenti>N</fig:commenti>\n<fig:reg-uploads>N</fig:reg-uploads>\n", "w+", array("nonull"));
}

// controlla esistenza file commenti in /misc/gallery, se non c'e' lo crea
if(!file_exists($gallerycomm)) {
	fnwrite($gallerycomm, "<?xml version='1.0'?>\n", "w+", array("nonull"));
}

// controlla esistenza feed rss, se non c'e' lo crea
if(!file_exists($galleryfeed)) {
	generate_Gallery_RSS($mod);
}

// azioni in POST da configurazione admin
$action = getparam("action", PAR_POST, SAN_FLAT);
if (($action != "") AND is_admin()) {
	// configurazione numero colonne e righe tabella immagini
	if($action=="numcolsrows") {
		$num_cols=getparam("num_cols", PAR_POST, SAN_FLAT);
		$num_rows=getparam("num_rows", PAR_POST, SAN_FLAT);
		if(($num_cols!="") AND ($num_rows!="") AND is_numeric($num_cols) AND is_numeric($num_rows)) {
			$file_dati = get_file($galleryconf);
			$file_dati = str_replace("<fig:columns>".get_xml_element("fig:columns",$file_dati)."</fig:columns>","<fig:columns>".$num_cols."</fig:columns>",$file_dati);
			$file_dati = str_replace("<fig:rows>".get_xml_element("fig:rows",$file_dati)."</fig:rows>","<fig:rows>".$num_rows."</fig:rows>",$file_dati);
			fnwrite($galleryconf, "$file_dati", "w+", array("nonull"));
			fnlog($zone, "$ip_indirizzo||$myforum||Number of columns and rows saved.");
		}
	}
	// configurazione dimensione thumbs
	elseif($action=="dimthumbs") {
		$hw_thumbs = getparam("hw_thumbs", PAR_POST, SAN_FLAT);
		if($hw_thumbs!="") {
			$file_dati = get_file($galleryconf);
			$file_dati = str_replace("<fig:dim-thumbs>".get_xml_element("fig:dim-thumbs",$file_dati)."</fig:dim-thumbs>","<fig:dim-thumbs>".$hw_thumbs."</fig:dim-thumbs>",$file_dati);
			fnwrite($galleryconf, "$file_dati", "w+", array("nonull"));
			fnlog($zone, "$ip_indirizzo||$myforum||Thumbs dimensions saved.");
		}
	}
	// configurazione commenti
	elseif($action=="confcommenti") {
		$commenti=getparam("commenti", PAR_POST, SAN_FLAT);
		if(($commenti!="") AND (($commenti=="Y") OR ($commenti=="N"))) {
			$file_dati = get_file($galleryconf);
			$file_dati = str_replace("<fig:commenti>".get_xml_element("fig:commenti",$file_dati)."</fig:commenti>","<fig:commenti>".$commenti."</fig:commenti>",$file_dati);
			fnwrite($galleryconf, "$file_dati", "w+", array("nonull"));
			fnlog($zone, "$ip_indirizzo||$myforum||Comments configuration saved.");
		}
	}
	// configurazione upload da utenti registrati
	elseif($action=="upload_by_regusers") {
		$reguploads=getparam("reguploads", PAR_POST, SAN_FLAT);
		if(($reguploads!="") AND (($reguploads=="Y") OR ($reguploads=="N"))) {
			$file_dati = get_file($galleryconf);
			$file_dati = str_replace("<fig:reg-uploads>".get_xml_element("fig:reg-uploads",$file_dati)."</fig:reg-uploads>","<fig:reg-uploads>".$reguploads."</fig:reg-uploads>",$file_dati);
			fnwrite($galleryconf, "$file_dati", "w+", array("nonull"));
			fnlog($zone, "$ip_indirizzo||$myforum||Registered users upload configuration saved.");
		}
	}
	// eliminazione file commenti e creazione di uno vuoto
	elseif($action=="delcomm") {
		unlink($gallerycomm);
		fnwrite($gallerycomm, "<?xml version='1.0'?>\n", "w+", array("nonull"));
		fnlog($zone, "$ip_indirizzo||$myforum||Comments deleted.");
	}
	// upload nuova immagine
	elseif($action=="upload") {
		if(!is_writeable(getparam("path", PAR_POST, SAN_FLAT))) {
			?><script language="javascript">alert('<?=_FIG_ALERTNOTWR?>');</script><?
		}
		// verifico che sia effettivamente un'immagine
		elseif(getimagesize($_FILES['file_up']['tmp_name']))
			fig_upload(getparam("path", PAR_POST, SAN_FLAT));
		else {
			fnlog($zone, "$ip_indirizzo||$myforum||Tried to upload a file that's not an image.");
			?><script language="javascript">alert('<?=_FIG_ALERTNOTIMG?>');</script><?
		}
		fnlog($zone, "$ip_indirizzo||$myforum||New image uploaded.");
		//Genera feed RSS della gallery
		generate_Gallery_RSS($mod);
	}
	// rinomina immagine
	elseif($action=="rename") {
		$rename_from=getparam("rename_from",PAR_POST,SAN_FLAT);
		$rename_to=getparam("rename_to",PAR_POST,SAN_FLAT);
		if($rename_from=="") {
			// nessuna scelta effettuata, non faccio nulla :)
		}
		elseif(eregi("(jpg|jpeg|png|gif)",get_file_extension($rename_to))) {
			if(rename($rename_from, getparam("path", PAR_POST,SAN_FLAT)."/".$rename_to)) {
				fnlog($zone, "$ip_indirizzo||$myforum||Image renamed.");
				?><script language="javascript">alert('<?=_FIG_RENAMEOK?>');</script><?
			        //Genera feed RSS della gallery
			        generate_Gallery_RSS($mod);
			} else {
				?><script language="javascript">alert('<?=_FIG_RENAMENO?>');</script><?
			}
		} else {
			fnlog($zone, "$ip_indirizzo||$myforum||Tried to rename the image $rename_from as $rename_to.");
			?><script language="javascript">alert('<?=_FIG_RENAMENO?>');</script><?
		}
	}
	// eliminazione immagine
	elseif($action=="delete") {
		$file_del=getparam("file_del",PAR_POST,SAN_FLAT);
		if($file_del=="" OR !eregi("(jpg|jpeg|png|gif)",get_file_extension($file_del))) {
			// nessuna scelta effettuata o non e' immagine, non faccio nulla :)
		} elseif(unlink($file_del)) {
			?><script language="javascript">alert('<?=_FIG_ALERTIMGDEL?>');</script><?
		} else {
			?><script language="javascript">alert('<?=_FIG_ALERTNOTWR?>');</script><?
		}
		fnlog($zone, "$ip_indirizzo||$myforum||Image deleted.");
		//Genera feed RSS della gallery
		generate_Gallery_RSS($mod);
	}
}

// upload nuova immagine da parte di un utente registrato
$path=getparam("path", PAR_POST,SAN_FLAT);

if($action=="regupload") {
	if(!is_writeable($path)) {
		?><script language="javascript">alert('<?=_FIG_ALERTNOTWR?>');</script><?
	}
	// verifico che sia effettivamente un'immagine
	elseif(getimagesize($_FILES['file_up']['tmp_name']))
		fig_upload($_POST['path']);
	else {
		?><script language="javascript">alert('<?=_FIG_ALERTNOTIMG?>');</script><?
	}
	fnlog($zone, "$ip_indirizzo||$myforum||New image uploaded by $myforum.");
	//Genera feed RSS della gallery
	generate_Gallery_RSS($mod);
}
// azioni in POST per salvataggio commenti
elseif(isset($_POST['writecomm'])) {
	if(isset($_POST['by'])) $by = stripslashes(htmlspecialchars($_POST['by']));
		else $by = "";
	if(isset($_POST['body'])) $what = htmlspecialchars($_POST['body']);
		else $what = "";
	$what = str_replace("\r","",$what);
	$what = str_replace("\n","<br />",$what);
	$string = get_file($gallerycomm);

	// si tratta del primo commento inserito
	if(!stristr($string, "<fig:comments>"))
		$string = "<?xml version='1.0'?>\n<fig:comments>\n\t<fig:comment>\n\t\t<fig:by>$by</fig:by>\n\t\t<fig:what>$what</fig:what>\n\t</fig:comment>\n</fig:comments>\n";
	// c'e' almeno un commento gia' inserito
	else $string = str_replace("</fig:comments>", "\t<fig:comment>\n\t\t<fig:by>$by</fig:by>\n\t\t<fig:what>$what</fig:what>\n\t</fig:comment>\n</fig:comments>",$string);

	fnwrite($gallerycomm, stripslashes("$string"), "w", array("nonull"));
	fnlog($zone, "$ip_indirizzo||$myforum||New comment.");

	echo "<script language=\"javascript\">window.location='index.php?mod=$mod';</script>";
}

// directory dove sono presenti le immagini
$path = "sections/$mod";
// carico tutti i files immagine in un array
$dir = opendir($path);
$n_file = 0;
while ($filename = readdir($dir)) {
	if(@getimagesize($path."/".$filename)!=FALSE AND !stristr($filename,"none_")) {
		$array_dir[$n_file] = $filename;
		$n_file++;
	}
}
closedir($dir);
// ordinamento alfabetico dell'array
if($n_file!=0) {
	natcasesort($array_dir);
	$array_dir = array_values($array_dir);
}

// visualizzazione maschera per inserimento commenti
if (getparam("inscomm", PAR_GET, SAN_FLAT) !="") {
	OpenTableTitle(_FIG_ADDCOMM);
	if($myforum!="" OR $guestcomment==1) {			// controllo se utente non registrato puo' postare o no
		if($myforum=="")
			$by = _FIG_SCON;					// utente sconosciuto
		else $by = $myforum;				// utente registrato
		echo "<form action=\"index.php?mod=$mod\" method=\"post\">
			<input type=\"hidden\" name=\"writecomm\" />
			<input type=\"hidden\" name=\"by\" value=\"$by\" /><br />
			<strong>"._FIG_COMMENTI."</strong><br />
			<textarea rows=\"7\" name=\"body\" style=\"width:95%;\"></textarea><br /><br />
			<input type=\"submit\" value=\""._FIG_FINVIA."\" />
		</form><br />";
	} else echo _FIG_DEVIREG." <strong>".$sitename."</strong> "._FIG_DEVIREG2; // utenti non registrati non possono postare
	CloseTableTitle();
	echo "<br />";
}

// carico la configurazione della galleria in variabili
$file_xml = get_file($galleryconf);
$cols = get_xml_element("fig:columns",$file_xml);		// numero di colonne tabella immagini (2 di default)
if($cols=="")
	$cols = 2;
$rows = get_xml_element("fig:rows",$file_xml);			// numero di righe tabella immagini (3 di default)
if($rows=="")
	$rows = 3;
$hw_thumbs = get_xml_element("fig:dim-thumbs",$file_xml);	// dimensioni thumbnails (175 di default)
if($hw_thumbs=="")
	$hw_thumbs = 175;
$commenti =  get_xml_element("fig:commenti",$file_xml);		// abilitazione commenti (abilitati di default)
if($commenti=="")
	$commenti = "Y";
$reguploads =  get_xml_element("fig:reg-uploads",$file_xml);	// abilitazione uploads da utenti registrati (disabilitati di default)
if($reguploads=="")
	$reguploads = "N";

// menu_admin - gestione galleria
if(is_admin()) {
	?><center>
	<input type="button" value="<?=_CONFIG?>" onclick="ShowHideDiv('confgalleryadmin');" />
	</center><br />
	<div id="confgalleryadmin" style="display:none"><?
	OpenTableTitle(_FIG_ADMIN_SECT);
	?><table cellspacing="5"><tbody>
	<!-- configurazione numero colonne e righe tabella immagini -->
	<tr><td><form action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="numcolsrows" readonly="true" />
	<?=_FIG_TXT_NUMCOLSROWS._FIG_TXT_NUMCOLS?><input type="text" name="num_cols" size="3" maxlength="3" value="<?=$cols?>" />
	<?=_FIG_TXT_NUMROWS?><input type="text" name="num_rows" size="3" maxlength="3" value="<?=$rows?>" />
	</td><td><?if(is_writeable($galleryconf)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	<!-- configurazione dimensione thumbs -->
	<tr><td><form action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="dimthumbs" readonly="true" />
	<?=_FIG_TXT_DIMTHUMBS?><input type="text" name="hw_thumbs" size="8" maxlength="3" value="<?=$hw_thumbs?>" />
	</td><td><?if(is_writeable($galleryconf)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	<!-- configurazione abilitazione uploads da utenti registrati -->
	<tr><td><form action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="upload_by_regusers" readonly="true" />
	<?=_FIG_TXT_REGUPLOADS?>
	<select name="reguploads">
		<option value="<?=$reguploads?>"><?=$reguploads?></option><?
		if($reguploads=="N")
			echo "<option value=\"Y\">Y</option>";
		else echo "<option value=\"N\">N</option>";
	?></select>
	</td><td><?if(is_writeable($galleryconf) AND is_writeable($gallerycomm)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	<!-- configurazione abilitazione commenti a galleria -->
	<tr><td><form action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="confcommenti" readonly="true" />
	<?=_FIG_TXT_COMMENTI?>
	<select name="commenti">
		<option value="<?=$commenti?>"><?=$commenti?></option><?
		if($commenti=="N")
			echo "<option value=\"Y\">Y</option>";
		else echo "<option value=\"N\">N</option>";
	?></select>
	</td><td><?if(is_writeable($galleryconf) AND is_writeable($gallerycomm)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	<!-- eliminazione commenti alla galleria -->
	<tr><td><form action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="delcomm" readonly="true" />
	<?=_FIG_TXT_DELCOMM?>
	</td><td><?if(is_writeable($gallerycfgdir)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	<!-- upload nuova immagine -->
	<tr><td><form enctype="multipart/form-data" action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="upload" readonly="true" />
	<input type="hidden" name="path" value="sections/<?=$mod?>" readonly="true" />
	<?=_FIG_TXT_UPLOAD?><input name="file_up" type="file" />
	</td><td><?if(is_writeable($path)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	<!-- rinomina immagine -->
	<tr><td><form action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="rename" readonly="true" />
	<input type="hidden" name="path" value="sections/<?=$mod?>" readonly="true" />
	<?=_FIG_TXT_RENAME?><select name="rename_from">
		<option></option><?
		for($i=0;$i<count($array_dir);$i++)
  			echo "<option value=\"$path/".$array_dir[$i]."\">".$array_dir[$i]."</option>";
	?></select>&nbsp;
	<input type="text" name="rename_to" size="20" maxlength="50" />
	</td><td><?if(is_writeable($path)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	<!-- eliminazione immagine caricata -->
	<tr><td><form action="index.php?mod=<?=$mod?>" method="post">
	<input type="hidden" name="action" value="delete" readonly="true" />
	<?=_FIG_TXT_DELETE?><select name="file_del">
		<option></option><?
		for($i=0;$i<count($array_dir);$i++)
  			echo "<option value=\"$path/".$array_dir[$i]."\">".$array_dir[$i]."</option>";
	?></select>
	</td><td><?if(is_writeable($path)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
	</form></td></tr>
	</tbody></table><?
	CloseTableTitle();
	?></div><?
}

// se non sono presenti immagini nella sezione, restituisce avviso e salta stampa galleria
if($n_file == 0) {
	echo "<div align='center'>"._FIG_TXT_NOIMAGES."</div>";
	// upload nuova immagine se funzione e' abilitata per utenti registrati
	if($reguploads=="Y" AND ($myforum) AND versecid($myforum)) {
		OpenTable();
		?><form enctype="multipart/form-data" action="index.php?mod=<?=$mod?>" method="post">
		<input type="hidden" name="action" value="regupload" readonly="true" />
		<input type="hidden" name="path" value="sections/<?=$mod?>" readonly="true" />
		<?=_FIG_TXT_UPLOAD?><input name="file_up" type="file" />
		<?if(is_writeable($path)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
		</form><?
		CloseTable();
	}
	echo "<br />";
} else {
// INIZIO PROCEDURA STAMPA GALLERIA

$pag = getparam("pag",PAR_GET,SAN_FLAT);
if( !is_numeric($pag) OR $pag<1 OR $pag>($n_file/($rows*$cols)+1) ) {
	$pag = 1;
}
// stampa menu_top select per cambio pagina
menu_change_page("toppage", $n_file, $rows, $cols, $pag);
	
?><table align="center" width="100%" cellspacing="2" cellpadding="5" bgcolor="<?=$bgcolor2?>"><tbody><?
	if($pag!="")				// determina qual e' la prima foto della pagina
		$max_x_pag = ($pag * ($rows * $cols)) - ($rows * $cols - 1);
	else $max_x_pag = 1;

	for ($i=$max_x_pag; $i<$max_x_pag+($rows * $cols) and $i<=$n_file; $i++) {
		if($i%$cols == 1)				// apertura nuova riga
			echo "<tr bgcolor=\"$bgcolor3\">";
		$nomefile = $array_dir[$i-1];
		$nomefile = eregi_replace("^[0-9]*_","",$nomefile); 	// elimina i numeri iniziali
		$nomefile = eregi_replace("_"," ",$nomefile); 			// converte _ in spazi
		$nomefile = eregi_replace("[\.]*[a-z0-9]{1,4}$","",$nomefile); 	// elimina l'estensione
		$size = getimagesize($path."/".$array_dir[$i-1]);
		?><td valign="bottom" width="<?=intval(100/$cols)?>%" height="<?=intval(100/$rows)?>%">	<!-- stampa casella con immagine -->
		  <div align="center">
		  <a rel="lightbox" href="<?=$path."/".$array_dir[$i-1]?>" title="<?=$nomefile?>"><?
			// se dimensioni < di quelle scelte, stampo immagine, altrimenti creo thumbnail
			if($size[0]<$hw_thumbs AND $size[1]<$hw_thumbs) {
				?><img border="1" src="<?="$path/".$array_dir[$i-1]?>" alt="thumb" />
				</a><?
			}
			elseif($gd_flag==FALSE) {
				if($size[0]>$size[1]) {
					$new_w = $hw_thumbs;
					$new_h = $hw_thumbs * $size[1] / $size[0];
				} else {
					$new_w = $hw_thumbs * $size[0] / $size[1];
					$new_h = $hw_thumbs;
				}
				?><img border="1" src="<?=$path."/".$array_dir[$i-1]?>" height="<?=$new_h?>" width="<?=$new_w?>" alt="thumb" />
				</a><?
			}
			else { 
				?><img border="1" src="gallery/thumb.php?image=<?=$path."/".$array_dir[$i-1]?>&amp;hw=<?=$hw_thumbs?>" alt="thumb" />
				</a><?
			}
		  ?></div>
		  <div align="center"><b><?
			//echo $array_dir[$i-1];	// visualizza il nome completo del file
			echo $nomefile;			// visualizza il nome del file elaborandolo perche' compaia come descrizione
		  ?></b></div>
		  <div align="center"><?=round(filesize($path."/".$array_dir[$i-1]) / 1024, 1)." Kb - ".$size[0]."x".$size[1]." px"?></div>
		</td><?
		if($i%$cols == 0)				// chiusura della riga
			echo "</tr>";
	}
	while (($i-1)%$cols != 0) {				// stampa casella vuota per terminare correttamente la riga
		echo "<td width=\"".(intval(100/$cols))."%\" height=\"".(intval(100/$rows))."%\"></td>";
		$i++;
	}
?></tbody></table><?

// stampa menu_bottom select per cambio pagina
menu_change_page("bottompage", $n_file, $rows, $cols, $pag);

?><div align="center"><?
	// upload nuova immagine se funzione e' abilitata per utenti registrati
	$myforum=getparam("myforum", PAR_COOKIE, SAN_FLAT);
	if($reguploads=="Y" AND ($myforum) AND versecid($myforum)) {
		OpenTable();
		?><form enctype="multipart/form-data" action="index.php?mod=<?=$mod?>" method="post">
		<input type="hidden" name="action" value="regupload" readonly="true" />
		<input type="hidden" name="path" value="sections/<?=$mod?>" readonly="true" />
		<?=_FIG_TXT_UPLOAD?><input name="file_up" type="file" />
		<?if(is_writeable($path)) echo "<input type=\"SUBMIT\" value=\"OK\" />"; else echo "<font color=\"red\">"._FIG_ALERTNOTWR."</font>";?>
		</form><?
		CloseTable();
	}
	//Stampa il bottone per il feed RSS della gallery
	?><div style="text-align:right;margin:5px 0 5px 0;">
		<a href="<?=$galleryfeed?>" target="_blank" title="<?=_BACKEND?>"><img border="0" src="images/rss.png" alt="<?=_BACKEND?>" height="32" width="32"/></a>
	</div><?
	// menu inserimento commenti (se abilitati) + stampa commenti
	if($commenti=="Y") {
		OpenTable();
		echo "<b>"._FIG_COMMENTI."</b> | <a href=\"index.php?mod=$mod&amp;inscomm=1\" title=\""._FIG_ADDCOMM."\">"._FIG_ADDCOMM."</a>";
		CloseTable();
		$file_xml = get_file($gallerycomm);
		$comments = get_xml_element("fig:comments",$file_xml);
		$comment = get_xml_array("fig:comment",$comments);
		for($n=0; $n<count($comment); $n++)	{			// stampa commenti a sondaggio
			$user = get_xml_element("fig:by",$comment[$n]);
			print "<div class='comment' style='min-height:105px;'>";
			if($user == _FIG_SCON)
				echo "<strong>"._FIG_DA."</strong> "._FIG_SCON;
			else { 
				// inserisco l'avatar nei commenti
				if(file_exists(get_fn_dir("users")."/$user.php")) {
					$userdata = array();
					$userdata = load_user_profile($user);
					$img = $userdata['avatar'];
					if($img!="") {
						if(!stristr($img,"http://"))
							echo "<img src='forum/".$img."' alt='avatar' border='0' align='left' hspace='10' vspace='5' style='max-width:100px' />";
						else
							echo "<img src='".$img."' alt='avatar' border='0' align='left' hspace='10' vspace='5' style='max-width:100px' />";
					} else
						echo "<img src='forum/images/blank.png' alt='avatar' border='0' align='left' hspace='10' vspace='5' style='max-width:100px' />";
				} else echo "<img src='forum/images/blank.png' alt='avatar' border='0' align='left' hspace='10' vspace='5' style='max-width:100px' />";
				// fine avatar
				print "<b>"._FIG_DA."</b> $user";
			}
			echo "<br /><br />".get_xml_element("fig:what",$comment[$n]);
			print "</div>";
			echo "<br />";
		}
	}
?></div><?

} // FINE PROCEDURA STAMPA GALLERIA


/*
 * Stampa menu per cambio pagina
 */
function menu_change_page($position, $n_file=0, $rows=0, $cols=0, $pag=0) {
	$position = getparam($position, PAR_NULL, SAN_FLAT);
	$mod      = getparam("mod", PAR_GET, SAN_FLAT);
	if($n_file > ($rows * $cols)) {
		?><div align="center" style="margin:1em 0 1em 0">
		<form name="<?=$position?>" action="">
		<span class="change_page" style="font-size:150%"><?
		echo $start_left = ($pag > 1) ? ("<a href=\"index.php?mod=$mod&amp;pag=1\" title=\""._FIG_TXT_PAGINA." 1\">&#171;</a>") : ("&#171;");
		echo "&nbsp;&nbsp;";
		echo $arrow_left = ($pag > 1) ? ("<a href=\"index.php?mod=$mod&amp;pag=".($pag-1)."\" title=\""._FIG_TXT_PAGINA." ".($pag-1)."\">&#8249;</a>") : ("&#8249;");
		?>&nbsp;&nbsp;</span>
		<select name="select_<?=$position?>" onchange="self.location=document.<?=$position?>.select_<?=$position?>[document.<?=$position?>.select_<?=$position?>.selectedIndex].value"><?
			for($i=0;$i<$n_file/($rows*$cols);$i++) {
				if($pag == "")
					echo "<option value=\"index.php?mod=$mod&amp;pag=".($i+1)."\">".($i+1)."</option>";
				else if($pag == $i+1)
						echo "<option value=\"index.php?mod=$mod&amp;pag=".($i+1)."\" selected='selected'>".($i+1)."</option>";
					else echo "<option value=\"index.php?mod=$mod&amp;pag=".($i+1)."\">".($i+1)."</option>";
			}
		?></select>
		<span class="change_page" style="font-size:150%">&nbsp;&nbsp;<?
		$last_pag = (is_int($n_file/($rows*$cols))) ? ($n_file/($rows*$cols)) : (intval($n_file/($rows*$cols))+1);
		echo $arrow_right = ($pag < $last_pag) ? ("<a href=\"index.php?mod=$mod&amp;pag=".($pag+1)."\" title=\""._FIG_TXT_PAGINA." ".($pag+1)."\">&#8250;</a>") : ("&#8250;");
		echo "&nbsp;&nbsp;";
		echo $end_right = ($pag < $last_pag) ? ("<a href=\"index.php?mod=$mod&amp;pag=$last_pag\" title=\""._FIG_TXT_PAGINA." $last_pag\">&#187;</a>") : ("&#187;");
		?></span></form>
		</div><?
	}
}

/*
 * Mette on-line il file selezionato
 */
function fig_upload($path) {
	$path=getparam($path,PAR_NULL, SAN_FLAT);
	switch($_POST['action']) {
		case("upload"):
			if(is_admin()) {
				if($_FILES['file_up']['name']<>"" AND eregi("(jpg|jpeg|png|gif)",get_file_extension($_FILES['file_up']['name']))) {
					//controllo che il file non sia gia' esistente
					if(file_exists("$path/".$_FILES['file_up']['name'])) {
						?><script language="javascript">alert('<?=_FIG_ALERTEXIST?>');</script><?
						return;
					}
					//upload del file
					if(move_uploaded_file($_FILES['file_up']['tmp_name'], "$path/".$_FILES['file_up']['name'])) {
						?><script language="javascript">alert('<?=_FIG_ALERTUPOK?>');</script><?
					}
					//se non riesce restituisci avviso sui permessi di scrittura
					else {
						?><script language="javascript">alert('<?=_FIG_ALERTNOTWR?>');</script><?
					}
				}
			}
		break;
		case("regupload"):
			$myforum=getparam("myforum", PAR_COOKIE, SAN_FLAT);
			if(($myforum!="") AND versecid($myforum)) {
				if($_FILES['file_up']['name']<>"" AND eregi("(jpg|jpeg|png|gif)",get_file_extension($_FILES['file_up']['name']))) {
					$new_file = explode(".",basename($_FILES['file_up']['name']));
					$n = count($new_file) - 1;
					//controllo che il file non sia gia' esistente
					if(file_exists("$path/$new_file[0]_by_$myforum.$new_file[$n]")) {
						?><script language="javascript">alert('<?=_FIG_ALERTEXIST?>');</script><?
						return;
					}
					//upload del file
					if(move_uploaded_file($_FILES['file_up']['tmp_name'], "$path/$new_file[0]_by_$myforum.$new_file[$n]")) {
						?><script language="javascript">alert('<?=_FIG_ALERTUPOK?>');</script><?
					}
					//se non riesce restituisci avviso sui permessi di scrittura
					else {
						?><script language="javascript">alert('<?=_FIG_ALERTNOTWR?>');</script><?
					}
				}
			} else $myforum = "";
		break;
	}
}

/**
 * Genera il feed RSS della gallery
 *
 * Genera il file <i>/misc/gallery.xml</i> che contiene le immagini presenti nella gallery; il file XML 
 * e' strutturato per essere letto con un normale aggregator RSS, ed e' compatibile 
 * con le {@link http://feedvalidator.org/docs/rss2.html specifiche RSS 2.0}.
 *
 * @param string $sectionName Nome della sezione contenente la Gallery di cui si vuole generare il feed RSS
 *
 * @author Michele Tartara <mikyt@users.sourceforge.net>
 */
function generate_Gallery_RSS($sectionName) {
	global $sitename, $admin_mail;
	$gallery_dir = 'sections/'.$sectionName;
	
	$url = "http://".getparam("HTTP_HOST", PAR_SERVER, SAN_FLAT).getparam("PHP_SELF", PAR_SERVER, SAN_FLAT);
	$url = str_replace(basename($url),"",$url);
	$gallery_url = $url."index.php?mod=".$sectionName;

	// tag apertura del feed
	$body = "<?xml version=\"1.0\" encoding=\""._CHARSET."\"?>\n<rss version=\"2.0\">\n\t<channel>\n";
	// informazioni generali sul feed
	$body .= "\t\t<title>$sitename - Gallery</title>\n\t\t<link>$gallery_url</link>\n\t\t<description><![CDATA[\"$sitename\" $sectionName]]></description>\n";
	$body .= "\t\t<managingEditor>$admin_mail</managingEditor>\n\t\t<generator>FlatNuke RSS Generator - http://www.flatnuke.org</generator>\n";
	$body .= "\t\t<lastBuildDate>".date("D, d M Y H:i:s",time())." GMT</lastBuildDate>\n";
	// carico array con le news ordinate per data
	$handle = opendir($gallery_dir);
	$modlist = array();
	$count = 0;
	while ($file = readdir($handle)) {
		if (eregi("jpg$|jpeg$|png$|gif$", get_file_extension($file))) {
			$modlist[$count]['name'] = $file;
			$modlist[$count]['time'] = filemtime($gallery_dir."/".$file);
			$count++;
		}
	}
	closedir($handle);
	if(count($modlist)>0) {	// time descending order
		usort($modlist, create_function('$a, $b', "return strnatcasecmp(\$a['time'], \$b['time']);"));
		$modlist = array_reverse($modlist, FALSE);
	}
	// creazione tag per ognuna delle news
	for ($i=0; $i < count($modlist); $i++) {
		$filename = $gallery_dir."/".rawurlencode($modlist[$i]['name']);
		$link = $url.$filename;
		$mytitle = $modlist[$i]['name'];
		$mytitle = eregi_replace("^[0-9]*_","",$mytitle); 	// elimina i numeri iniziali
		$mytitle = eregi_replace("_"," ",$mytitle); 			// converte _ in spazi
		$mytitle = eregi_replace("[\.]*[a-z0-9]{1,4}$","",$mytitle); 	// elimina l'estensione
		$body .= "\t\t<item>\n";
		$body .= "\t\t\t<title>$mytitle</title>\n";
		$body .= "\t\t\t<link>$link</link>\n";
		$body .= "\t\t\t<description><![CDATA[<img src=\"$link\" alt=\"$mytitle\"/>]]></description>\n";
		$body .= "\t\t\t<guid isPermaLink=\"true\">$link</guid>\n";
		$body .= "\t\t\t<pubDate>".date("D, d M Y H:i:s", filemtime(str_replace("%20"," ",$filename)))." GMT</pubDate>\n";
		$body .= "\t\t</item>\n";
	}
	// tag chiusura del feed
	$body.="\t</channel>\n</rss>";
	// scrittura del feed
	fnwrite("misc/gallery/".str_replace("/","_",$sectionName).".xml", $body, "w", array("nonull"));
}

?>
