<?

/**
 * File delle funzioni di sistema
 *
 * Questo file contiene le procedure di sistema necessarie al funzionamento di FlatNuke.
 *
 * @package Funzioni_di_sistema
 * Prova {@tutorial Funzioni_di_sistema/docapi.pkg}
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License
 */


/**
 * Contiene funzioni condivise tra il forum e il core di FlatNuke
 */
include_once("shared.php");


/**
 * Incrementa il contatore delle visite di una news
 *
 * Incrementa di una unita' il contatore delle visite di una news.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $news Nome assoluto del file della news da elaborare
 */
function add_read($news){

	//se sono amministratore non incremento
	if (is_admin()) return;

	$news = getparam($news,PAR_NULL,SAN_FLAT);
	$lockfile = "news/$news.xml";
	// check file existance
	if(!file_exists($lockfile)) {
		OpenTable();
		print("<div align='center'><b>"._NORESULT."</b></div>");
		CloseTable();
		return;
	}
	$sem = lock($lockfile);
	$string = get_file($lockfile);
	$reads = get_xml_element("fn:reads",$string);
	//solo se non sono amministratore
	$reads += 1;
	$string = ereg_replace("<fn:reads>.*</fn:reads>","<fn:reads>$reads</fn:reads>",$string);
	fnwrite($lockfile, $string, "w", array("nonull"));
	unlock($sem);
}


/**
 * Visualizza il dettaglio di una news
 *
 * Stampa a video il dettaglio di una news compreso di titolo, intestazione,
 * corpo e commenti.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $news Nome assoluto del file della news da visualizzare
 */
function read_news($news){
	global $theme, $mesi, $giorni, $fuso_orario, $newspp;
	$news    = getparam($news,     PAR_NULL,   SAN_FLAT);
	// check if the news really exists
	if(!file_exists("news/$news.xml")) {
		print("<div align='center'><b>"._NORESULT."</b></div>");
		return;
	}
	// add 1 visit to the news (if you aren't admin)
	add_read($news);
	// read news contents
	$fd       = get_file("news/$news.xml");
	$title    = get_xml_element("fn:title",$fd);
	$avatar   = get_xml_element("fn:avatar",$fd);
	$header   = get_xml_element("fn:header",$fd);
	$body     = get_xml_element("fn:body",$fd);
	$comments = get_xml_element("fn:comments",$fd);
	$comment  = get_xml_array("fn:comment",$comments);
	// print news
	if(defined('_THEME_VER')) {
		if(_THEME_VER > 0)
			OpenTableTitle($title);
	} else OpenTableTitle("<img src='themes/$theme/images/read.png' alt='Read' />&nbsp;".$title);
	// topic
	$w3c_title = _ARGOMENTO.": ".eregi_replace("\.png$|\.gif$|\.jpeg$|\.jpg$","",$avatar);
	echo "<a href='index.php?mod=none_Search&amp;where=news&amp;find=$avatar'>";
	echo "<img src='images/news/$avatar' align='right' border='0' alt='$avatar' title='$w3c_title' /></a>";
	print stripslashes($header)."<br /><br />".stripslashes($body);
	// footer
	echo "<div class='footnews'>\n";
	$news_link = get_news_link_array($news);
	echo $news_link['news_infos']."<br />";
	echo $news_link['link_comment']." ";
	echo $news_link['link_print']." ";
	if (is_admin()) echo $news_link['link_modify']." ";
	if (is_admin()) echo $news_link['link_delete']." ";
	echo "</div>\n";
	// comments
	for($j=0;$j<count($comment);$j++){
		print "<br />";
		$user=get_xml_element("fn:by",$comment[$j]);
		print "<div class='comment' style='min-height:105px;'>";
		// avatar into the comment
		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' />";
		// comment author
		print "<b>"._DA."</b> $user  ";
		// comment time
		$date_comment = get_xml_element("fn:date",$comment[$j]);
		if(is_numeric($date_comment)){
			print "<b>"._DATA.":</b> ";
			echo $giorni[date("w",$date_comment+(3600*$fuso_orario))].date(" d ",$date_comment+(3600*$fuso_orario));
			$tmp_c = date("m",$date_comment+(3600*$fuso_orario));
			if ($tmp_c<10)
				$tmp_c = str_replace("0","",$tmp_c);
			print $mesi[$tmp_c-1];
			$date_comment = date(" Y - ",$date_comment+(3600*$fuso_orario)).date("H:",$date_comment+(3600*$fuso_orario)).date("i",$date_comment+(3600*$fuso_orario));
		}
		else $date_comment = "/";
		print "$date_comment<br /><br />";
		// comment
		print stripslashes(get_xml_element("fn:post",$comment[$j]));
		// link to delete the current comment
		if(is_admin()) {
			echo "<div style='margin-top:0.5em;text-align:right;'>";
			echo "<img src='themes/$theme/images/delete.png' alt='Delete comment' /> ";
			$delcomment_param = "&amp;file=news/$news.xml&amp;comment_date=".get_xml_element("fn:date",$comment[$j]);
			echo "<a href='#' onclick=\"check('verify.php?mod=delcomment".$delcomment_param."')\" title='"._ELIMINA."'>"._ELIMINA."</a>";
			echo "</div>";
		}
		print "</div>";
	}
	echo "<br /><hr noshade='noshade' size='1' />";
	// search previous and next news
	$array_news = array();
	$handle = opendir("news");
	while ($file = readdir($handle)) {
		if (!( $file=="." OR $file==".." ) AND eregi("xml$",get_file_extension($file))) {
			array_push($array_news, $file);
		}
	}
	closedir($handle);
	if(count($array_news)>0)
		sort($array_news);
	while ($cur_news = current($array_news)) {
		if ($cur_news == "$news.xml") {
			$current = current($array_news);
			$key = key($array_news);
			if($key-1 < 0)
				$prev = _NOPREVNEWS;
			else $prev = "<a href='index.php?mod=read&amp;id=".str_replace(".xml","",$array_news[$key-1])."'>&#171; "._PREVNEWS."</a>";
			if($key+1 > count($array_news)-1)
				$next = _NONEXTNEWS;
			else $next = "<a href='index.php?mod=read&amp;id=".str_replace(".xml","",$array_news[$key+1])."'>"._NEXTNEWS." &#187;</a>";
			echo "<div align='center'>$prev | $next</div>";
		}
		next($array_news);
	}
	// list of last news about the same topic
	echo "<hr noshade='noshade' size='1' /><b>"._RELATEDNEWSLAST."</b><br /><br />";
	argument_search("news", $avatar, $newspp);
	// link to read all the news for the same topic
	echo "<hr noshade='noshade' size='1' />";
	echo "<b>"._RELATEDNEWSALL."</b><center><div style='margin:1em'>";
	echo "<a href='index.php?mod=none_Search&amp;where=news&amp;find=$avatar'>";
	echo "<img src='images/news/$avatar' border='0' alt='$avatar' title='$w3c_title' /></a>";
	echo "</div></center>";

	CloseTableTitle();
}


/**
 * Ricerca una determinata stringa all'interno delle news o dei topics del forum
 *
 * Esegue una ricerca di una stringa all'interno dei files presenti nella directory
 * delle news o dei topics del forum, stampandone un elenco
 *
 * @author Marco Segato <segatom@users.sourceforge.net>
 * @since 2.5.7
 *
 * @param string $where Sezione di ricerca, 'news' oppure 'forum/topics'
 * @param string $find Stringa da ricercare
 * @param number $max_news Indica il numero massimo di news da stampare; se 0 le stampa tutte
 */
function argument_search($where, $find, $max_news=0) {
	global $theme;

	$where=getparam($where,PAR_NULL, SAN_FLAT);
	$find=getparam($find,PAR_NULL, SAN_FLAT);

	if($where=="")
		$find="";
	$haveresult = 0;
	$num_news = 0;
	if((trim($find)!="") and file_exists($where)) {
		$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
		//fnlog("Search", $addr."||".get_username()."||Search done in $where about \"$find\"."); // too verbose, produces too big logs
		$modlist = array();
		$handle = opendir($where);
		while ($file = readdir($handle)) {
			if (!( $file=="." OR $file==".." ) AND eregi("xml$",get_file_extension($file))) {
				array_push($modlist, $file);
			}
		}
		closedir($handle);
		if(count($modlist)>0)
			rsort($modlist);
		// se num. massimo di news da stampare ($max_news) e' 0, le stampo tutte
		if($max_news==0)
			$max_news = count($modlist);
		// stampa la lista delle ultime news con stesso argomento
		for ($i=0; $i<count($modlist) AND $num_news<$max_news; $i++) {
			$string = get_file($where.'/'.$modlist[$i]);
			$found = 0;
			if(stristr($string, $find)) {
				$found = 1;
				$haveresult = 1;
				$num_news++;
			}
			if($found==1) {
				if($where=="news") {
					$title = get_xml_element("fn:title", $string);
					if($title=="")
						$title = _LEGGITUTTO;
					$reads = get_xml_element("fn:reads", $string);
					$id = str_replace(".xml", "", $modlist[$i]);
					echo "<img src='themes/$theme/images/read.png' alt='Read' />&nbsp;<a href=\"index.php?mod=read&amp;id=$id\">$title</a> ";
					echo "(".date("d/m/Y - H:i", $id).") "._LETTO."$reads "._VOLTE."<br />";
				}
				if($where=="forum/topics") {
					$title = get_xml_element("ff:topic", $string);
					if($title=="")
						$title = _LEGGITUTTO;
					$id = str_replace(".xml", "", $modlist[$i]);
					echo "<img src='themes/$theme/images/read.png' alt='Read'>&nbsp;<a href=\"forum/index.php?op=topic&quale=$id\" />$title</a> ";
					echo "(".date("d/m/Y - H:i", $id).")<br />";
				}
			}
		}
		if($haveresult==0) {
			echo _NORESULT."<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		}
	}
	else {
		?><div align="center">
		<form action="index.php" method="get">
		<input type="hidden" name="mod" value="none_Search" />
		<?=_CERCASTR?><br /><br />
		<input type="radio" name="where" value="news" />News
		<input type="radio" name="where" value="forum/topics" />Forum<br />
		<input type="text" name="find" size="14" /><br /><br />
		<input type="submit" value="<?=_CERCA?>" />
		</form>
		</div><?
	}
}


/**
 * Conta i commenti associati ad una news
 *
 * Calcola il numero di commenti inseriti per una news e lo restituisce.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $news Nome assoluto del file della news da elaborare
 * @return number Numero dei commenti
 */
function count_comment($news){

	$news=getparam($news,PAR_NULL,SAN_FLAT);
	$com=0;
	$fd=file("news/$news.xml");
	for($j=1; $j<count($fd);$j++){
		if(stristr($fd[$j],"<fn:comment>"))
			$com+=1;
	}
	return $com;
}


/**
 * Visualizza una sezione
 *
 * Visualizza il contenuto della sezione passata come parametro.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $section Nome assoluto della sezione da visualizzare
 */
function view_section($section){

	if (file_exists("include/redefine/view_section.php")){
		include("include/redefine/view_section.php");
		return;
	}

	global $theme;

	// security checks
	$section = getparam($section,PAR_NULL,SAN_FLAT);
	$file = get_file_var();
	$mode = getparam("mode", PAR_GET, SAN_FLAT);

	// prevents to go up/down to other directories
	if(stristr($section,"..")) die(_NONPUOI);
	if(stristr($file,"..")) die(_NONPUOI);

	// check if section really exists
	if(!file_exists("sections/$section")) {
		OpenTable();
		print("<div align='center'><b>"._SECTNOTEXIST."</b></div><br /><br />");
		if (file_exists("themes/$theme/fn_404.php")) {
			include(stripslashes("themes/$theme/fn_404.php"));
		} else {
			echo "<div style=\"text-align:center;\"><img src=\"images/fn_404.png\" alt=\""._SECTNOTEXIST."\" title=\""._SECTNOTEXIST."\"/></div>";
		}
		CloseTable();
		return;
	}

	// CHECKING SECTION PERMISSIONS -->
	if (!user_can_view_section($section,get_username())){
		OpenTable();
		print("<div align='center'><b>"._NOLEVELSECT."</b></div><br /><br />");
		if (file_exists("themes/$theme/fn_denied.php")) {
			include(stripslashes("themes/$theme/fn_denied.php"));
		} else {
			echo "<div style=\"text-align:center;\"><img src=\"images/fn_denied.png\" alt=\""._NOLEVELSECT."\" title=\""._NOLEVELSECT."\"/></div>";
		}
		CloseTable();
		return;
	}
	// <-- END CHECKING SECTION PERMISSIONS

	if($file!="")
		$sect = $section."/$file";
	else
		$sect = $section;

	// Build navigation bar of the section
	$tit = "";
	$albero = explode("/",$sect);
	for($i=0;$i<sizeof($albero);$i++){
		$mypath = "";
		for($j=0;$j<=$i;$j++){
			if($i>0 and ($j!=$i)){
				$mypath .= $albero[$j]."/";
			} else {
				$mypath .= $albero[$j];
			}
		}
		$tmp = str_replace("none_","",$albero[$i]);
		$tmp = eregi_replace("^[0-9]*_","",$tmp);
		if($i!=(sizeof($albero)-1)){
			$accesskey="";
			if (get_access_key($mypath)!=""){
				$accesskey = "accesskey=\"".get_access_key($mypath)."\"";
			}
			$tit .= "<a href='index.php?mod=".rawurlencodepath($mypath)."' title=\""._GOTOSECTION.": ".str_replace("_"," ",$tmp)."\" $accesskey>".str_replace("_"," ",$tmp)."</a>/";
		} else {
			$tit .= str_replace("_"," ",$tmp);
			$tit = ereg_replace("\.[a-z0-9]{1,4}$","",$tit); // delete file extension
		}
	}

	// Find the image that identifies the current section; if not find, it takes the default one by the theme
	if(file_exists("sections/$section/section.png")) {
		$section_image = "sections/$section/section.png";
	} else $section_image = "themes/$theme/images/section.png";

	// Start printing section
	if(defined('_THEME_VER')) {
		if(_THEME_VER > 0) {
			OpenTableTitle("<a title=\"\" accesskey=\"0\"></a>".stripslashes($tit));
		}
	} else {
		OpenTableTitle("<a title=\"\" accesskey=\"0\"><img src='$section_image' alt='Section' /></a>&nbsp;".stripslashes($tit));
	}
	
	// Include code for section's header
	load_php_code("include/section/header");

	if($file==""){
		if(file_exists("sections/$section/section.php")){
			include("sections/$section/section.php");
			echo "<br />";
		}
		/* Main download section with Fdplus */
		if(file_exists("sections/$section/download") and is_file("sections/$section/download")) {
			echo "<br />";
			include_once("download/fd+.php");
			fd_overview();
		}
		/* Single download section with Fdplus */
		if(file_exists("sections/$section/downloadsection") and is_file("sections/$section/downloadsection")) {
			echo "<br />";
			include_once("download/fd+.php");
			fd_view_section();
		}
		/* Forum section with Flatforum */
		if(file_exists("sections/$section/forum") and is_file("sections/$section/forum")) {
			echo "<br />";
			include_once("forum/flatforum.php");
		}
		/* Gallery section */
		if(file_exists("sections/$section/gallery") and is_file("sections/$section/gallery")) {
			echo "<br />";
			include("gallery/gallery.php");
		}
	} else {
		include(stripslashes('sections/'.$section.'/'.$file));
	}

	// Include code for section's footer
	load_php_code("include/section/footer");

	// link to print current section
	$options = "?";
	foreach ($_GET as $key => $value) {
		$value   .= getparam($value, PAR_GET, SAN_FLAT);
		$options .= "$key=$value&amp;";
	}
	echo "<div align='right'><a href='print.php".$options."' target='new' title=\""._STAMPA."\"><img src='themes/$theme/images/print.png' border='0' alt='print' /></a></div>";

	// Administration of the section (visible only to administrtaors)
	echo "<hr size='1' />";
	if(is_admin() AND is_writeable("sections/$section") AND !fn_is_system_dir($section)) {
		section_admin_panel();
	}
	if(user_can_edit_section($section,get_username()) AND is_writeable("sections/$section") AND !fn_is_system_dir($section)) {
		section_user_edit_panel();
	}
	
	CloseTableTitle();
}


/**
 * Elenca le sezioni ed i link ad esse associati
 *
 * Restituisce un array contenente le sezioni ed un secondo
 * array contenente i link preformattati alle sezioni stesse.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @since 2.5.8
 *
 * @param string $path Directory delle sezioni da scorrere
 * @param string $result Specifica se restituire i nomi delle sezioni ('names') oppure i loro link ('links')
 * @return array Lista dei nomi o lista dei link delle sezioni trovate
 */
function list_sections($path, $result){
	$path   = getparam($path,   PAR_NULL, SAN_FLAT);
	$result = getparam($result, PAR_NULL, SAN_FLAT);
	$modlist   = array();
	$link_list = array();

	$handle = opendir($path);
	while ($file = readdir($handle)) {
		if (!( $file=="." or $file==".." ) and (!ereg("^\.",$file) and ($file!="CVS") and !stristr($file,"none_") )) {
			if (!user_can_view_section(eregi_replace("^sections/","","$path/$file"))) continue;
			array_push($modlist, $file);
		}
	}
	closedir($handle);

	if(count($modlist)<=0){
		return(null);
	}

	sort($modlist);

	$j=0;
	for ($item_num=0; $item_num < count($modlist); $item_num++) {
		if(!stristr($modlist[$item_num],"none_")){
			if(stristr($modlist[$item_num],"_")){
				$tmp=eregi_replace("^[0-9]*_","",$modlist[$item_num]);
				$tmp=str_replace("_"," ",$tmp);
			}
			else
				$tmp=$modlist[$item_num];
		$link_list[$j] = "<a href=\"index.php?mod=".rawurlencodepath($modlist[$item_num])."\" title=\" "._GOTOSECTION.": $tmp\"";
		if (get_access_key($modlist[$item_num])!=""){
			$link_list[$j] = $link_list[$j]." accesskey=\"".get_access_key($modlist[$item_num])."\"";
		}
		$link_list[$j] = $link_list[$j].">$tmp</a>";
		$j++;
		}
	}

	switch($result) {
		case "names":
			return($modlist);
		break;
		case "links":
			return($link_list);
		break;
	}
}


/**
 * Crea il menu principale
 *
 * Crea un blocco contenente il menu principale elencando tutte le directories
 * che in <i>/sections/</i> non iniziano con "none_":
 *  - prima vengono, in ordine alfabetico, le directories che iniziano
 *    con un carattere (es: Prova);
 *  - di seguito, in ordine crescente, quelle che iniziano con una coppia
 *    di numeri (es: 03_Prova).
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * //-> DEPRECATED! USE list_sections() AND BUILD THE MENU FROM THE THEME
 */
function create_menu(){
}


/**
 * Visualizza i blocchi laterali
 *
 * Visualizza il contenuto dei blocchi laterali presenti nelle directories
 * <i>/blocks/dx/</i> oppure <i>/blocks/sx/</i> a seconda del parametro passato;
 * non vengono stampati i blocchi che iniziano per "none_".
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $edge Lato dei blocchi da stampare
 */
function create_blocks($edge){
	global $theme;

	if (file_exists("include/redefine/create_blocks.php")){
		include("include/redefine/create_blocks.php");
		return;
	}

	$edge=getparam($edge,PAR_NULL,SAN_FLAT);
	$modlist = array();

	$handle=opendir('blocks/'.$edge);
	while ($file = readdir($handle)) {
		if (!is_dir("blocks/$edge/$file") and (!ereg("^\.",$file)) and !stristr($file,"none_")) {
			array_push($modlist, $file);
		}
	}
	closedir($handle);

	if(count($modlist)>0)
		sort($modlist);
	for ($item_num=0; $item_num < count($modlist); $item_num++) {
		$tmp=eregi_replace("^[0-9]*_","",$modlist[$item_num]);
		$title=str_replace("_"," ",str_replace(".php","",$tmp));
		// backward theme compatibility
		if(function_exists("OpenBlock")){
			OpenBlock("themes/$theme/images/block.png",$title);
		}
		else {
			OpenTableTitle("<img src=\"themes/$theme/images/menu.png\" alt=\"$title\" />&nbsp;$title");
		}
		include ("blocks/$edge/$modlist[$item_num]");
		if(function_exists("CloseBlock"))
			CloseBlock();
		else
			CloseTableTitle();
	}
}


/**
 * Visualizza la sezione dedicata alle news
 *
 * Visualizza nella sezione un numero di news (a partire dalla piu' recente)
 * secondo quanto indicato in fase di configurazione.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 */
function create_news(){
	// security checks
	$pag = getparam("pag",PAR_GET,SAN_FLAT);
	global $newspp, $theme;
	// redefine this function
	if (file_exists("include/redefine/create_news.php")){
		include("include/redefine/create_news.php");
		return;
	}
	// load news array
	$modlist = array();
	$handle  = opendir('news');
	while ($file = readdir($handle)) {
		if (!( $file=="." or $file==".." ) and (!ereg("^\.",$file) and ($file!="CVS")) and eregi("xml$",get_file_extension($file)) ) {
			array_push($modlist, $file);
		}
	}
	closedir($handle);
	if(count($modlist)>0)
		rsort($modlist);
	// calculate current page limits
	$totpages = (count($modlist)%$newspp!=0) ? (intval(count($modlist)/($newspp)+1)) : (intval(count($modlist)/$newspp));
	if( !is_numeric($pag) OR $pag<1 OR $pag>$totpages ) {
		$pag   = 1;
		$first = 0;
	} else $first = ($pag * $newspp) - ($newspp);
	//echo "<div>Pag $pag/$totpages. First file is modlist[$first].</div>"; //-> TEST
	
	// print news of current page
	for ($i=$first; $i<count($modlist) AND $i<($first+$newspp); $i++) {
		$string = get_file("news/$modlist[$i]");
		print "<br />";
		$title  = get_xml_element("fn:title",$string);
		$header = ereg_replace(".*<fn:header>","",$string);
		$header = ereg_replace("</fn:header>.*","",$header);
		$avatar = get_xml_element("fn:avatar",$string);
		if(defined('_THEME_VER')) {
			if(_THEME_VER > 0)
				$ntitle = $title;
		} else $ntitle = "<img src=\"themes/$theme/images/news.png\" alt=\"News\" />&nbsp;$title";

		OpenTableTitle($ntitle);
		$w3c_title = _ARGOMENTO.": ".eregi_replace("\.png$|\.gif$|\.jpeg$|\.jpg$","",$avatar);
		echo "<a href=\"index.php?mod=none_Search&amp;where=news&amp;find=$avatar\">";
		if(file_exists("images/news/$avatar")) {
			echo "<img src=\"images/news/$avatar\" border=\"0\" alt=\"$w3c_title\" title=\"$w3c_title\" align=\"right\" />";
		} else echo "<div style='text-align:right;padding-bottom:5px;'>$w3c_title</div>";
		echo "</a>";
		echo stripslashes($header);
		if(defined('_THEME_VER')) {	// compatibilita' vecchi temi
			if(_THEME_VER > 0) {
				CreateFootNews(str_replace(".xml","",$modlist[$i]));
			}
		} else {
			CloseTableTitle2(str_replace(".xml","",$modlist[$i]));
		}
	}
	// print links to other pages
	if($totpages > 1) {
		echo "<div style='font-size:0.8em; padding: 30px 5px 10px 5px;'>";
		if($pag > 1) {
			echo "<div style='float:left'>";
			echo "<a href=\"index.php?pag=".($pag-1)."\" title=\""._GOTOTHEPREVIOUSPAGE."\">&#171; "._GOTOTHEPREVIOUSPAGE."</a>";
			echo "</div>";
		}
		if($pag < $totpages) {
			echo "<div style='float:right'>";
			echo "<a href=\"index.php?pag=".($pag+1)."\" title=\""._GOTOTHENEXTPAGE."\">"._GOTOTHENEXTPAGE." &#187;</a>";
			echo "</div>";
		}
		echo "</div>";
	}
}


/**
 * Visualizza una textarea per commentare una news
 *
 * Permette di inserire un commento alla notizia passata come parametro,
 * tramite una comoda textarea.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $news Nome assoluto del file della news da modificare
 */
function insert_comment($news){
	// security checks
	global $sitename,$guestcomment;
	$news    = getparam($news,PAR_NULL,SAN_FLAT);
	$req     = getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT);
	// load news array
	$modlist = array();
	$handle = opendir('news');
	while ($file = readdir($handle)) {
		if (!($file == "." or $file == "..") and eregi("xml$",get_file_extension($file))) {
			array_push($modlist, $file);
		}
	}
	closedir($handle);
	// verify news exists
	if(!in_array($news.".xml", $modlist)) {
		OpenTable();
		echo "<div align='center'><b>"._NORESULT."</b></div>";
		CloseTable();
		return;
	}
	// verify guests can post
	if(strstr($req,"guestcomment="))
		$guestcomment = 0;
	// print interface
	OpenTableTitle(_ADDCOMM);
	if((get_username()!="") or ($guestcomment==1)){
		echo "<form action=\"index.php\" method=\"post\">
		<input type=\"hidden\" name=\"fnaction\" value=\"fnsavenewscomment\" />
		<input type=\"hidden\" name=\"id\" value=\"$news\" />";
		// bbcodes panel
		bbcodes_panel("body", "home", "formatting"); echo "<br />";
		bbcodes_panel("body", "home", "emoticons"); echo "<br />";
		bbcodes_panel("body","home","images"); echo "<br />";
		echo "<textarea cols=\"50\" rows=\"20\" name=\"body\" style=\"width: 95%\" ></textarea><br /><br />
		<input type=\"submit\" value=\""._FINVIA."\" />
		</form><br />";
		read_news($news);
	}
	else{
		print _DEVIREG." <b>".$sitename."</b> "._DEVIREG2;
	}
	CloseTableTitle();
}


/**
 * Add a comment to the news
 *
 * This function add a comment to the news selected.
 *
 * @author Marco Segato <segatom@users.sourceforge.net>
 * @since  2.7.2
 */
function fn_save_news_comment() {
	// define variables
	$myforum    = get_username();
	$id         = getparam("id", PAR_POST, SAN_FLAT);
	$ip         = getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$newsfile   = get_fn_dir("news")."/$id.xml";
	$guest_get  = trim(getparam($guestcomment, PAR_GET,  SAN_FLAT));
	$guest_post = trim(getparam($guestcomment, PAR_POST, SAN_FLAT));
	global $guestcomment;
	// security checks
	if(!file_exists($newsfile)) {
		header("Location: index.php");
		return;
	}
	if ($guest_get!="" OR $guest_post!="")
		die();
	if ($guestcomment!=1 AND is_guest())
		die();
	// retrieve news contents
	$name = ($myforum=="") ? (_SCON) : ($myforum);
	$body = (isset($_POST['body'])) ? ($_POST['body']) : ("");
	// spam checks
	if ( (is_spam($body,"words") AND !is_admin()) OR $body=="" ){
		echo _SPAMALERT."<br /><br />";
		echo "<a href=\"javascript:history.back()\">"._INDIETRO."</a>";
		die();
	}
	// build news contents
	$myname = stripslashes(htmlspecialchars($name));
	$body   = str_replace("\n", "<br />", $body);
	$mybody = tag2html($body, "home");
	// start writing the comment
	$string = get_file($newsfile);
	if(!stristr($string,"<fn:comments>")) {	// first comment
		$string = str_replace("</fn:news>","\t<fn:comments>\n\t\t<fn:comment>\n\t\t\t<fn:by>$myname</fn:by>\n\t\t\t<fn:date>".time()."</fn:date>\n\t\t\t<fn:post>".$mybody."</fn:post>\n\t\t</fn:comment>\n\t</fn:comments>\n</fn:news>",$string);
	} else {	// there is one or more comment
		$string = str_replace("</fn:comments>","\t<fn:comment>\n\t\t\t<fn:by>$myname</fn:by>\n\t\t\t<fn:date>".time()."</fn:date>\n\t\t\t<fn:post>".$mybody."</fn:post>\n\t\t</fn:comment>\n\t</fn:comments>",$string);
	}
	// save news comment
	fnwrite($newsfile, $string, "w", array("nonull"));
	fnlog("News", $ip."||".$myforum."||Comment added to the news $id.");
	header("Location: index.php?mod=read&id=$id");
}


/**
 * Visualizza una textarea per la modifica di un file
 *
 * Permette di modificare direttamente online il file passato come parametro,
 * tramite una comoda textarea che ne visualizza il contenuto.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $filename Nome del file da modificare
 * @param string $editor l'editor da usare (attualmente solo "fckeditor")
 */
function edit_content($filename,$editor="html"){
	if (file_exists("include/redefine/edit_content.php")){
		include("include/redefine/edit_content.php");
		return;
	}

	$filename=getparam($filename,PAR_NULL,SAN_FLAT);
	$from=getparam("from",PAR_GET,SAN_FLAT);
	$from=stripslashes($from);
	$editor = getparam($editor,PAR_NULL,SAN_FLAT);
	$editor= trim($editor);
	
	if(stristr($filename,"..") or !file_exists($filename)) {
		OpenTable();
		print("<div align='center'><b>"._NORESULT."</b></div>");
		CloseTable();
		return;
	}

	OpenTableTitle(_MODIFICA." ".$filename);
	echo "<form action=\"verify.php\" method=\"post\">
	<input type=\"hidden\" name=\"mod\" value=\"modcont\" />
	<input type=\"hidden\" name=\"from\" value=\"".$from."\" />";
	
	//Testo da modificare
	$text = get_unprotected_text(file_get_contents($filename));
	
// 	echo "EDITOR: $editor";	
	if ($editor=="fckeditor"){
		if (file_exists("include/plugins/editors/FCKeditor/fckeditor.php")){
			include("include/plugins/editors/FCKeditor/fckeditor.php");
			$oFCKeditor = new FCKeditor('body') ;
			$oFCKeditor->BasePath	= "include/plugins/editors/FCKeditor/" ;
			$oFCKeditor->Value= $text;
			$oFCKeditor->Width="100%";
			$oFCKeditor->Height="800";
			$oFCKeditor->ToolbarSet= "Default";
			$oFCKeditor->Create() ;
		}
		else {
		echo "<textarea cols=\"80\" rows=\"30\" name=\"body\" style=\"width: 95%\">";
		echo htmlspecialchars($text);
		echo "</textarea>";
		}
	}
	else {
	echo "<textarea cols=\"80\" rows=\"30\" name=\"body\" style=\"width: 95%\">";
	echo htmlspecialchars($text);
	echo "</textarea>";
	}
	
	echo "<br /><br />
	<input type=\"hidden\" name=\"file\" value=\"".$filename."\" />
	<input type=\"submit\" value=\""._MODIFICA."\" />
	</form>";
	CloseTableTitle();
}

/**
 * Visualizza una textarea per la modifica di un file da parte di un utente
 *
 * Permette di modificare direttamente online il file passato come parametro,
 * tramite una comoda textarea che ne visualizza il contenuto.
 *
 * @author Aldo Boccacci
 *
 * @param string $filename Nome del file da modificare
 * @param string $editor l'editor da usare (attualmente solo "fckeditor")
 */
function user_edit_content($filename,$editor="html"){

	$filename=getparam($filename,PAR_NULL,SAN_FLAT);
	$from=getparam("from",PAR_GET,SAN_FLAT);
	$from=stripslashes($from);
	$editor = getparam($editor,PAR_NULL,SAN_FLAT);
	$editor= trim($editor);
	$username = get_username();
	
	if (!check_path($filename,"sections/","true")) fn_die("USERMODCONT","Error: The path ".strip_tags($filename)." is not valid!",__FILE__,__LINE__);
	
	$mod = get_mod();
	if (trim($mod)!="usermodcont") fn_die("USERMODCONT","Error: \$mod must be \"usermodcont\"",__FILE__,__LINE__);
	
	$sectmod = eregi_replace("sections\/","",dirname($filename));
	
	if (!user_can_view_section($sectmod)) fn_die("USERMODCONT","Error: the user ".strip_tags($username)." cannot view the section ".strip_tags($sectmod)."",__FILE__,__LINE__);
	
	if (!user_can_edit_section($sectmod)) fn_die("USERMODCONT","Error: the user ".strip_tags($username)." cannot edit the section ".strip_tags($sectmod)."",__FILE__,__LINE__);
	
	//Testo da modificare
	$text = get_unprotected_text(file_get_contents($filename));
	if (eregi("\<\?|\?\>",$text)) fn_die("USERMODCONT","Error, user".strip_tags($username)." cannot edit the section ".strip_tags($sectmod)." because contains php code",__FILE__,__LINE__);
	
	if(stristr($filename,"..") or !file_exists($filename)) {
		OpenTable();
		print("<div align='center'><b>"._NORESULT."</b></div>");
		CloseTable();
		return;
	}

	OpenTableTitle(_MODIFICA." ".$filename);
	echo "<form action=\"verify.php\" method=\"post\">
	<input type=\"hidden\" name=\"mod\" value=\"usermodcont\" />
	<input type=\"hidden\" name=\"from\" value=\"".$from."\" />";
	
	//Testo da modificare
	$text = get_unprotected_text(file_get_contents($filename));
	
// 	echo "EDITOR: $editor";	
	if ($editor=="fckeditor"){
		if (file_exists("include/plugins/editors/FCKeditor/fckeditor.php")){
			include("include/plugins/editors/FCKeditor/fckeditor.php");
			$oFCKeditor = new FCKeditor('body') ;
			$oFCKeditor->BasePath	= "include/plugins/editors/FCKeditor/" ;
			$oFCKeditor->Value= $text;
			$oFCKeditor->Width="100%";
			$oFCKeditor->Height="800";
			$oFCKeditor->ToolbarSet= "Default";
			$oFCKeditor->Create() ;
		}
		else {
		echo "<textarea cols=\"80\" rows=\"30\" name=\"body\" style=\"width: 95%\">";
		echo htmlspecialchars($text);
		echo "</textarea>";
		}
	}
	else {
	echo "<textarea cols=\"80\" rows=\"30\" name=\"body\" style=\"width: 95%\">";
	echo htmlspecialchars($text);
	echo "</textarea>";
	}
	
	echo "<br /><br />
	<input type=\"hidden\" name=\"file\" value=\"".$filename."\" />
	<input type=\"submit\" value=\""._MODIFICA."\" />
	</form>";
	CloseTableTitle();
}

/**
 * Effettua il parsing di un feed RSS esterno
 *
 * Legge il file di un feed RSS esterno al sito e ne genera una stampa
 * leggibile e ordinata con le notizie segnalate, completa di link
 * per raggiungerle sul sito di origine.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $url Indirizzo del feed RSS
 * @return null|string Nulla se non trova il file, oppure il contenuto del feed RSS
 */
function parse_RSS($url){

	$url=getparam($url,PAR_NULL,SAN_FLAT);

	if ($url != "") {
		if (!ereg("http://",$url)) {
			$url = "http://$url";
		}
		$rdf = parse_url($url);
		$fp = fsockopen($rdf['host'], 80, $errno, $errstr, 15);
		if (!$fp) {
			print(_NORSS);
			return;
		}
		if ($fp) {
			@fputs($fp, "GET " . $rdf['path'] . "?" . $rdf['query'] . " HTTP/1.0\r\n");
			@fputs($fp, "HOST: " . $rdf['host'] . "\r\n\r\n");
			$string = "";
			while(!feof($fp)) {
				$pagetext = fgets($fp,228);
				$string .= chop($pagetext);
			}
			fputs($fp,"Connection: close\r\n\r\n");
			fclose($fp);
			$items = explode("</item>",$string);

			$content = "";
			$cont = 0;
			for ($i=0;$i<sizeof($items)-1;$i++) {
				$link = ereg_replace(".*<link>","",$items[$i]);
				$link = ereg_replace("</link>.*","",$link);
				$title2 = ereg_replace(".*<title>","",$items[$i]);
				$title2 = ereg_replace("</title>.*","",$title2);
				// some feeds are exposed with CDATA format
				$title2 = str_replace("<![CDATA[","",$title2);
				$title2 = str_replace("]]>","",trim($title2));
				if ($items[$i] == "" AND $cont != 1) {
					$content = "";
				} else {
					if (strcmp($link,$title2) AND $items[$i] != "") {
						$cont = 1;
						$content .= "<b><big>&middot;</big></b>&nbsp;<a href=\"$link\" target=\"new\">$title2</a><br />\n";
					}
				}
			}
		}
	}
	return $content;
}


/**
 * Genera il feed RSS
 *
 * Genera il file <i>/misc/backend.xml</i> che contiene le news presenti in
 * homepage; 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}.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @author Marco Segato <segatom@users.sourceforge.net> | 20050206: RSS 2.0 support
 */
function generate_RSS() {
	include "config.php";
	switch($lang) {
		case "de" OR "es" OR "fr" OR "it" OR "pt":
			include_once ("languages/$lang.php");
		break;
		default:
			include_once ("languages/en.php");
	}

	$url = "http://".getparam("HTTP_HOST", PAR_SERVER, SAN_FLAT).getparam("PHP_SELF", PAR_SERVER, SAN_FLAT);
	$url = str_replace(basename($url),"",$url);

	// 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</title>\n\t\t<link>$url</link>\n\t\t<description><![CDATA[\"$sitename\" HEADLINES]]></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('news');
	$modlist = array();
	while ($file = readdir($handle)) {
        if (!( $file=="." or $file=="..") and (!ereg("^\.",$file) and ($file!="CVS")) AND eregi("xml$",get_file_extension($file))) {
			array_push($modlist, $file);
		}
	}
	closedir($handle);
	if(count($modlist)>0)
		rsort($modlist);
	// creazione tag per ognuna delle news
	for ($i=0; $i < count($modlist); $i++) {
		if ($i>=$newspp)
			break;
		$string = get_file("news/$modlist[$i]");
		$mytitle = get_xml_element("fn:title",$string);
		$mydesc = stripslashes(str_replace("<br>","<br />",get_xml_element("fn:header",$string)));
		$id = str_replace(".xml","",$modlist[$i]);
		$body .= "\t\t<item>\n";
		$body .= "\t\t\t<title>$mytitle</title>\n";
		$body .= "\t\t\t<link>$url"."index.php?mod=read&amp;id=$id</link>\n\t\t\t<description><![CDATA[$mydesc]]></description>\n";
		$body .= "\t\t\t<pubDate>".date("D, d M Y H:i:s",$id)." GMT</pubDate>\n";
		$body .= "\t\t</item>\n";
	}
	// tag chiusura del feed
	$body.="\t</channel>\n</rss>";
	// scrittura del feed
	fnwrite("misc/backend.xml", $body, "w", array("nonull"));
}


/**
 * Restituisce il livello di una sezione
 *
 * Restituisce il livello della sezione passata come parametro, leggendolo dal
 * file <i>/section/nomesezione/level.php</i>:
 *  - -1 se non esiste il file level.php, la sezione sara' visibile da tutti;
 *  - 0 per una sezione visibile solo da utenti registrati;
 *  - da 1 a 9 per una sezione visibile solo da utenti di livello intermedio;
 *  - 10 per una sezione visibile solo da utenti amministratore.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 *
 * @param string $section Nome della sezione
 * @return int -1 se la sezione non ha livello, oppure un numero di livello da 0 a 10
 */
function getsectlevel($section){
	$section=getparam($section,PAR_NULL,SAN_FLAT);
	if(!file_exists("sections/$section/level.php"))
		return(-1);
	$fp=file("sections/$section/level.php");
	return((int)str_replace("\n","",$fp[0]));
}


/**
 * Funzione alternativa a html_entity_decode()
 *
 * Rimpiazza la funzione nativa di PHP html_entity_decode() per gli utenti
 * che utilizzano una versione di PHP piu' vecchia della 4.3.0.
 *
 * @author Documentazione ufficiale PHP - {@link http://it.php.net/manual/en/function.html-entity-decode.php}
 *
 * @param string $string
 * @return string Una stringa che preserva i caratteri speciali HTML
 */
function unhtmlentities($string) {
  	/*$trans_tbl = get_html_translation_table(HTML_ENTITIES);
	$trans_tbl = array_flip($trans_tbl);
        return strtr($string, $trans_tbl);*/
}


/**
 * Genera un log di attivita'
 *
 * Aggiunge al file <i>/misc/log/log.php</i> una riga che contiene
 * la data e l'ora di produzione della segnalazione di log, la zona
 * di origine e una descrizione dell'attivita' effettuata.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @since 2.5.4
 *
 * @param string $zone Nome della sezione cui si riferisce il log
 * @param string $txt Testo del log da salvare
 */
function fnlog($zone, $txt){
	$zone=getparam($zone,PAR_NULL,SAN_FLAT);
	$txt=getparam($txt,PAR_NULL,SAN_FLAT);
	if($zone == "Forum") {
		$pref="../";
		$flog = $pref."misc/log";
	}
	else {
		$pref ="";
		$flog = "misc/log";
	}
	// prepare environment if not present
	if(!is_dir($flog))
		mkdir($flog, 0777);
	// log rotate every 0.5 MB
	if(file_exists("$flog/log.php") AND (filesize("$flog/log.php") >= 524288)) {
		rename("$flog/log.php",$pref."misc/log/log-".time().".php");
		$fp=fopen("$flog/log.php","a");
		fwrite($fp, "<?exit(1);?>\n");
		fclose($fp);
	}
	// check file existance and write an empty file
	if(!file_exists("$flog/log.php")) {
		$fp=fopen("$flog/log.php","a");
		fwrite($fp, "<?exit(1);?>\n");
		fclose($fp);
	}
	// write log file
	if (file_exists("$flog/log.php")){
		$fp=fopen("$flog/log.php","a");
		$string =  date ("d/m/Y H:i:s");
		$string = $string." $zone: $txt\n";
		fwrite($fp,$string);
		fclose($fp);
	}
}


/**
 * Mostra le informazioni sul copyright di un modulo
 *
 * Crea un link da cui e' possibile visualizzare una finestra popup
 * con informazioni dettagliate sul copyright del modulo corrente.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @since 2.5.4
 *
 * @param string $modulo Nome del modulo installato
 * @param string $versione Versione del modulo installato
 * @param string $autore Nome dell'autore del modulo
 * @param string $email E-mail dell'autore del modulo
 * @param string $homepage Homepage dell'autore del modulo
 * @param string $licenza Licenza di rilascio del modulo
 */
function module_copyright($modulo, $versione, $autore, $email, $homepage, $licenza) {
	$modulo   = getparam($modulo,   PAR_NULL, SAN_FLAT);
	$versione = getparam($versione, PAR_NULL, SAN_FLAT);
	$autore   = getparam($autore,   PAR_NULL, SAN_FLAT);
	$email    = getparam($email,    PAR_NULL, SAN_FLAT);
	$email    = email_mask($email);
	$homepage = getparam($homepage, PAR_NULL, SAN_FLAT);
	$licenza  = getparam($licenza,  PAR_NULL, SAN_FLAT);

	// preview link
	echo "<br /><div align='right'><a href='javascript:;' onclick='copyrightshow();' title='Copyright info'>Copyright &copy; <b>$modulo</b></a></div><br />";
	// preview box
	echo "<div id='fncopyright'>";
	echo "<p align='center'><b>Copyright informations</b></p>Module developed for the <b><a href='http://flatnuke.sf.net'>Flatnuke</a></b> CMS<br /><br />";
	echo "<b>Module name</b>: $modulo<br /><b>Version</b>: $versione<br /><b>License</b>: $licenza<br />";
	echo "<b>Author</b>: $autore<br /><b>E-mail</b>: <a href='mailto:$email'>".str_replace("%20"," ",$email)."</a><br /><b>Home page</b>: <a href='$homepage' target='_blank' title='$homepage'>$homepage</a> <br />";
	echo "<p align='center'><b><a href='javascript:;' onclick='copyrightshow();'>Close</a></b></p></div>";
}


/**
 * Gestione tag per codice html
 *
 * Rimpiazza i pseudo-tag ([b], [i], ecc) con i tag html)
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @author Marco Segato <segatom@users.sourceforge.net> | 20050916: Unificato la funzione per l'uso nel sito e nel forum
 * @since 2.5.7
 *
 * @param string $string Stringa da verificare
 * @param string $where Riferimento alla root per l'esecuzione del codice: 'home' per le news, 'forum' per il forum
 * @return string Codice HTML
 */
function tag2html($string, $where) {
	// verifico provenienza della chiamata e adatto i richiami alle directories
	$string=getparam($string,PAR_NULL,SAN_FLAT);
	$where=getparam($where,PAR_NULL,SAN_FLAT);

	$prepath="forum/";
	// solo l'amministratore puo' usare codice HTML
	$myforum=getparam("myforum", PAR_COOKIE, SAN_FLAT);
	if(getlevel($myforum,$where) < 10) {
		$string = str_replace("<", "&lt;", $string);
		$string = str_replace(">", "&gt;", $string);
	}
	// formatting fixes
	$string = str_replace("&lt;br/&gt;", "<br />", $string);
	$string = str_replace("&lt;br /&gt;", "<br />", $string);
	$string = str_replace("&lt;br&gt;", "<br />", $string);
	$string = str_replace("<br>", "<br />", $string);
	$string = str_replace("&#91;", "[", $string);
	$string = str_replace("&#93;", "]", $string);
	$string = str_replace("|", "", $string);
	// emoticons
	$string = str_replace("[:)]", "<img src='".$prepath."emoticon/01.png' alt=':)' />", $string);
	$string = str_replace("[:(]", "<img src='".$prepath."emoticon/02.png' alt=':(' />", $string);
	$string = str_replace("[:o]", "<img src='".$prepath."emoticon/03.png' alt=':o' />", $string);
	$string = str_replace("[:p]", "<img src='".$prepath."emoticon/04.png' alt=':p' />", $string);
	$string = str_replace("[:D]", "<img src='".$prepath."emoticon/05.png' alt=':D' />", $string);
	$string = str_replace("[:!]", "<img src='".$prepath."emoticon/06.png' alt=':!' />", $string);
	$string = str_replace("[:O]", "<img src='".$prepath."emoticon/07.png' alt=':O' />", $string);
	$string = str_replace("[8)]", "<img src='".$prepath."emoticon/08.png' alt='8)' />", $string);
	$string = str_replace("[;)]", "<img src='".$prepath."emoticon/09.png' alt=';)' />", $string);
	$string = str_replace("[rolleyes]", "<img src='".$prepath."emoticon/rolleyes.png' alt=':rolleyes:' />", $string);
	$string = str_replace("[neutral]", "<img src='".$prepath."emoticon/neutral.png' alt=':|' />", $string);
	$string = str_replace("[:x]", "<img src='".$prepath."emoticon/mad.png' alt=':x' />", $string);
	$string = str_replace("[O:)]", "<img src='".$prepath."emoticon/angel.png' alt='O:)' />", $string);
	$string = str_replace("[whistle]", "<img src='".$prepath."emoticon/whistle.png' alt='whistle' />", $string);
	$string = str_replace("[eh]", "<img src='".$prepath."emoticon/eh.png' alt='whistle' />", $string);
	$string = str_replace("[evil]", "<img src='".$prepath."emoticon/evil.png' alt=':evil:' />", $string);
	$string = str_replace("[idea]", "<img src='".$prepath."emoticon/idea.png' alt=':idea:' />", $string);
	$string = str_replace("[bier]", "<img src='".$prepath."emoticon/bier.png' alt=':bier:' />", $string);
	$string = str_replace("[flower]", "<img src='".$prepath."emoticon/flower.png' alt=':flower:' />", $string);
	$string = str_replace("[sboing]", "<img src='".$prepath."emoticon/sboing.png' alt=':sboing:' />", $string);
	
	// formattazione testo
	$string = str_replace("\n", "<br />", $string);
	$string = str_replace("\r", "", $string);
	$string = str_replace("[b]", "<b>", $string);
	$string = str_replace("[u]", "<u>", $string);
	$string = str_replace("[/u]", "</u>", $string);
	$string = str_replace("[/b]", "</b>", $string);
	$string = str_replace("[i]", "<i>", $string);
	$string = str_replace("[/i]", "</i>", $string);
	$string = str_replace("[strike]","<span style=\"text-decoration : line-through;\">",$string);
	$string = str_replace("[/strike]","</span>",$string);
	$string = preg_replace("/\[quote\=(.+?)\](.+?)\[\/quote\]/s",'<blockquote><b>$1 '._HASCRITTO.':</b><br />$2</blockquote>',$string);
	$string = str_replace("[quote]", "<blockquote>", $string);
	$string = str_replace("[/quote]", "</blockquote>", $string);
	$string = str_replace("[code]", "<pre>", $string);
	$string = str_replace("[/code]", "</pre>", $string);
	$string = preg_replace("/\[url\=(.+?)\](.+?)\[\/url\]/s",'<a title="$2" href="$1" target="blank_">$2</a>',$string);
	
	if (is_guest()){
		$string = eregi_replace("\[mail\].*\[\/mail\]","<span style=\"text-decoration : line-through;\" title=\"only users can view mail addresses\">[e-mail]</span>",$string);
	}
	else {
		$string = preg_replace("/\[mail\](.+?)\[\/mail\]/s",'<a title="mail to $1" href="mailto:$1">$1</a>',$string);
	}
	
	// solo l'amministratore puo' inserire immagini
	switch($where) {
		case "home":
			if(is_admin()) {
				$string = str_replace("[img]", "<br /><img src=\"", $string);
				$string = str_replace("[/img]", "\" alt=\"uploaded_image\" /><br />", $string);
			}
		break;
		case "forum":
				$string = str_replace("[img]", "<br /><img src=\"", $string);
				$string = str_replace("[/img]", "\" alt=\"uploaded_image\" /><br />", $string);
		break;
	}
	
	//posizione
	$string = str_replace("[left]", "<div style=\"text-align : left;\">", $string);
	$string = str_replace("[right]", "<div style=\"text-align : right;\">", $string);
	$string = str_replace("[center]", "<div style=\"text-align : center;\">", $string);
	$string = str_replace("[justify]", "<div style=\"text-align : justify;\">", $string);
	$string = str_replace("[/left]", "</div>", $string);
	$string = str_replace("[/right]", "</div>", $string);
	$string = str_replace("[/center]", "</div>", $string);
	$string = str_replace("[/justify]", "</div>", $string);
	
	// colori del testo
	$string = str_replace("[red]", "<span style=\"color : #ff0000\">", $string);
	$string = str_replace("[green]", "<span style=\"color : #00ff00\">", $string);
	$string = str_replace("[blue]", "<span style=\"color : #0000ff\">", $string);
	$string = str_replace("[pink]", "<span style=\"color : #ff00ff\">", $string);
	$string = str_replace("[yellow]", "<span style=\"color : #ffff00\">", $string);
	$string = str_replace("[cyan]", "<span style=\"color : #00ffff\">", $string);
	$string = str_replace("[/red]", "</span>", $string);
	$string = str_replace("[/blue]", "</span>", $string);
	$string = str_replace("[/green]", "</span>", $string);
	$string = str_replace("[/pink]", "</span>", $string);
	$string = str_replace("[/yellow]", "</span>", $string);
	$string = str_replace("[/cyan]", "</span>", $string);
	
	//dimensione
	$string = str_replace("[size=50%]", "<span style=\"font-size: 50%;\">", $string);
	$string = str_replace("[size=75%]", "<span style=\"font-size: 75%;\">", $string);
	$string = str_replace("[size=100%]", "<span style=\"font-size: 100%;\">", $string);
	$string = str_replace("[size=150%]", "<span style=\"font-size: 150%;\">", $string);
	$string = str_replace("[size=200%]", "<span style=\"font-size: 200%;\">", $string);
	$string = str_replace("[/size]", "</span>", $string);
	
	//elenchi
	$string = str_replace("[ol]<br />", "<ol>", $string);
	$string = str_replace("[ol]", "<ol>", $string);
	$string = str_replace("[/ol]", "</ol>", $string);
	$string = str_replace("[*]", "<li>", $string);
	//per risolvere il problema dell'"a capo"
	$string = eregi_replace("\[\/\*\]\<br />", "</li>", $string);
	$string = eregi_replace("\[\/\*\]\n", "</li>", $string);
	$string = str_replace("[/*]", "</li>", $string);
	$string = str_replace("[ul]<br />", "<ul>", $string);
	$string = str_replace("[ul]", "<ul>", $string);
	$string = str_replace("[/ul]", "</ul>", $string);
	
	// WIKIPEDIA
	$items = explode("[/wp]",$string);
	for ($i = 0; $i < count($items); $i++) {
		$wp="";
		if(stristr($items[$i],"[wp")){
			$wp_lang = ereg_replace(".*\[wp lang=","",$items[$i]);
			$wp_lang = ereg_replace("\].*","",$wp_lang);
			$wp = ereg_replace(".*\[wp.*\]", "", $items[$i]);
			$wp = ereg_replace("\[/wp\].*", "", $wp);
			if ($wp != "") {
				$nuovowp="<a style=\"text-decoration: none; border-bottom: 1px dashed; color: blue;\" target=\"new\" href=\"http://$wp_lang.wikipedia.org/wiki/$wp\">$wp</a>";
			$string=str_replace("[wp lang=$wp_lang]".$wp."[/wp]", $nuovowp, $string);
			}
		}
	}

	$items = "";
	// URLs
	$items = explode("[/url]",$string);
	for ($i = 0; $i < count($items); $i++) {
		$url="";
		if(stristr($items[$i],"[url]")){
			$url = ereg_replace(".*\[url\]", "", $items[$i]);
			$url = ereg_replace("\[/url\].*", "", $url);
			if ($url != "") {
				if (stristr($url, "http://") == FALSE) {
					$nuovourl="<a target=\"new\" href=\"http://$url\">$url</a>";
				} else {
					$nuovourl="<a target=\"new\" href=\"$url\">$url</a>";
				}
			$string=str_replace("[url]".$url."[/url]", $nuovourl, $string);
			}
		}
	}

	return ($string);
}


/**
 * Crea il pannello dei pulsanti BBCODES
 *
 * Crea il pannello dei pulsanti BBCODES per inserire il testo corretto
 * nell'area di testo indicata come parametro.
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @author Marco Segato <segatom@users.sourceforge.net> | 20050906: added parameter 'area' in JS function
 * @author Bjorn Splinter <insites@gmail.com> | 20050912: added variable 'prepath', changed some '' to "" to prevent IE script errors
 * @since 2.5.7
 *
 * @param string $area Area di testo in cui inserire i BBCODES
 * @param string $where Riferimento alla root per l'esecuzione del codice: 'home' per le news, 'forum' per il forum
 * @param string $what 'formatting' per creare il pannello con i tasti di formattazione testo, 'emoticons' per le emoticons
 */
function bbcodes_panel($area, $where, $what) {
	$area    = getparam($area,PAR_NULL,SAN_FLAT);
	$where   = getparam($where,PAR_NULL,SAN_FLAT);
	$what    = getparam($what,PAR_NULL,SAN_FLAT);
	$mod    = getparam("mod",PAR_GET,SAN_FLAT);
	if (!check_path($mod,"","false")) $mod="";
	global $lang;
	// verifico provenienza della chiamata e adatto i richiami alle directories
	switch($where) {
		case "home":
			$prepath = "forum/";
		break;
		case "forum":
			$prepath = "";
		break;
	}
	// stampo la parte di pannello selezionata
	switch($what) {
		case "emoticons":
		?><a href="javascript:void(0)" onclick="javascript:insertTags('[:)]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=":)"><img src="<?=$prepath?>emoticon/01.png" border="0" alt="Happy" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[:(]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=":("><img src="<?=$prepath?>emoticon/02.png" border="0" alt="Triste"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[:o]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=":o"><img src="<?=$prepath?>emoticon/03.png" border="0" alt="sorpresa" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[:p]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=":p"><img src="<?=$prepath?>emoticon/04.png" border="0" alt="linguaccia"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[:D]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=":D"><img src="<?=$prepath?>emoticon/05.png" border="0" alt="risata" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[:!]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=":!"><img src="<?=$prepath?>emoticon/06.png" border="0" alt="indifferente"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[:O]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=":O"><img src="<?=$prepath?>emoticon/07.png" border="0" alt="sbalordito"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[8)]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="8)"><img src="<?=$prepath?>emoticon/08.png" border="0" alt="fighetto"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[;)]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title=";)"><img src="<?=$prepath?>emoticon/09.png" border="0" alt="occhiolino" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[rolleyes]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="rolleyes"><img src="<?=$prepath?>emoticon/rolleyes.png" border="0" alt="rolleyes" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[eh]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="eh"><img src="<?=$prepath?>emoticon/eh.png" border="0" alt="eh" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[neutral]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="neutral"><img src="<?=$prepath?>emoticon/neutral.png" border="0" alt="neutral"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[:x]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="mad"><img src="<?=$prepath?>emoticon/mad.png" border="0" alt="mad"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[O:)]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="angel"><img src="<?=$prepath?>emoticon/angel.png" border="0" alt="angel"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[evil]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="evil"><img src="<?=$prepath?>emoticon/evil.png" border="0" alt="evil" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[idea]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="idea"><img src="<?=$prepath?>emoticon/idea.png" border="0" alt="idea"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[bier]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="bier"><img src="<?=$prepath?>emoticon/bier.png" border="0" alt="bier"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[whistle]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="whistle"><img src="<?=$prepath?>emoticon/whistle.png" border="0" alt="whistle" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[flower]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="flower"><img src="<?=$prepath?>emoticon/flower.png" border="0" alt="flower"  /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[sboing]', '', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="sboing"><img src="<?=$prepath?>emoticon/sboing.png" border="0" alt="sboing" /></a><?
		break;
		
		case "formatting":
		?>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[b]', '[/b]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="bold"><img src="<?=$prepath?>emoticon/bold.png" border="0" alt="bold" title="bold" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[i]', '[/i]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="italic"><img src="<?=$prepath?>emoticon/italic.png" border="0" alt="italic" title="italic" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[u]', '[/u]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="underline"><img src="<?=$prepath?>emoticon/underline.png" border="0" alt="underscore" title="underscore" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[strike]', '[/strike]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="strike"><img src="<?=$prepath?>emoticon/strike.png" border="0" alt="strike" title="strike" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[left]', '[/left]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="left"><img src="<?=$prepath?>emoticon/left.png" border="0" alt="left" title="left" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[center]', '[/center]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="center"><img src="<?=$prepath?>emoticon/center.png" border="0" alt="center" title="center" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[right]', '[/right]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="right"><img src="<?=$prepath?>emoticon/right.png" border="0" alt="right" title="right" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[justify]', '[/justify]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="justify"><img src="<?=$prepath?>emoticon/justify.png" border="0" alt="justify" title="justify" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[quote]', '[/quote]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="quote"><img src="<?=$prepath?>emoticon/quote.png" border="0" alt="quote" title="quote" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[code]', '[/code]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="quote"><img src="<?=$prepath?>emoticon/code.png" border="0" alt="code" title="code" /></a>
		<? if (is_admin()){ ?>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[img]', '[/img]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="image"><img src="<?=$prepath?>emoticon/image.png" border="0" alt="image" title="image" /></a>
		<? }//fine if immagini 
		if (!is_guest()){
		?>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[mail]', '[/mail]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="mail"><img src="<?=$prepath?>emoticon/mail.png" border="0" alt="mail" title="mail" /></a>
		<? }//fine if mail ?>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[url]', '[/url]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="url"><img src="<?=$prepath?>emoticon/url.png" border="0" alt="url" title="url" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[wp lang=<?=$lang?>]', '[/wp]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="wikipedia page"><img src="<?=$prepath?>emoticon/wikipedia.png" border="0" alt="wikipedia" title="wikipedia" /></a>
		<br />
		<select name="<?=$area?>fontsize" onchange="javascript:insertTags('[size=' + this.form.<?=$area?>fontsize.options[this.form.<?=$area?>fontsize.selectedIndex].value + ']', '[/size]', '<?=$area?>'); this.form.<?=$area?>fontsize.selectedIndex=0;" >
			<option value="" selected="selected" disabled="disabled"><?=_SIZE?></option>
			<option value="50%" >50%</option>
			<option value="75%" >75%</option>
			<option value="100%" >100%</option>
			<option value="150%" >150%</option>
			<option value="200%" >200%</option>
		</select>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[red]', '[/red]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="red"><img src="<?=$prepath?>emoticon/red.png" border="0" alt="red" title="red" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[green]', '[/green]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="green"><img src="<?=$prepath?>emoticon/green.png" border="0" alt="green" title="green" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[blue]', '[/blue]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="blue"><img src="<?=$prepath?>emoticon/blue.png" border="0" alt="blue" title="blue" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[pink]', '[/pink]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="pink"><img src="<?=$prepath?>emoticon/pink.png" border="0" alt="pink" title="pink" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[yellow]', '[/yellow]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()"  title="yellow"><img src="<?=$prepath?>emoticon/yellow.png" border="0" alt="yellow" title="yellow" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[cyan]', '[/cyan]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="cyan"><img src="<?=$prepath?>emoticon/cyan.png" border="0" alt="cyan" title="cyan" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[ol]\n[*][/*]\n[*][/*]\n[*][/*]\n', '[/ol]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="olist"><img src="<?=$prepath?>emoticon/olist.png" border="0" alt="olist" title="olist" /></a>
		<a href="javascript:void(0)" onclick="javascript:insertTags('[ul]\n[*][/*]\n[*][/*]\n[*][/*]\n', '[/ul]', '<?=$area?>')" onmouseover="document.getElementsByName('<?=$area?>')[0].focus()" title="ulist"><img src="forum/emoticon/ulist.png" border="0" alt="ulist" title="ulist" /></a>
		<?
		echo "<a href=\"#\" onclick=\"Helpwindow=window.open('forum/help.php','Help','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=700,height=600,left=200,top=100')\"><img src=\"forum/emoticon/help.png\" border=\"0\" alt=\"help\" title=\"help\" /></a>";
		break;
		
		case "images":
		if (!is_admin()) return;
		if (!is_dir("sections/none_Images/")) return;
		$file = "";
		$images = array();
		$dir="";
		$dir = opendir("sections/none_Images/");
		while (($file = readdir($dir)) !== false) {
			if (eregi("\.png$|\.gif$|\.jpeg$|\.jpg$|\.bmp$",trim($file)))
			array_push($images, $file);
		}
// 		print_r($images);
		if (count($images)>0){
			?><select name="<?=$area?>images" onchange="javascript:insertTags('[img]' + this.form.<?=$area?>images.options[this.form.<?=$area?>images.selectedIndex].value, '[/img]', '<?=$area?>');this.form.<?=$area?>images.selectedIndex=0" ><?
			$image="";
			echo "<option value=\"\" selected=\"selected\" disabled=\"disabled\">Inserisci immagine</option>";
			foreach ($images as $image){
				echo "<option value=\"sections/none_Images/$image\">".basename($image)."</option>";
			}
			?></select><?
		}
		echo "&nbsp;<a href=\"index.php?mod=none_Images\" title=\"clicca per caricare delle immagini sul sito\">Carica delle immagini</a>";
		break;
	}
}


/**
 * Verifica se l'utente e' amministratore
 *
 * Funzione che verifica se l'utente che sta visualizzando la pagina e'
 * in possesso o meno delle credenziali di amministratore del sito.
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @return boolean VERO o FALSO
 */
function is_admin(){
	$myforum = getparam("myforum", PAR_COOKIE, SAN_FLAT);
	if ($myforum == "") {
		return FALSE;
	}
	if ((getlevel($myforum, "home"))=="10" AND versecid($myforum)) {
		return TRUE;
	}
	else return FALSE;
}


/**
 * Restituisce TRUE se il visitatore e' un utente regolarmente loggato
 *
 * Funzione che restituisce TRUE se il visitatore collegato al portale e' un utente regolarmente
 * registrato. Restituisce FALSE in caso contrario
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @return TRUE se l'utente collegato e' un utente normale, FALSE se e' un ospite o un amministratore
 */
function is_user(){
	$myforum = getparam("myforum", PAR_COOKIE, SAN_FLAT);
	if ($myforum == "") {
		return FALSE;
	}
	if (getlevel($myforum, "home")>"-1" AND getlevel($myforum, "home")<"10" AND versecid($myforum)) {
		return TRUE;
	}
	else return FALSE;
}


/**
 * Restituisce TRUE se l'utente collegato e' un ospite non loggato
 *
 * Questa funzione restituisce TRUE se il visitatore collegato al sito e' un semplice ospite.
 * Restituisce FALSE se si tratta di un utente o un amministratore regolarmente loggati.
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @return TRUE se l'utente collegato e' un ospite, FALSE se e' un utente normale o un amministratore
 */
function is_guest(){
	if (is_admin() or is_user())
		return FALSE;
	else return TRUE;
}


/**
 * Restituisce lo username dell'utente collegato (se valido)
 *
 * Funzione che restituisce lo username dell'utente collegato al portale. (se valido e regolarmente loggato)
 * Se l'utente collegato e' in realta' un ospite o se non e' regolarmente loggato restituisce
 * una stringa vuota.
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @return lo username dell'utente collegato
 */
function get_username(){
	if (is_guest())
		return "";
	$myforum = getparam("myforum", PAR_COOKIE, SAN_FLAT);

	if (is_alphanumeric($myforum))
		return $myforum;
	else return "";
}


/**
 * Restistuisce TRUE se l'utente collegato puo' vedere la sezione specificata da $mod
 *
 * Questa funzione restituisce TRUE se l'utente collegato al portale ha i permessi per visualizzare la sezione
 * richiesta.
 * Indicando anche il secondo parametro si possono verificare i permessi di un determinato utente.
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @param string $mod  il mod della sezione di cui verificare i permessi di visione
 * @param string $user l'utente di cui verificare i permessi. Se non viene specificato questo parametro,
 *                     o se la stringa e' vuota si verifica l'utente attualmente collegato al portale
 * @return TRUE se l'utente puo' vedere la sezione, FALSE in caso contrario
 */
function user_can_view_section($mod,$user=""){
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) return FALSE;
	if ($user==""){
		$user = getparam("myforum", PAR_COOKIE, SAN_FLAT);
	}
	else $user = getparam($user,PAR_NULL,SAN_FLAT);
	
	if (!check_username($user) and trim($user)!="") return FALSE;
	
	if (!is_dir("sections/$mod")) return FALSE;

	$sectlevel = getsectlevel($mod);
	$userlevel = getlevel($user,"home");
	
	if ($userlevel=="10") return TRUE;
	//sara' settata a true se viene rispettato il livello
	$level_ok = "";
	//sara' settata true se viene rispettato il nome utente
	$user_ok ="";
	
	
	//se non esistono ne' il file view.php ne' il file level.php
	//e la funzione load_user_view_permissions() restituisce NULL
	//allora non esistono restrizioni alla visione e l'utente puo' visualizzare
	//la sezione indicata da $mod
	if (!file_exists("sections/$mod/view.php") and !file_exists("sections/$mod/level.php")) return true;
	
	//se il primo if restituisce false, ovvero se esistono restrizioni, allora devo
	//controllare i permessi a livello utente.
	
	//VERIFICARE BENE!
	//controllo il livello
	if (!file_exists("sections/$mod/level.php"))  $level_ok = true;
	else if (file_exists("sections/$mod/level.php") and $userlevel >= $sectlevel and versecid(get_username())) $level_ok = true;
	else $level_ok = false;
	
	//controllo il permesso a livello utente
	if (!file_exists("sections/$mod/view.php"))  $user_ok = true;
	else if (in_array($user,load_user_view_permissions($mod))) $user_ok = true;
	else $user_ok = false;
	
	//tiro le somme...
	if ($level_ok == true and $user_ok == true) return true;
	else return false;
	
	return false;
}


/**
 * Restistuisce TRUE se l'utente collegato puo' vedere la sezione specificata da $mod
 *
 * Questa funzione verifica se l'utente collegato ha i permessi di scrittura nella sezione
 * passata come parametro.
 * Indicando anche il secondo parametro si possono verificare i permessi di un determinato utente.
 * La funzione non controlla i permessi di scrittura sui file a livello di filesystem: questi andranno
 * controllati a parte.
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @param string $mod  il mod della sezione di cui verificare i permessi di scrittura
 * @param string $user l'utente di cui verificare i permessi. Se non viene specificato questo parametro,
 *                     o se la stringa e' vuota si verifica l'utente attualmente collegato al portale
 * @return TRUE se l'utente puo' modificare la sezione, FALSE in caso contrario
 * NOTA: attualmente restituisce TRUE soltanto se l'utente interessato e' un amministratore
 */
function user_can_edit_section($mod,$user=""){
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) return FALSE;
	if ($user==""){
		$user = get_username();
	}
// 	else $user = get_username();
	if (!check_username($user)) return FALSE;
	
	if (!is_dir("sections/$mod")) return FALSE;
	
	if (is_admin()) return TRUE;
	
	if (!file_exists("sections/$mod/edit.php"))  return FALSE;
	else if (in_array($user,load_user_edit_permissions($mod))) return TRUE;
	else return FALSE;
	

	return FALSE;
}


/**
 * Restituisce l'accesskey della sezione specificata
 *
 * Funzione che restituisce l'accesskey della sezione specificata come parametro.
 * L'accesskey deve essere un singolo carattere alfanumerico e deve essere specificato nel file
 * accesskey.php eventualmente presente nella sezione specificata.
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @param string $mod il mod della sezione di cui restituire l'accesskey
 * @return l'accesskey della sezione specificata
 */
function get_access_key($mod){
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) return "";

	if (!is_dir("sections/$mod")) return "";
	if (!file_exists("sections/$mod/accesskey.php")) return "";

	$accesskey="";
	$accesskey = trim(get_file("sections/$mod/accesskey.php"));

	if (strlen($accesskey)!=1) return "";

	if (!is_alphanumeric($accesskey)) return "";

	return $accesskey;
}


/**
 * carica il profilo dell'utente specificato
 *
 * Carica il profilo dell'utente specificato e restituisce un array con i dati.
 * La struttura dell'array restituito e':
 *   $userprofile['password'] = la password codificata in md5 dell'utente
 *   $userprofile['name']     = il nome scelto dal'utente
 *   $userprofile['mail']     = l'indirizzo e-mail specificato
 *   $userprofile['homepage'] = l'home page
 *   $userprofile['work']     = il lavoro
 *   $userprofile['from']     = la provenienza geografica
 *   $userprofile['avatar']   = l'avatar scelto dall'utente
 *   $userprofile['hiddenmail'] = se impostato a "1" (default) 
 *                                nasconde la mail agli altri utenti (non agli amministratori)
 *   $userprofile['regdate']  = la data di registrazione sul portale
 *   $userprofile['regcode']  = il codice di registrazione generato dal portale per la registrazione via mail
 *   $userprofile['regmail']  = la mail utilizzata per registrarsi sul portale
 *   $userprofile['lastedit'] = la data di ultima modifica del profilo
 *   $userprofile['lasteditby'] = l'utente che ha fatto l'ultima modifica al profilo
 *   $userprofile['sign']     = la firma che sara' accodata ai messaggi
 *   $userprofile['jabber']   = il nome-utente jabber
 *   $userprofile['skype']    = il nome-utente skype
 *   $userprofile['icq']      = il contatto icq
 *   $userprofile['msn']      = il nome-utente msn
 *   $userprofile['presentation'] = la presentazione dell'utente
 *   $userprofile['level']    = il livello dell'utente
 *
 * @author Aldo Boccacci <zorba_@tin.it>
 * @since 2.5.8
 *
 * @param string $user il nome dell'utente di cui caricare il profilo
 * @return array $userprofile un array con i dati dell'utente
 */
function load_user_profile($user, $mail_activation=0){
	$user = getparam($user,PAR_NULL, SAN_FLAT);	
	$addr = getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);

	if (!is_alphanumeric($user)){
		if (trim($user)=="") return NULL;
		fnlog("load_user_profile", "$addr||".get_username()."||Username not valid!");
		return NULL;
	}
	
	if ($mail_activation!=0 and $mail_activation!=1) $mail_activation=0;
	
	if ($mail_activation==0){
		$filetoload = get_fn_dir("users")."/$user.php";
	} else if ($mail_activation==1){
		$filetoload = get_waiting_users_dir()."/$user.php";
	} else return NULL;
	
	$userprofile = array();
	if (file_exists($filetoload)){
		$xmltring = get_file($filetoload);
		//la password
		if (ctype_alnum(trim(get_xml_element("fn:password",$xmltring)))){
			$userprofile['password'] = trim(get_xml_element("fn:password",$xmltring));
		} else {
			fnlog("load_user_profile", "$addr||".get_username()."||MD5 password not valid!");
			die("md5 password is not valid!");
		}
		//il nome
		$userprofile['name'] = strip_tags(get_xml_element("fn:name",$xmltring));
		//la mail
		$userprofile['mail'] = strip_tags(get_xml_element("fn:mail",$xmltring));
		//home page
		$userprofile['homepage'] = strip_tags(get_xml_element("fn:homepage",$xmltring));
		//lavoro
		$userprofile['work'] = strip_tags(get_xml_element("fn:work",$xmltring));
		//provenienza
		$userprofile['from'] = strip_tags(get_xml_element("fn:from",$xmltring));
		//avatar
		$userprofile['avatar'] = strip_tags(get_xml_element("fn:avatar",$xmltring));
		//avatar
		$userprofile['hiddenmail'] = strip_tags(trim(get_xml_element("fn:hiddenmail",$xmltring)));
		if (!eregi("0|1",$userprofile['hiddenmail']))
			$userprofile['hiddenmail'] = "1";
		//regdate
		$userprofile['regdate'] = strip_tags(trim(get_xml_element("fn:regdate",$xmltring)));
		if (!check_var($userprofile['regdate'],"digit"))
			$userprofile['regdate'] = "0";
		//regcode
		$userprofile['regcode'] = strip_tags(trim(get_xml_element("fn:regcode",$xmltring)));
		if (!check_var($userprofile['regcode'],"digit"))
			$userprofile['regcode'] = "0";
		//la mail utilizzata per registrarsi
		$userprofile['regmail'] = strip_tags(get_xml_element("fn:regmail",$xmltring));
		//lastedit
		$userprofile['lastedit'] = strip_tags(trim(get_xml_element("fn:lastedit",$xmltring)));
		if (!check_var($userprofile['lastedit'],"digit"))
			$userprofile['lastedit'] = "0";
		//lasteditby
		$userprofile['lasteditby'] = strip_tags(trim(get_xml_element("fn:lasteditby",$xmltring)));
		if (!is_alphanumeric($userprofile['lasteditby']))
			$userprofile['lasteditby'] = "";
		//firma (ora bbcode)
		$userprofile['sign'] = strip_tags(stripslashes(get_xml_element("fn:sign",$xmltring)));
		//jabber
		$userprofile['jabber'] = strip_tags(get_xml_element("fn:jabber",$xmltring));
		//skype
		$userprofile['skype'] = strip_tags(get_xml_element("fn:skype",$xmltring));
		//icq
		$userprofile['icq'] = strip_tags(get_xml_element("fn:icq",$xmltring));
		//msn
		$userprofile['msn'] = strip_tags(get_xml_element("fn:msn",$xmltring));
		//presentazione utente
		$presentation = trim(get_xml_element("fn:presentation",$xmltring));
		$presentation = strip_tags($presentation);
		if (strlen($presentation)<500) {
			$presentation = str_replace("[img]","",$presentation);
			$presentation = str_replace("[/img]","",$presentation);
			$userprofile['presentation']=$presentation;
		}
		else $userprofile['presentation']="";
		
		//livello
		$check_level = trim(get_xml_element("fn:level",$xmltring));
		if (ctype_digit($check_level) and ($check_level>=0) and ($check_level<=10)){
			$userprofile['level'] = strip_tags(get_xml_element("fn:level",$xmltring));
		} else $userprofile['level'] = "-1";
	}
	else return NULL;

	return $userprofile;
}


/**
 * Salva il profilo dell'utente indicato con i dati passati
 * 
 * L'array ha la seguente struttura:
 *   $data['password']   = password;
 *   $data['name']       = nome;
 *   $data['mail']       = mail;
 *   $data['homepage']   = url del sito web;
 *   $data['work']       = lavoro;
 *   $data['from']       = provenienza;
 *   $data['avatar']     = avatar;
 *   $data['hiddenmail'] = se impostato a "1" (default) 
 *                         nasconde la mail agli altri utenti (non agli amministratori)
 *   $data['regdate']    = la data di registrazione sul portale
 *   $data['regcode']    = il codice di registrazione generato dal portale per la registrazione via mail
 *   $data['regmail']    = la mail utilizzata per registrarsi sul portale
 *   $data['lastedit']   = la data di ultima modifica del profilo
 *   $data['lasteditby'] = l'utente che ha fatto l'ultima modifica al profilo
 *   $data['sign']       = firma;
 *   $data['jabber']     = il nome-utente jabber
 *   $data['skype']      = il nome-utente skype
 *   $data['icq']        = il contatto icq
 *   $data['msn']        = il nome-utente msn
 *   $data['presentation'] = la presentazione dell'utente
 *   $data['level']      = livello;
 *
 * @author Aldo Boccacci
 * @since 2.6
 *
 * @param string $user l'utente di cui salvare il profilo
 * @param array $data_array l'array contenente i dati dell'utente
 */
function save_user_profile($user, $data_array,$mail_activation=0){
	$user = getparam($user,PAR_NULL, SAN_FLAT);

	if ($mail_activation!=0 and $mail_activation!=1) $mail_activation=0;
	
	//per salvare il log
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	
	if (!is_alphanumeric($user)){
		fnlog("save_user_profile", "$addr||".get_username()."||Username not valid!");
		die("username is not valid!");
	}
	
	if (!is_array($data_array)){
		fnlog("save_user_profile", "$addr||".get_username()."||The second argument must be an array!");
		die("the second argoment of the function save_user_profile is not valid!");
	}
	
	if (!is_dir(get_fn_dir("users"))){
		mkdir(get_fn_dir("users"),0777);
	}
	
	//controllo tutti i parametri
	$clean_data = array();
	
	//password
	if (isset($data_array['password'])){
		if (ctype_alnum(trim($data_array['password']))){
			$clean_data['password'] = trim($data_array['password']);
		}
		else {
			fnlog("save_user_profile", "$addr||".get_username()."||The password isn't valid!");
// 			echo "password: ".$data_array['password'];
			die("the password passed to the function save_user_profile is not valid!");
		}
	}
	else {
		fnlog("save_user_profile", "$addr||".get_username()."||The password isn't set!");
		die("the password passed to the function save_user_profile is not set!");
	}
	
	//nome
	if (isset($data_array['name'])){
		if (strlen($data_array['name'])>30)
			$data_array['name'] = substr($data_array['name'],0,31);
		$clean_data['name'] = strip_tags(fnsanitize($data_array['name']));
		$clean_data['name'] = str_replace("\n","",$clean_data['name']);
		$clean_data['name'] = str_replace("\r","",$clean_data['name']);
		if (is_spam($clean_data['name'],"words")){
			echo "<b>"._FNOME."</b> "._ISSPAM;
			echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
			die();
		}
	}
	else $clean_data['name'] = "";
	
	//mail
	if (isset($data_array['mail'])){
		$clean_data['mail'] = strip_tags(fnsanitize($data_array['mail']));
		$clean_data['mail'] = str_replace("\n","",$clean_data['mail']);
		$clean_data['mail'] = str_replace("\r","",$clean_data['mail']);
		//Spam check
		if (is_spam($clean_data['mail'],"emails")){
			echo "<b>"._FEMAIL."</b> "._ISSPAM;
			echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
			die();
		}
	}
	else $clean_data['mail'] = "";
	
	//mail
	if (isset($data_array['regmail'])){
		$clean_data['regmail'] = strip_tags(fnsanitize($data_array['regmail']));
		$clean_data['regmail'] = str_replace("\n","",$clean_data['regmail']);
		$clean_data['regmail'] = str_replace("\r","",$clean_data['regmail']);
		//Spam check
		if (is_spam($clean_data['regmail'],"emails")){
			echo "<b>"._FEMAIL."</b> "._ISSPAM;
			echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
			die();
		}
	}
	else $clean_data['regmail'] = "";
	
	
	//homepage
	if (isset($data_array['homepage'])){
		if (strlen($data_array['homepage'])>50)
			$data_array['homepage'] = substr($data_array['homepage'],0,51);
		$clean_data['homepage'] = strip_tags(fnsanitize($data_array['homepage']));
		//Spam check
		if (is_spam($clean_data['homepage'],"words")){
			echo "<b>"._FHOME."</b> "._ISSPAM;
			echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
			die();
		}
	}
	else $clean_data['homepage'] = "";
		
	//work
	if (isset($data_array['work'])){
		if (strlen($data_array['work'])>40)
			$data_array['work'] = substr($data_array['work'],0,41);
		$clean_data['work'] = strip_tags(fnsanitize($data_array['work']));
		$clean_data['work'] = str_replace("\n","",$clean_data['work']);
		$clean_data['work'] = str_replace("\r","",$clean_data['work']);
		//Spam check
		if (is_spam($clean_data['work'],"words")){
			echo "<b>"._FPROFES."</b> "._ISSPAM;
			echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
			die();
		}
	}
	else $clean_data['work'] = "";	
	
	//from
	if (isset($data_array['from'])){
		if (strlen($data_array['from'])>40)
			$data_array['from'] = substr($data_array['from'],0,41);
		$clean_data['from'] = strip_tags(fnsanitize($data_array['from']));
		$clean_data['from'] = str_replace("\n","",$clean_data['from']);
		$clean_data['from'] = str_replace("\r","",$clean_data['from']);
		//Spam check
		if (is_spam($clean_data['from'],"words")){
			echo "<b>"._FPROV."</b> "._ISSPAM;
			echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
			die();
		}
	}
	else $clean_data['from'] = "";
		
	//avatar
	if (isset($data_array['avatar'])){
		if (eregi("jpg$|jpeg$|png$|gif$",get_file_extension($data_array['avatar']))){
			$clean_data['avatar'] = strip_tags(fnsanitize($data_array['avatar']));
			$clean_data['avatar'] = str_replace("\n","",$clean_data['avatar']);
			$clean_data['avatar'] = str_replace("\r","",$clean_data['avatar']);
			//Spam check
			if (is_spam($clean_data['avatar'],"words")){
				echo "<b>"._FAVAT."</b> "._ISSPAM;
				echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
					die();
			}
		}
		else $clean_data['avatar'] = "images/blank.png";
	}
	else $clean_data['avatar'] = "images/blank.png";
	
	
	if (isset($data_array['hiddenmail'])){
		if (eregi("0|1",strip_tags(trim($data_array['hiddenmail']))))
			$clean_data['hiddenmail'] = strip_tags(trim($data_array['hiddenmail']));
		else $clean_data['hiddenmail'] = 1;
	
	}
	else $clean_data['hiddenmail'] = 1;
	
	//regdate
	if (isset($data_array['regdate'])){
		if (check_var(trim($data_array['regdate']),"digit")){
			$clean_data['regdate'] = strip_tags(trim($data_array['regdate']));
		}
		else $clean_data['regdate'] = "0";
	}
	else $clean_data['regdate'] = "0";
	
	//regdate
	if (isset($data_array['regcode'])){
		if (check_var(trim($data_array['regcode']),"digit")){
			$clean_data['regcode'] = strip_tags(trim($data_array['regcode']));
		}
		else $clean_data['regcode'] = "0";
	}
	else $clean_data['regcode'] = "0";
	
	//lastedit
	if (isset($data_array['lastedit'])){
		if (check_var(trim($data_array['lastedit']),"digit")){
			$clean_data['lastedit'] = strip_tags(trim($data_array['lastedit']));
		}
		else $clean_data['lastedit'] = "0";
	}
	else $clean_data['lastedit'] = "0";
	
	//lasteditby
	if (isset($data_array['lasteditby'])){
		if (is_alphanumeric(trim($data_array['lasteditby']))){
			$clean_data['lasteditby'] = strip_tags(trim($data_array['lasteditby']));
		}
		else $clean_data['lasteditby'] = "";
	}
	else $clean_data['lasteditby'] = "";
	
	//sign
	if (isset($data_array['sign'])){
		if (strlen($data_array['sign'])>120)
			$data_array['sign'] = substr($data_array['sign'],0,121);
		$clean_data['sign'] = strip_tags($data_array['sign']);
		//Spam check
		if (is_spam($clean_data['sign'],"words")){
			echo "<b>"._FFIRMA."</b> "._ISSPAM;
			echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
			die();
		}
	}
	else $clean_data['sign'] = "";

	//jabber
	if (isset($data_array['jabber'])){
		if (strlen($data_array['jabber'])<30){
			$clean_data['jabber'] = trim(strip_tags($data_array['jabber']));
		} else $clean_data['jabber'] = "";
	} else $clean_data['jabber'] = "";
	//skype
	if (isset($data_array['skype'])){
		if (6<strlen($data_array['skype']) and strlen($data_array['skype'])<32){
			$clean_data['skype'] = trim(strip_tags($data_array['skype']));
		} else $clean_data['skype'] = "";
	} else $clean_data['skype'] = "";
	//icq
	if (isset($data_array['icq'])){
		if (strlen($data_array['icq'])<30){
			$clean_data['icq'] = trim(strip_tags($data_array['icq']));
		} else $clean_data['icq'] = "";
	} else $clean_data['icq'] = "";
	//msn
	if (isset($data_array['msn'])){
		if (strlen($data_array['msn'])<30){
			$clean_data['msn'] = trim(strip_tags($data_array['msn']));
		} else $clean_data['msn'] = "";
	} else $clean_data['msn'] = "";
	
	//presentation
	if (isset($data_array['presentation'])){
		if (strlen($data_array['presentation'])<500){
			$clean_data['presentation']=strip_tags(str_replace("[/img]","",str_replace("[img]","",$data_array['presentation'])));
			//Spam check
			if (is_spam($clean_data['presentation'],"words")){
				echo "<b>"._FNPRESENTATION."</b> "._ISSPAM;
				echo "<div align=\"center\"><br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
				die();
			}
		}
		else $clean_data['presentation']="";
	
	}
	else $clean_data['presentation']="";
	
	//level
	if (isset($data_array['level'])){
		$data_array['level'] = trim($data_array['level']);
		if (ctype_digit($data_array['level']) and ($data_array['level']>=0) and ($data_array['level']<=10)){
			$clean_data['level'] = strip_tags(fnsanitize($data_array['level']));
		}
		else $clean_data['level'] = "0";
	}
	else $clean_data['level'] = "0";
	
// 	echo "nome:".$clean_data['name'];
//ora scrivo tutto
	$xmlstring = "<fn:userprofile>
	<fn:password>".$clean_data['password']."</fn:password>
	<fn:name>".$clean_data['name']."</fn:name>
	<fn:mail>".$clean_data['mail']."</fn:mail>
	<fn:hiddenmail>".$clean_data['hiddenmail']."</fn:hiddenmail>
	<fn:homepage>".$clean_data['homepage']."</fn:homepage>
	<fn:work>".$clean_data['work']."</fn:work>
	<fn:from>".$clean_data['from']."</fn:from>
	<fn:avatar>".$clean_data['avatar']."</fn:avatar>
	<fn:regdate>".$clean_data['regdate']."</fn:regdate>
	<fn:regcode>".$clean_data['regcode']."</fn:regcode>
	<fn:regmail>".$clean_data['regmail']."</fn:regmail>
	<fn:lastedit>".$clean_data['lastedit']."</fn:lastedit>
	<fn:lasteditby>".$clean_data['lasteditby']."</fn:lasteditby>
	<fn:sign>".$clean_data['sign']."</fn:sign>
	<fn:jabber>".$clean_data['jabber']."</fn:jabber>
	<fn:skype>".$clean_data['skype']."</fn:skype>
	<fn:icq>".$clean_data['icq']."</fn:icq>
	<fn:msn>".$clean_data['msn']."</fn:msn>
	<fn:presentation>".$clean_data['presentation']."</fn:presentation>
	<fn:level>".$clean_data['level']."</fn:level>
</fn:userprofile>";

	if (eregi("\<\?",$xmlstring) or eregi("\?\>",$xmlstring)){
		fnlog("save_user_profile", "$addr||".get_username()."||The xml profile cannot contains php tags!");
		die("data passed to the function save_user_profile contains php tags!");
	}
	
	//se e' prevista l'attivazione via mail salvo il tutto nella cartella dedicata
	if ($mail_activation==1)
		$userfile = fopen(get_waiting_users_dir()."/$user.php","w");
	else $userfile = fopen(get_fn_dir("users")."/$user.php","w");
	if (fwrite($userfile,"<?exit(1);?>\n<?xml version='1.0'?>\n$xmlstring")){
		fnlog("save_user_profile", "$addr||".get_username()."||Saved profile of the user $user");
	}
	fclose($userfile);

}


/**
 * Restituisce un array con alcuni link utili alle news
 *
 * Restituisce un array contenente alcuni link che possono essere utilizzati
 * per accedere alle funzioni di gestione delle news.
 * La struttura dell'array restituito e':
 * $ret_strings['news_infos']   = data di pubblicazione della news e numero di letture
 * $ret_strings['link_read']    = link per leggere la news completa
 * $ret_strings['link_comment'] = link per commentare la news
 * $ret_strings['link_print']   = link per stampare la news
 * $ret_strings['link_modify']  = link per modificare la news (solo amministratori)
 * $ret_strings['link_delete']  = link per eliminare la news (solo amministratori)
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @since 2.6
 *
 * @param string $news l'indirizzo assoluto della news da processare
 * @return array un array con dati/link per la news
 */
function get_news_link_array($news){
	$news = getparam($news,PAR_NULL,SAN_FLAT);
	global $theme, $giorni, $mesi, $fuso_orario;
	// publishing date
	$ret_strings['news_infos'] = _POSTATO.$giorni[date("w",$news+(3600*$fuso_orario))].date(" d ",$news+(3600*$fuso_orario));
	$tmp = date("m", $news+(3600*$fuso_orario));
	if($tmp<10)
		$tmp = str_replace("0","",$tmp);
	$ret_strings['news_infos'] .= $mesi[$tmp - 1];
	$ret_strings['news_infos'] .= date(" Y - ",$news+(3600*$fuso_orario)).date("H:",$news+(3600*$fuso_orario)).date("i",$news+(3600*$fuso_orario));
	// times read
	$string = get_file("news/$news.xml");
	$tmp = ereg_replace(".*<fn:reads>","",$string);
	$tmp = ereg_replace("</fn:reads>.*","",$tmp);
	$ret_strings['news_infos'] .= " ("._LETTO." $tmp "._VOLTE.")";
	// news title
	$title = get_xml_element("fn:title",$string);
	$title = eregi_replace("\"","&quot;",$title);
	// accesskey
	$newsarray = array();
	$handle = opendir('news');
	while ($file = readdir($handle)) {
		if (!( $file=="." or $file==".." ) and (!ereg("^\.",$file)and ($file!="CVS")) AND eregi("xml$",get_file_extension($file))) {
			$file = eregi_replace("news/","",$file);
			array_push($newsarray, eregi_replace(".xml","",$file));
		}
	}
	closedir($handle);
	if(count($newsarray)>0)
		arsort($newsarray);
	$keyarray = array();
	$accesscounter = 1;
	foreach ($newsarray as $newsfile){
		$keyarray[$newsfile] = $accesscounter;
		$accesscounter++;
	}
	// link to read the full news
	$ret_strings['link_read'] = "<img src='themes/$theme/images/read.png' alt='Read' /> ";
	$ret_strings['link_read'] .= "<a href='index.php?mod=read&amp;id=$news' title=\""._FLEGGI." news: $title\"";
	if ($keyarray[$news]>0 AND $keyarray[$news]<10)
		$ret_strings['link_read'] .= " accesskey='".$keyarray[$news]."'";
	$ret_strings['link_read'] .= "><b>"._LEGGITUTTO."</b></a>";
	// link to comment the news
	$ret_strings['link_comment'] = "<img src='themes/$theme/images/comment.png' alt='Comment' /> ";
	$ret_strings['link_comment'] .= "<a href='index.php?mod=comment&amp;id=$news' title=\""._ADDCOMM." news: $title\">";
	$commenti = count_comment($news);
	if($commenti == 0)
		$ret_strings['link_comment'] .= _COMMENTI."?</a>";
	else 
		$ret_strings['link_comment'] .= _COMMENTI." ($commenti)</a>";
	// link to print the news
	$ret_strings['link_print'] = "<img src='themes/$theme/images/print.png' alt='Print' /> ";
	$ret_strings['link_print'] .= "<a href='print.php?news=$news' target='new' title=\""._STAMPA." news: $title\">"._STAMPA."</a>";
	if(is_admin()) {
		// link to modify the news
		$ret_strings['link_modify'] = "<img src='themes/$theme/images/modify.png' alt='Modify' /> ";
		$ret_strings['link_modify'] .= "<a href='index.php?mod=none_Admin&amp;op=fnccnews&amp;news=$news' title=\""._MODIFICA." news: $title\">"._MODIFICA."</a>";
		// link to delete the news
		$ret_strings['link_delete'] = "<img src='themes/$theme/images/delete.png' alt='Delete' /> ";
		$ret_strings['link_delete'] .= "<a href='#' onclick=\"check('index.php?mod=none_Admin&amp;get_act=deletenews&amp;delnews=news/$news.xml')\" title=\""._ELIMINA." news: $title\">"._ELIMINA."</a>";
	}
	
	return($ret_strings);
}


/**
 * Restituisce un array con i componenti del footer
 *
 * Restituisce un array contenente alcuni link e stringhe che possono essere
 * utilizzati per stampare il footer del sito.
 * La struttura dell'array restituito e':
 * $ret_strings['img_fn']   = immagine con link al sito di Flatnuke
 * $ret_strings['img_w3c']  = immagine con link al sito di validazione HTML
 * $ret_strings['img_css']  = immagine con link al sito di validazione CSS
 * $ret_strings['img_rss']  = immagine con link al file RSS
 * $ret_strings['img_mail'] = immagine con link alla mail dell'amministratore
 * $ret_strings['legal']    = nota legale
 * $ret_strings['time']     = tempo di generazione della pagina
 *
 * @author Simone Vellei <simone_vellei@users.sourceforge.net>
 * @since 2.6
 *
 * @return array un array con dati/link per il footer
 */
function get_footer_array(){
	global $time1, $admin_mail, $admin, $theme;
	if(file_exists("themes/$theme/images/validate/flatnuke_powered.png")){
		$img_fn = "themes/$theme/images/validate/flatnuke_powered.png";
	} else $img_fn = "images/validate/flatnuke_powered.png";
	if(file_exists("themes/$theme/images/validate/valid_html401.png")){
		$img_w3c = "themes/$theme/images/validate/valid_html401.png";
	} else $img_w3c = "images/validate/valid_html401.png";
	if(file_exists("themes/$theme/images/validate/valid_css.png")){
		$img_css = "themes/$theme/images/validate/valid_css.png";
	} else $img_css = "images/validate/valid_css.png";
	if(file_exists("themes/$theme/images/validate/rss20_powered.png")){
		$img_rss = "themes/$theme/images/validate/rss20_powered.png";
	} else $img_rss = "images/validate/rss20_powered.png";
	if(file_exists("themes/$theme/images/validate/email.png")){
		$img_mail = "themes/$theme/images/validate/email.png";
	} else $img_mail = "images/validate/email.png";
	$ret_strings['img_fn'] = "<a href=\"http://www.flatnuke.org/\" target=\"_blank\" title=\"FlatNuke\">";
	$ret_strings['img_fn'] .= "<img align=\"middle\" border=\"0\" src=\"$img_fn\" alt=\"FlatNuke\" /></a>";
	$ret_strings['img_w3c'] = "<a href=\"http://validator.w3.org/check/referer\" target=\"_blank\" title=\"Valid HTML 4.01!\">";
	$ret_strings['img_w3c'] .= "<img align=\"middle\" border=\"0\" src=\"$img_w3c\" alt=\"Valid HTML 4.01!\" /></a>";
	$ret_strings['img_css'] = "<a href=\"http://jigsaw.w3.org/css-validator/check/referer\" target=\"_blank\" title=\"Valid CSS!\">";
	$ret_strings['img_css'] .= "<img align=\"middle\" border=\"0\" src=\"$img_css\" alt=\"Valid CSS!\" /></a>";
	$ret_strings['img_rss'] = "<a href=\"misc/backend.xml\" target=\"_blank\" title=\"Get RSS 2.0 Feed\">";
	$ret_strings['img_rss'] .= "<img align=\"middle\" border=\"0\" src=\"$img_rss\" alt=\"Get RSS 2.0 Feed\" /></a>";
	$ret_strings['img_mail'] = "<a href=\"mailto:".email_mask($admin_mail)."\" title=\"Site admin: ".$admin."\">";
	$ret_strings['img_mail'] .= "<img align=\"middle\" border=\"0\" src=\"$img_mail\" alt=\"Mail me!\" /></a>";
	$ret_strings['legal'] = _LEGAL;
	$time2 = get_microtime();
	$ret_strings['time'] = "Page generated in ".sprintf("%.4f", abs($time2 - $time1))." seconds.";

	return $ret_strings;
}


/**
 * Stampa la lista delle sottosezioni della sezione visualizzata
 * 
 * Stampa la lista formattata in una cornice delle sottosezioni della sezione corrente
 * 
 * @param string $mod la sezione di cui stampare l'indice
 * @author Aldo Boccacci (dal codice inserito in view_section())
 * @since 2.6.1
 */
function print_subsections($mod){
	
	if (file_exists("include/redefine/print_subsections.php")){
		include("include/redefine/print_subsections.php");
		return;
	}
	
	$section = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) return;
	
	global $theme;
	
	// Build the list of sub-sections and the list of files
	$modlist = array();
	$fileslist = array();
	$handle = opendir('sections/'.$section);
	while ($tmpfile = readdir($handle)) {
		if(!stristr($tmpfile,"none_")){
			if ( (!ereg("[.]",$tmpfile)) and is_dir("sections/".$section."/".$tmpfile)) {
				if (!user_can_view_section("$section/$tmpfile")) continue;
				if ($tmpfile=="CVS") continue;
				array_push($modlist, $tmpfile);
			}
			if ( (!ereg("^\.",$tmpfile)) and eregi("\.txt$|\.htm$|\.html$",trim($tmpfile))) {
				array_push($fileslist, $tmpfile);
			}
		}
	}
	closedir($handle);
	
	if(count($modlist)>0 OR count($fileslist)>0) {
		if(count($modlist)>0) sort($modlist);
		if(count($fileslist)>0) sort($fileslist);
		OpenTable();
		// print subsections
		for ($i=0; $i < sizeof($modlist); $i++) {
			if(stristr($modlist[$i],"_")){
				$tmp = eregi_replace("^[0-9]*_","",$modlist[$i]);
				$tmp = str_replace("_"," ",$tmp);
			}
			// compatibility with old Flatnuke versions...
			else $tmp = $modlist[$i];
			// Find the image that identifies the current subsection; if not found, takes the default one by the theme
			if(file_exists("sections/$section/$modlist[$i]/section.png")) {
				$subsection_image = "sections/$section/$modlist[$i]/section.png";
			} else $subsection_image = "themes/$theme/images/subsection.png";
			// print link
			echo "<img src='$subsection_image' alt='Subsection' />&nbsp;<a href='index.php?mod=".rawurlencodepath($section."/".$modlist[$i])."' title=\""._GOTOSECTION.": $tmp\"";
			if (get_access_key($section."/".$modlist[$i])!=""){
				echo " accesskey=\"".get_access_key($section."/".$modlist[$i])."\"";
			}
			echo ">$tmp</a><br />";
		}
		// print files
		for ($i=0;$i<count($fileslist);$i++){
			if (file_exists(get_fn_dir("sections")."/$section/".$fileslist[$i].".description") and file_exists(get_fn_dir("sections")."/$section/downloadsection")) continue;
			if (eregi("\.html$|\.htm$",$fileslist[$i])){
				echo "<img src=\"images/mime/kde/web.png\" alt=\"-\">&nbsp;";
			} else if (eregi("\.txt$",$fileslist[$i])){
				echo "<img src=\"images/mime/kde/text.png\" alt=\"-\">&nbsp;";
			}
			echo "<a href=\"index.php?mod=".rawurlencodepath($section)."&amp;file=".$fileslist[$i]."\" title=\""._GOTOFILE." ".$fileslist[$i]."\">".$fileslist[$i]."</a><br />";
		}
		CloseTable();
		echo "<br />";
	}
}


/**
 * Restituisce un array con i nomi di tutti gli utenti registrati sul portale indipendentemente dal livello
 * 
 * @return un array contenente i nomi degli utenti registrati sul portale
 * @author Aldo Boccacci
 * @since 2.7
 *
 */
function list_users(){
	$files = array();
	$users= array();
	$files = glob(get_fn_dir("users")."/*.php");
		for ($count=0;$count<count($files);$count++){
		$username = "";
		$username = eregi_replace("\.php$","",basename($files[$count]));
		if (!is_alphanumeric($username)) continue;
		$users[] = $username;
	}
	return $users;
}


/**
 * Elenca gli utenti di livello 10 registrati nel portale.
 * @author Aldo Boccacci
 * @since flatforum 0.1 / flatnuke 2.6.0
 */
function list_admins(){
	$admins = array();
	$users = array();
	$users = glob(get_fn_dir("users")."/*.php");
	for ($count=0;$count<count($users);$count++){
		$username = "";
		$username = eregi_replace("\.php$","",basename($users[$count]));
		if (getlevel($username, "home")=="10")
			$admins[] = $username;
	}
	
	return $admins;
}


/**
 * Carica l'elenco degli utenti autorizzati a visualizzare una certa sezione
 * 
 * @param string $mod la sezione di cui caricare i permessi
 * @return una array contenente i nomi degli utenti che possono visualizzare la sezione
 */
function load_user_view_permissions($mod){
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if  (!check_path($mod,"","false")) die();
	
	if (!is_dir("sections/$mod")) return NULL;
	if (!file_exists("sections/$mod/view.php")) return array();
	
	$string = get_file("sections/$mod/view.php");
	$string = get_xml_element("fn:view",$string);
	
	$usersarray = array();
	$checkedusers = array();
	$usersarray = get_xml_array("user",$string);
	
	$cu = 0;
	for ($cu; $cu<count($usersarray);$cu++){
		$user = "";
		$user = strip_tags(trim($usersarray[$cu]));
		if (is_alphanumeric($user))
			$checkedusers[] = $user;
	}
	
	return $checkedusers;
}


/**
 * Carica l'elenco degli utenti autorizzati a modificare una certa sezione
 * 
 * @param string $mod la sezione di cui caricare i permessi
 * @return una array contenente i nomi degli utenti che possono modificare la sezione
 */
function load_user_edit_permissions($mod){
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if  (!check_path($mod,"","false")) die();
	
	if (!is_dir("sections/$mod")) return NULL;
	if (!file_exists("sections/$mod/edit.php")) return array();
	
	$string = get_file("sections/$mod/edit.php");
	$string = get_xml_element("fn:edit",$string);
	
	$usersarray = array();
	$checkedusers = array();
	$usersarray = get_xml_array("user",$string);
	
	$cu = 0;
	for ($cu; $cu<count($usersarray);$cu++){
		$user = "";
		$user = strip_tags(trim($usersarray[$cu]));
		if (is_alphanumeric($user))
			$checkedusers[] = $user;
	}
	
	return $checkedusers;
}

/**
 * Salva la lista degli utenti autorizzati a modificare una sezione
 * 
 * @param string $mod la sezione di cui savlare i permessi
 * @param array $users l'elenco degli utenti autorizzati a modificare la sezione
 * @return una array contenente i nomi degli utenti che possono modificare la sezione
 */
function save_user_edit_permissions($mod,$users){
	if (!is_admin()) return;
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	
	if  (!check_path($mod,"","false")) die();
	if (!is_array($users)) die("\$users must be an array!");
	
	if (!is_dir("sections/$mod")) return NULL;
	if (!is_writable("sections/$mod/")){
		die(_THEDIR." sections/$mod/"._NOTWRITABLE);
	}
	
	$checkedusers = array();
	$cu =0;
	for ($cu;$cu<count($users);$cu++){
		$user = strip_tags(trim($users[$cu]));
		if (file_exists(get_fn_dir("users")."/$user.php")){
			if (is_alphanumeric($user)){
				if (!in_array($user,$checkedusers)) $checkedusers[] = $user;
			}
		}
	}
	
	if (count($checkedusers)==0){
		if (file_exists(get_fn_dir("sections")."/$mod/edit.php"))
			if (unlink(get_fn_dir("sections")."/$mod/edit.php")){
				fnlog("Section manage:","$addr||".get_username()."||Section ".strip_tags($mod)." with no more user edit permissions");
				return;
			}
			else fnlog("Section manage","$addr||".get_username()."||I'm not able to delete the file: ".get_fn_dir("sections")."/$mod/edit.php");
	}
	
	$string = "<fn:edit>\n";
	$cu = 0;
	for ($cu; $cu<count($checkedusers);$cu++){
		$string .= "\t<user>".$checkedusers[$cu]."</user>\n";
	}
	$string .= "</fn:edit>";
	
	if (eregi("\<\?",$string) or eregi("\?\>",$string))	
		die(_NONPUOI);
	
	fnwrite("sections/$mod/edit.php","<?xml version='1.0'?>\n".$string,"w",array("nonull"));
	fnlog("Section manage","$addr||".get_username()."||Save edit permission for section ".strip_tags($mod));
}


/**
 * Salva la lista degli utenti autorizzati a visualizzare una sezione
 * 
 * @param string $mod la sezione di cui salvare i permessi
 * @param array $users l'elenco degli utenti autorizzati a visualizzare la sezione
 * @return una array contenente i nomi degli utenti che possono visualizzare la sezione
 */
function save_user_view_permissions($mod,$users){
	if (!is_admin()) return;
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	if  (!check_path($mod,"","false")) die();
	if (!is_array($users)) die("\$users must be an array!");
	
	if (!is_dir("sections/$mod")) return NULL;
	if (!is_writable("sections/$mod/")){
		die(_THEDIR." sections/$mod/"._NOTWRITEBLE);
	}
	
	$checkedusers = array();
	$cu =0;
	for ($cu;$cu<count($users);$cu++){
		$user = strip_tags(trim($users[$cu]));
		if (file_exists(get_fn_dir("users")."/$user.php")){
			if (is_alphanumeric($user)){
				if (!in_array($user,$checkedusers)) $checkedusers[] = $user;
			}
		}
	}
	
	if (count($checkedusers)==0){
		if (file_exists(get_fn_dir("sections")."/$mod/view.php"))
			if (unlink(get_fn_dir("sections")."/$mod/view.php")){
				fnlog("Section manage","$addr||".get_username()."||Section ".strip_tags($mod)." with no more user view restrictions");
				return;
			}
			else fnlog("Section manage","$addr||".get_username()."||I'm not able to delete the file: ".get_fn_dir("sections")."/$mod/view.php");
	}

	$string = "<fn:view>\n";
	$cu = 0;
	for ($cu; $cu<count($checkedusers);$cu++){
		$string .= "\t<user>".$checkedusers[$cu]."</user>\n";
	}
	$string .= "</fn:view>";
	
	if (eregi("\<\?",$string) or eregi("\?\>",$string))	
		die(_NONPUOI);
	
	fnwrite("sections/$mod/view.php","<?xml version='1.0'?>\n".$string,"w",array("nonull"));
	fnlog("Section manage","$addr||".get_username()."||Save edit permission for section ".strip_tags($mod));
}


/**
 * Restituisce il percorso della cartella che contiene i profili in attesa di validazione via mail
 * e nel caso non esista la crea al volo.
 * 
 * @author Aldo Boccacci
 * @since 2.7
 * @return il percorso della cartella contenente i profili degli utenti in attesa di validazione
 */
function get_waiting_users_dir(){
	
	if (!is_dir(get_fn_dir("users"))){
		mkdir(get_fn_dir("users"),0777);
	}
	
	if (!file_exists(get_fn_dir("users")."/index.html")){
		fnwrite(get_fn_dir("users")."/index.html"," ","w",array("nonull"));
	}
	
	if (file_exists(get_fn_dir("var")."/waitingusersdir.php")){
		$code = get_xml_element("fn:waitingusersdir",get_file(get_fn_dir("var")."/waitingusersdir.php"));
		if (check_var($code,"digit")){
			//se non esiste la cartella la creo
			if (!file_exists(get_fn_dir("users")."/$code"))
				mkdir(get_fn_dir("users")."/$code",0777);
			
			//creo anche il file index.html per evitare di far vedere i file contenuti
			if (!file_exists(get_fn_dir("users")."/$code/index.html")){
				fnwrite(get_fn_dir("users")."/$code/index.html"," ","w",array());
			}
			return get_fn_dir("users")."/$code/";
		}
		else return FALSE;
	}
	else {
		//se non esite il file misc/waitingusersdir.php lo creo assieme alla cartella associata
		$random = mt_rand(0,9999999999);
		
		if (!file_exists(get_fn_dir("users")."/$random")){
			mkdir(get_fn_dir("users")."/$random",0777);
			fnwrite(get_fn_dir("users")."/index.html"," ","w",array());
			fnwrite(get_fn_dir("var")."/waitingusersdir.php","<?xml version='1.0'?>
	<fn:waitingusersdir>$random</fn:waitingusersdir>","w",array("nonull"));
		}
		
		if (!file_exists(get_fn_dir("users")."/$random/index.html")){
		fnwrite(get_fn_dir("users")."/$random/index.html"," ","w",array("nonull"));
		}
		
		return get_fn_dir("users")."/$random/";
	}

}


/**
 * Elenco email degli utenti registrati
 *
 * La funzione restituisce un array con l'elenco
 * delle email di tutti gli utenti registrati.
 * 
 * @author Marco Segato <segatom@users.sourceforge.net>
 * @since 2.7.1
 *
 * @return array Elenco delle email
 */
function list_users_emails(){
	$emails = array();
	$users  = list_users();
	for ($count=0;$count<count($users);$count++) {
		$data = load_user_profile($users[$count]);
		$user = $users[$count];
		if(trim($data['mail'])!="") {
			$emails[$user] = $data['mail'];
		}
	}
	return $emails;
}


/**
 * Restituisce un array con le email utilizzate per l'attivazione dei profili utente
 *
 * @param int $waitingusers se impostato a 0 restituisce le mail degli utenti gia' registrati, se impostata a 1
 *            restituisce le email degli utenti in attesa di validazione
 * @author Aldo Boccacci
 * @since 2.7
 */
function list_reg_emails($waitingusers=0){
	if (!eregi("1|0",$waitingusers)) $waitingusers=0;
	$emails = array();
	$files = array();
        $users = array();
	if ($waitingusers==0){
		$users = list_users();
		for ($count=0;$count<count($users);$count++){
			/*$user = $users[$count];
			$string = get_file(get_fn_dir("users")."/$user.php");
			$emails[$user] = strip_tags(get_xml_element("fn:regmail",$string));*/
			$data = load_user_profile($users[$count]);
			$user = $users[$count];
			$emails[$user] = $data['regmail'];
		}
	}
	else if($waitingusers==1){
		$users = list_waiting_users();
		for ($count=0;$count<count($users);$count++){
			$data = load_user_profile($users[$count],1);
			$user = $users[$count];
			$emails[$user] = $data['regmail'];
		}
	}
	return $emails;
}


/**
 * Restituisce un array con i nomi di tutti gli utenti in attesa di validazione via mail 
 * sul portale
 * 
 * @return un array contenente i nomi degli utenti in attesa di validazione sul portale
 * @author Aldo Boccacci
 * @since 2.7
 *
 */
function list_waiting_users(){
	$files = array();
	$users= array();
	$files = glob(get_waiting_users_dir()."/*.php");
		for ($count=0;$count<count($files);$count++){
		$username = "";
		$username = eregi_replace("\.php$","",basename($files[$count]));
		if (!is_alphanumeric($username)) continue;
		$users[] = $username;
	}
	return $users;
}


/**
 * Funzione che controlla la validita' di un indirizzo e-mail
 * 
 * @param string $mail la mail da controllare
 * @return TRUE se la mail e' valida o FALSE in caso contrario
 * @author Aldo Boccacci
 * @since 2.7
 */
function check_mail($mail){
	$mail = getparam($mail, PAR_NULL,SAN_NULL);
	return eregi("^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$",$mail);
}


/**
 * Controlla la validita' di un nome utente
 * @param string $username la mail da controllare
 * @return TRUE se il nome utente e' valido o FALSE in caso contrario
 * @author Aldo Boccacci
 * @since 2.7
 * 
 */
function check_username($username){
	$username = getparam($username, PAR_NULL,SAN_NULL);
	return is_alphanumeric($username);
}


/**
 * Interfaccia che permette di rinominare una sezione
 * 
 * @param string $mod il mod della sezione da rinominare
 * @author Aldo Boccacci
 * @since 2.7
 */
function rename_sect_interface($mod){
	if (!is_admin()) die();
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) fn_die("RENAMESECTINTERFACE","\$mod is not valid!",__FILE__,__LINE__);
	$sectname = "";
	$sectname = basename($mod);
	
	echo "<b>"._FNRENAMESECTION.":</b>";
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fnrenamesect\" />";
	echo "<input type=\"hidden\" readonly name=\"fnsectpath\" value=\"".dirname($mod)."\" />";
	echo "<input type=\"hidden\" readonly name=\"fnoldsectname\" value=\"".rawurlencodepath($sectname)."\" />";
	echo "<input type=\"text\" name=\"fnnewsectname\" size=\"20\" value=\"$sectname\" /><br/><br/>
	<input type=\"submit\" name=\"fnok\" value=\""._RENAME."\" />";
	echo "</form>";
}


/**
 * Funzione che permette di rinominare una sezione
 * @author Aldo Boccacci
 * @since 2.7
 */
function rename_section(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnsectpath = getparam("fnsectpath",PAR_POST,SAN_FLAT);
	$fnoldsectname = getparam("fnoldsectname",PAR_POST,SAN_FLAT);
	$fnnewsectname = getparam("fnnewsectname",PAR_POST,SAN_FLAT);
	$fnnewsectname = eregi_replace(" ","_",$fnnewsectname);
	
	if (!check_path($fnsectpath,"","false")) fn_die("RENAMESECTION","\$fnsectpath is not valid!",__FILE__,__LINE__);
	if (!check_path($fnoldsectname,"","false")) fn_die("RENAMESECTION","\$fnoldsectname is not valid!",__FILE__,__LINE__);
	if (!check_path($fnnewsectname,"","false")) fn_die("RENAMESECTION","\$fnnewsectname is not valid!",__FILE__,__LINE__);
	
	if (!is_dir(get_fn_dir("sections")."/$fnsectpath/$fnoldsectname")){
		echo "<div style=\"text-align: center;\">"._THEDIR." <b>$fnsectpath/$fnoldsectname</b> "._DOESNTEXISTS."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></dir>";
		return;
	}
	
	if (!is_writable(get_fn_dir("sections")."/$fnsectpath/$fnoldsectname")){
		echo _FIG_ALERTNOTWR.": ".strip_tags("$fnsectpath/$fnoldsectname");
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	if (is_dir(get_fn_dir("sections")."/$fnsectpath/$fnnewsectname")){
		echo "<div style=\"text-align: center;\">"._THEDIR." <b>$fnsectpath/$fnnewsectname</b> "._ALREADYEXISTS."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (rename(get_fn_dir("sections")."/$fnsectpath/$fnoldsectname",get_fn_dir("sections")."/$fnsectpath/$fnnewsectname")){
		echo "<div style=\"text-align: center;\"><b>"._FNSECTIONRENAMED."</b>";
		echo "<br /><a href=\"index.php?mod=$fnsectpath/$fnnewsectname\" title=\""._GOTOSECTION."\">"._GOTOSECTION." <b>$fnnewsectname</b></a></div>";
		fnlog("Section manage","$addr||".get_username()."||Section ".strip_tags($fnoldsectname)." renamed in ".strip_tags($fnnewsectname));
	}
}


/**
 * Interfaccia che permette di creare una sezione
 * 
 * @param string $mod il mod della sezione nella quale creare una sottosezione
 * @author Aldo Boccacci
 * @since 2.7
 */
function create_sect_interface($mod){
	if (!is_admin()) die();
	if (!check_path($mod,"","false")) fndie("\$mod is not valid!",__FILE__,__LINE__);
	$sectname = "";
	$sectname = basename($mod);
	
	echo "<b>"._FNCREATESUBSECTION.":</b>";
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fncreatesect\" />";
	echo "<input type=\"hidden\" readonly name=\"fnsectpath\" value=\"$mod\" />";
	echo "<input type=\"text\" name=\"fnnewsectname\" size=\"20\" value=\"\" /><br/><br/>";
	
	echo "<b>"._SECTIONTYPE."</b>&nbsp;";
	echo "<select id=\"fnsecttype\" name=\"fnsecttype\">
		<option value=\"standard\">Standard</option>
		<option value=\"download\" title=\""._DOWNLOADMAINTITLE."\">"._DOWNLOADMAIN."</option>
		<option value=\"downloadsection\" title=\""._DOWNLOADSINGLETITLE."\">"._DOWNLOADSINGLE."</option>
		<option value=\"forum\">Forum</option>
		<option value=\"gallery\">Gallery</option>";
	echo "</select><br /><br />";
	echo "<input type=\"submit\" name=\"fnok\" value=\""._CREATE."\" />";
	echo "</form>";
}


/**
 * Interfaccia che permette di creare una sezione
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function create_section(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnsectpath = getparam("fnsectpath",PAR_POST,SAN_FLAT);
	$fnnewsectname = getparam("fnnewsectname",PAR_POST,SAN_FLAT);
	$fnnewsectname = eregi_replace(" ","_",$fnnewsectname);
	$fnsecttype = getparam("fnsecttype",PAR_POST,SAN_FLAT);
	
	if (!check_path($fnsectpath,"","false")) fn_die("RENAMESECTION","\$fnsectpath is not valid!",__FILE__,__LINE__);
	if (!check_path($fnnewsectname,"","false")) fn_die("RENAMESECTION","\$fnnewsectname is not valid!",__FILE__,__LINE__);
	
	if (!is_writable(get_fn_dir("sections")."/$fnsectpath")){
		echo _FIG_ALERTNOTWR.": ".strip_tags($fnsectpath);
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	if (!is_dir(get_fn_dir("sections")."/$fnsectpath")){
		echo _THEDIR." <b>$fnsectpath</b> "._DOESNTEXISTS."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	if (mkdir(get_fn_dir("sections")."/$fnsectpath/$fnnewsectname",0777)){
		fnwrite(get_fn_dir("sections")."/$fnsectpath/$fnnewsectname/section.php"," ","w",array());
		echo "<div style=\"text-align: center;\"><b>"._FNSECTIONCREATED."</b>";
		echo "<br /><a href=\"index.php?mod=$fnsectpath/$fnnewsectname\" title=\""._GOTOSECTION."\">"._GOTOSECTION." <b>$fnnewsectname</b></a></div>";
		fnlog("Section manage","$addr||".get_username()."||Section created: ".strip_tags("$fnsectpath/$fnnewsectname"));
		
		if ($fnsecttype=="forum"){
			set_section_type("$fnsectpath/$fnnewsectname","forum");
		}
		else if ($fnsecttype=="gallery"){
			set_section_type("$fnsectpath/$fnnewsectname","gallery");
		}
		else if ($fnsecttype=="download"){
			set_section_type("$fnsectpath/$fnnewsectname","download");
		}
		else if ($fnsecttype=="downloadsection"){
			set_section_type("$fnsectpath/$fnnewsectname","downloadsection");
		}
	}
	else {
		echo "I was not able to create the section: ".strip_tags("$fnsectpath/$fnnewsectname");
	}
}


/**
 * Interfaccia per confermare l'eliminazione della sezione
 * (solo amministratori)
 * 
 * @param string $mod il $mod della sezione da eliminare
 * @author Aldo Boccacci
 * @since 2.7
 */
function delete_sect_interface($mod){
	if (!is_admin()) die();
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) fndie("\$mod is not valid!",__FILE__,__LINE__);
	echo _FNDELETESECTION.": <b>$mod</b><br /><br />";
	
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fndeletesect\" />";
	echo "<input type=\"hidden\" readonly name=\"fnsectpath\" value=\"$mod\" />
	<input type=\"submit\" name=\"fnok\" value=\""._FNDELETESECTION."\" />";
	echo "</form>";
}


/**
 * Funzione che si occupa di eliminare una sezione
 * 
 * @author Aldo Boccacci
 * @since 2.7
 */
function delete_section(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnsectpath = getparam("fnsectpath",PAR_POST,SAN_FLAT);
	$updir = dirname($fnsectpath);
	
	if (!is_dir(get_fn_dir("sections")."/$updir")){
		echo _THEDIR." <b>$updir</b> "._DOESNTEXISTS."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	if (!is_writable(get_fn_dir("sections")."/$updir")){
		echo _FIG_ALERTNOTWR.": ".strip_tags($updir);
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	$subdirs = array();
	$handle = opendir("sections/$fnsectpath");
	while ($tmpfile = readdir($handle)) {
		if (!( $tmpfile=="." or $tmpfile==".." ) and is_dir("sections/$fnsectpath/$tmpfile")) {
		array_push($subdirs, $tmpfile);
		}
	}
	closedir($handle);
	
	if (count($subdirs)!=0){
		echo "The dir $fnsectpath isn't empty!";
		return;
	}
	if (rmdirr("sections/$fnsectpath")){
		echo "<div style=\"text-align: center;\"><b>"._FNSECTIONDELETED."</b>";
		echo "<br /><br /><a href=\"index.php?mod=$updir\" title=\""._GOTOSECTION." $updir\">"._GOTOSECTION." $updir</a></div>";
		
		fnlog("Section manage","$addr||".get_username()."||Deleted dir $fnsectpath");
	}
	else {
		echo "It was not possible to delete the dir $fnsectpath";
		fnlog("Section manage","$addr||".get_username()."||Error deleting dir $fnsectpath");
	}
}


/**
 * Interfaccia per creare nuovi file nelle sezioni
 *
 * @param string $mod la sezione nella quale creare il file
 * @author Aldo Boccacci
 * @since 2.7
 */
function create_file_interface($mod){
	if (!is_admin()) die();
	if (!check_path($mod,"","false")) fndie("\$mod is not valid!",__FILE__,__LINE__);
	$sectname = "";
	$sectname = basename($mod);
	
	echo "<b>"._FNCREATEFILE.":</b><br />";
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fncreatefile\" />";
	echo "<input type=\"hidden\" readonly name=\"fnsectpath\" value=\"$mod\" />";
	echo "<input type=\"text\" name=\"fnnewfilename\" size=\"20\" value=\"\" />.<select name=\"fnfileext\" id=\"fnfileext\">
	<option>html</option>
	<option>htm</option>
	<option>txt</option>
	</select>
	<br/><br/>
	<input type=\"submit\" name=\"fnok\" value=\""._CREATE."\" />";
	echo "</form>";
}


/**
 * Funzione per creare nuovi file nelle sezioni
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function create_file(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnsectpath = getparam("fnsectpath",PAR_POST,SAN_FLAT);
	$fnnewfilename = getparam("fnnewfilename",PAR_POST,SAN_FLAT);
	$fnnewfilename = eregi_replace(" ","_",$fnnewfilename);
	$fnfileext = trim(getparam("fnfileext",PAR_POST,SAN_FLAT));
	if (!eregi("^html$|^html$|^txt$|^php$",$fnfileext)) $fnfileext = "html";
	
	$fnnewfilename = "$fnnewfilename.$fnfileext";
	
	if (!check_path($fnsectpath,"","false")) fn_die("NEWFILE","\$fnsectpath is not valid!",__FILE__,__LINE__);
	if (!check_path($fnnewfilename,"","true")) fn_die("NEWFILE","\$fnnewfilename is not valid!",__FILE__,__LINE__);
	
	if (!is_writable(get_fn_dir("sections")."/$fnsectpath")){
		echo _FIG_ALERTNOTWR.": ".strip_tags($fnsectpath);
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	if (file_exists(get_fn_dir("sections")."/$fnsectpath/$fnnewfilename")){
		echo _ERROR.": "._THEFILE." <b>$fnnewfilename</b> "._ALREADYEXISTS;
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	fnwrite(get_fn_dir("sections")."/$fnsectpath/$fnnewfilename","text","w",array());
	if (file_exists(get_fn_dir("sections")."/$fnsectpath/$fnnewfilename")){
		echo "<div style=\"text-align: center;\"><b>"._FNFILECREATED."</b>";
		echo "<br /><a href=\"index.php?mod=$fnsectpath&amp;file=$fnnewfilename\" title=\""._GOTOFILE."\">"._GOTOFILE." <b>$fnnewfilename</b></a></div>";
		fnlog("Section manage","$addr||".get_username()."||File created: ".strip_tags("$fnsectpath/$fnnewfilename"));
	}
	else {
		echo "I was not able to create the file: ".strip_tags("$fnsectpath/$fnnewfilename");
	}
}


/**
 * Interfaccia per confermare l'eliminazione di un file
 * (solo amministratori)
 * 
 * @param string $file il file da eliminare
 * @author Aldo Boccacci
 * @since 2.7
 */
function delete_file_interface($file){
	if (!is_admin()) die();
	$file = getparam($file,PAR_NULL,SAN_FLAT);
	if (!check_path($file,"","true")) fndie("\$file is not valid!",__FILE__,__LINE__);
	echo _FNDELETEFILE.": <b>$file</b><br /><br />";
	
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fndeletefile\" />";
	echo "<input type=\"hidden\" readonly name=\"fnfilepath\" value=\"$file\" />
	<input type=\"submit\" name=\"fnok\" value=\""._FNDELETEFILE."\" />";
	echo "</form>";
}


/**
 * Funzione che si occupa di eliminare un file presente nelle sezioni
 * 
 * @author Aldo Boccacci
 * @since 2.7
 */
function delete_file(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnfilepath = getparam("fnfilepath",PAR_POST,SAN_FLAT);
	if (!check_path($fnfilepath,"","false")) fn_die("DELETEFILE",_NONPUOI,__FILE__,__LINE__);
	$dir = dirname($fnfilepath);
	
	if (!file_exists("sections/$fnfilepath")){
		echo "<div style=\"text-align: center;\">"._THEFILE." <b>sections/$fnfilepath</b> "._DOESNTEXISTS;
		echo "<br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
	}	
	
	if (is_writable("sections/$fnfilepath")){
		if (unlink("sections/$fnfilepath")){
			echo "<div style=\"text-align: center;\"><b>"._FNFILEDELETED."</b>";
			echo "<br /><br /><a href=\"index.php?mod=$dir\" title=\""._GOTOSECTION." $dir\">"._GOTOSECTION." $dir</a></div>";
			
			fnlog("Section manage","$addr||".get_username()."||File sections/$fnfilepath deleted");
		}
		else {
			echo "I was not able to delete the file";
		}
	}
	else {
		echo "<div align=\"center\">"._THEFILE." <b>section/$fnfilepath</b> "._NOTWRITABLE;
		echo "<br /><br /><a href=\"javascript:history.back()\">"._INDIETRO."</a></div>";
	}
}


/**
 * Interfaccia che permette di rinominare un file gestito da Flatnuke
 *
 * @param string $file il file per cui mostrare l'interfaccia
 * @author Aldo Boccacci
 * @since 2.7
 */
function rename_file_interface($file){
	if (!is_admin()) die();
	$file = getparam($file,PAR_NULL,SAN_FLAT);
	if (!check_path($file,"","true")) fndie("\$file is not valid!",__FILE__,__LINE__);
	if (basename($file)=="section.php") {
		echo "You cannot rename the file section.php";
		return;
	}
	$pathinfo = array();
	$pathinfo = pathinfo("$file");
// 	print_r($pathinfo);
	
	$filename= "";
	$filename = eregi_replace("\.".$pathinfo['extension']."$","",basename($file));
	
	echo "<b>"._FNRENAMEFILE.":</b><br /><br />";
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fnrenamefile\" />";
	echo "<input type=\"hidden\" readonly name=\"fnoldfilename\" value=\"$file\" />";
	echo "<input type=\"text\" name=\"fnnewfilename\" size=\"20\" value=\"$filename\" />.<select name=\"fnfileext\" id=\"fnfileext\">
	<option";
	if ($pathinfo['extension']=="html") echo " selected=\"selected\"";
	echo ">html</option>
	<option";
	if ($pathinfo['extension']=="htm") echo " selected=\"selected\"";
	echo ">htm</option>
	<option";
	if ($pathinfo['extension']=="txt") echo " selected=\"selected\"";
	echo ">txt</option>
	</select>
	<br/><br/>";
	echo "<input type=\"hidden\" readonly name=\"fnoldfilename\" value=\"$file\" />
	<input type=\"submit\" name=\"fnok\" value=\""._FNRENAMEFILE."\" />";
	echo "</form>";
}


/**
 * Funzione che rinomina un file presente all'interno delle sezioni
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_rename_file(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnoldfilename = getparam("fnoldfilename",PAR_POST,SAN_FLAT);
	$fnnewfilename = getparam("fnnewfilename",PAR_POST,SAN_FLAT);
	$fnfileext = getparam("fnfileext",PAR_POST,SAN_FLAT);
	if (!eregi("^html$|^htm$|^txt$",$fnfileext)) $fnfileext = "html";
	
	$fnfilepath = dirname($fnoldfilename);
	$fnnewfilename = eregi_replace(" ","_",$fnnewfilename);
	
	if (!check_path($fnfilepath,"","false")) fn_die("RENAMEFILE","\$fnfilepath is not valid!",__FILE__,__LINE__);
	if (!check_path($fnoldfilename,"","false")) fn_die("RENAMEFILE","\$fnoldfilename is not valid!",__FILE__,__LINE__);
	if (!check_path($fnnewfilename,"","false")) fn_die("RENAMEFILE","\$fnnewfilename is not valid!",__FILE__,__LINE__);
	
	if (!is_dir(get_fn_dir("sections")."/$fnfilepath")){
		echo _THEDIR." <b>$fnfilepath</b> "._DOESNTEXISTS."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a>";
		return;
	}
	
	if (!file_exists(get_fn_dir("sections")."/$fnoldfilename")){
		echo "<div style=\"text-align: center;\">"._THEFILE." <b>$fnoldfilename</b> "._DOESNTEXISTS."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (file_exists(get_fn_dir("sections")."/$fnfilepath/$fnnewfilename.$fnfileext")){
		echo "<div style=\"text-align: center;\">"._THEFILE." <b>$fnnewfilename.$fnfileext</b> "._ALREADYEXISTS."!";
		echo "<br /><br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (rename(get_fn_dir("sections")."/$fnoldfilename",get_fn_dir("sections")."/$fnfilepath/$fnnewfilename.$fnfileext")){
		echo "<div style=\"text-align: center;\"><b>"._FNFILERENAMED."</b>";
		echo "<br /><a href=\"index.php?mod=$fnfilepath&amp;file=$fnnewfilename.$fnfileext\" title=\""._GOTOFILE."\">"._GOTOFILE." <b>$fnnewfilename</b></a></div>";
		fnlog("Section manage","$addr||".get_username()."||Section ".strip_tags($fnoldfilename)." renamed in ".strip_tags($fnnewfilename));
	}
}


/**
 * Interfaccia che permette di spostare una sezione
 *
 * @param string $mod la sezione per cui mostrare l'interfaccia
 * @author Aldo Boccacci
 * @since 2.7
 */
function move_sect_interface($mod){
	if (!is_admin()) die();
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) fndie("\$mod is not valid!",__FILE__,__LINE__);
	
	echo _FNMOVESECTION.": <b>$mod</b><br /><br />";
	echo _FNCHOOSEDEST.":<br /><br />";
	
	//elenco le sezioni
	include_once("include/filesystem/DeepDir.php");
	
	$dir = new DeepDir();
	$dir->setDir(get_fn_dir("sections"));
	$dir->load();
	$dirs = array();
	$dirs = $dir->dirs;
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fnmovesect\" />";
	echo "<input type=\"hidden\" readonly name=\"fnsectpath\" value=\"$mod\" />";
	echo "<select id=\"fnsectdest\" name=\"fnsectdest\">";
	echo "<option";
	if (!is_writable(get_fn_dir("sections"))) echo " disabled=\"disabled\"";
	if (file_exists(get_fn_dir("sections")."/".basename($mod)) or is_dir(get_fn_dir("sections")."/".basename($mod))) echo " disabled=\"disabled\"";
	echo ">/</option>";
	//foreach a volte sembra dare dei problemi...
	for ($count=0;$count<count($dirs);$count++){
		$sect = $dirs[$count];
		$sect = eregi_replace("^sections/","",$sect);
		if (fn_is_system_dir($sect)) continue;
		if (eregi("/CVS$",$sect) or eregi("^CVS$",$sect)) continue;
		
		echo "<option";
		if (!is_writeable("sections/$sect")) echo " disabled=\"disabled\"";
		if (file_exists(get_fn_dir("sections")."/$sect/".basename($mod)) or is_dir(get_fn_dir("sections")."/$sect/".basename($mod))) echo " disabled=\"disabled\"";
		echo ">$sect</option>";
	}
	echo "</select><br /><br />";
	
	echo "<input type=\"submit\" name=\"fnok\" value=\""._FNMOVESECTION."\" />";
	echo "</form>";
}


/**
 * Funzione che si occupa di spostare la sezione specificata nel form
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function move_section(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnsectpath = getparam("fnsectpath",PAR_POST,SAN_FLAT);
	$fnsectdest = getparam("fnsectdest",PAR_POST,SAN_FLAT);
	if (!check_path($fnsectpath,"","false")) fn_die("MOVESECTION","\$fnsectpath is not valid!",__FILE__,__LINE__);
	if (!check_path($fnsectdest,"","false")) fn_die("MOVESECTION","\$fnsectdest is not valid!",__FILE__,__LINE__);
	
	if (fn_is_system_dir($fnsectpath)) fn_die("MOVESECTION","\$fnsectpath is a system dir of Flatnuke!",__FILE__,__LINE__);
	if (fn_is_system_dir($fnsectdest)) fn_die("MOVESECTION","\$fnsectdest is a system dir of Flatnuke!",__FILE__,__LINE__);
	
	if (!is_writable("sections/$fnsectpath")) fn_die("MOVESECTION","\$fnsectpath is not writable!",__FILE__,__LINE__);
	if (!is_writable("sections/$fnsectdest")) fn_die("MOVESECTION","\$fnsectdest is not writable!",__FILE__,__LINE__);
	
	if (file_exists("sections/$fnsectdest/".basename($fnsectpath))){
		if (is_file("sections/$fnsectdest/".basename($fnsectpath))) {
			echo "<div style=\"text-align: center;\">There is a file with the same name in the destination dir!";
			echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
			return;
		}
		else if (is_dir("sections/$fnsectdest/".basename($fnsectpath))) {
			echo "<div style=\"text-align: center;\">"._THEDIR." <b>sections/$fnsectdest/".basename($fnsectpath)."</b> "._ALREADYEXISTS;
			echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
			return;
		}
	}
	
	if (rename("sections/$fnsectpath","sections/$fnsectdest/".basename($fnsectpath))){
		echo "<div style=\"text-align: center;\"><b>"._FNSECTIONMOVED."</b><br /><br />";
		echo "<a href=\"index.php?mod=".rawurlencodepath("$fnsectdest/".basename($fnsectpath))."\" title=\""._GOTOSECTION." ".basename($fnsectpath)."\">"._GOTOSECTION." ".basename($fnsectpath)."</a></div>";
		fnlog("Section manage","$addr||".get_username()."||Section $fnsectpath moved to $fnsectdest");
	}
	else {
		echo "I was not able to move the section $fnsectpath to $fnsectdest";
		fnlog("Section manage","$addr||".get_username()."||I was not able to move the section $fnsectpath to $fnsectdest");
	}
}


/**
 * Interfaccia che permette di spostare una sezione
 *
 * @param string $file il file per cui mostrare l'interfaccia
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_move_file_interface($file){
	if (!is_admin()) die();
	$file = getparam($file,PAR_NULL,SAN_FLAT);
	if (!check_path($file,"","true")) fn_die("MOVEFILE","\$file is not valid!",__FILE__,__LINE__);
	
	echo _FNMOVEFILE.": <b>$file</b><br /><br />";
	echo _FNCHOOSEDEST.":<br /><br />";
	
	//elenco le sezioni
	include_once("include/filesystem/DeepDir.php");
	
	$dir = new DeepDir();
	$dir->setDir(get_fn_dir("sections"));
	$dir->load();
	$dirs = array();
	$dirs = $dir->dirs;
	echo "<form action=\"index.php\" method=\"POST\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fnmovefile\" />";
	echo "<input type=\"hidden\" readonly name=\"fnfilepath\" value=\"$file\" />";
	echo "<select id=\"fnsectdest\" name=\"fnsectdest\">";
	//foreach a volte sembra dare dei problemi...
	for ($count=0;$count<count($dirs);$count++){
		$sect = $dirs[$count];
		$sect = eregi_replace("^sections/","",$sect);
		if (fn_is_system_dir($sect)) continue;
		if (eregi("/CVS$",$sect) or eregi("^CVS$",$sect)) continue;
		
		echo "<option";
		if (!is_writeable("sections/$sect")) echo " disabled=\"disabled\"";
		if (file_exists(get_fn_dir("sections")."/$sect/".basename($file)) or is_dir(get_fn_dir("sections")."/$sect/".basename($file))) echo " disabled=\"disabled\"";
		echo ">$sect</option>";
	}
	echo "</select><br /><br />";
	echo "<input type=\"submit\" name=\"fnok\" value=\""._FNMOVEFILE."\" />";
	echo "</form>";
}


/**
 * Funzione che sposta un file da una sezione all'altra
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_move_file(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$fnfilepath = getparam("fnfilepath",PAR_POST,SAN_FLAT);
	$fnsectdest = getparam("fnsectdest",PAR_POST,SAN_FLAT);
	if (!check_path($fnfilepath,"","true")) fn_die("MOVEFILE","\$fnsectpath is not valid!",__FILE__,__LINE__);
	if (!check_path($fnsectdest,"","false")) fn_die("MOVESFILE","\$fnsectdest is not valid!",__FILE__,__LINE__);
	
	if (fn_is_system_dir(dirname($fnfilepath))) fn_die("MOVEFILE","\$fnfilepath is in a system dir of Flatnuke!",__FILE__,__LINE__);
	if (fn_is_system_dir($fnsectdest)) fn_die("MOVEFILE","\$fnsectdest is a system dir of Flatnuke!",__FILE__,__LINE__);
	
	if (!is_writable("sections/$fnfilepath")) fn_die("MOVEFILE","\$fnfilepath is not writable!",__FILE__,__LINE__);
	if (!is_writable("sections/$fnsectdest")) fn_die("MOVEFILE","\$fnsectdest is not writable!",__FILE__,__LINE__);
	
	if (file_exists("sections/$fnsectdest/".basename($fnfilepath))){
		if (is_dir("sections/$fnsectdest/".basename($fnsectpath))) {
			echo "<div style=\"text-align: center;\">There is a file with the same name in the destination dir!";
			echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
			return;
		}
		else if (is_file("sections/$fnsectdest/".basename($fnsectpath))) {
			echo "<div style=\"text-align: center;\">"._THEFILE." <b>sections/$fnsectdest/".basename($fnsectpath)."</b> "._ALREADYEXISTS;
			echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
			return;
		}
	}
	
	if (rename("sections/$fnfilepath","sections/$fnsectdest/".basename($fnfilepath))){
		echo "<div style=\"text-align: center;\"><b>"._FNFILEMOVED."</b><br /><br />";
		echo "<a href=\"index.php?mod=".rawurlencodepath("$fnsectdest")."&amp;file=".rawurlencode(basename($fnfilepath))."\" title=\""._GOTOFILE." ".basename($fnfilepath)."\">"._GOTOFILE." ".basename($fnfilepath)."</a></div>";
		fnlog("Section manage","$addr||".get_username()."||File $fnfilepath successfully moved to $fnsectdest");
	}
	else {
		echo "I was not able to move the file $fnfilepath to $fnsectdest";
		fnlog("Section manage","$addr||".get_username()."||I was not able to move the file $fnfilepath to $fnsectdest");
	}
}


/**
 * Interfaccia che permette di confermare la volonta' di dare all'utente selezionato il permesso 
 * di modificare la sezione specificata nel form.
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_add_edit_perm_confirm(){
	if (!is_admin()) return;
	$mod = getparam("mod",PAR_POST,SAN_FLAT);
	$user = getparam("fnadduseredit",PAR_POST,SAN_FLAT);
	
	if ($user=="---") {
		echo "<div align=\"center\"><b>"._FNCHOOSEUSER."</b><br /><br />";
		echo "<a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (!check_path($mod,"","false")) fn_die("FNADDUSERVIEWPERM","\$mod is not valid!",__FILE__,__LINE__);
	if (!check_username($user)) fn_die("FNADDUSERVIEWPERM","\$user is not valid!",__FILE__,__LINE__);
	
	if (!is_dir(get_fn_dir("sections")."/$mod")) fn_die("FNADDUSERVIEWPERM","\$mod is not a valid directory!",__FILE__,__LINE__);
	echo "<div align=\"center\"><b>"._ATTENTION."!</b><br /><br />";
	echo _FNEDITALLOW1." <b>$user</b> "._FNEDITALLOW2." <b>$mod</b>?";
	echo "<form action=\"index.php\" method=\"post\">
	<input type=\"hidden\" name=\"mod\" value=\"".rawurlencodepath($mod)."\">
	<input type=\"hidden\" name=\"user\" value=\"$user\">
	<input type=\"hidden\" name=\"fnaction\" value=\"fnaddusereditsectperm\"><br />
	<input type=\"submit\" value=\"OK (!)\" />
	<input type=\"button\" value=\""._CANCEL."\" onclick=\"javascript:history.back();\" />
	</form>
	";
	echo "</div>";
}


/**
 * Questa funzione imposta i permessi di scrittura per la sezione indicata nel form precedente
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_add_user_edit_perm(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$mod = getparam("mod",PAR_POST,SAN_FLAT);
	$mod = rawurldecode($mod);
	$user = getparam("user",PAR_POST,SAN_FLAT);
	
	if ($user=="---") {
		echo "<div align=\"center\"><b>"._FNCHOOSEUSER."</b><br /><br />";
		echo "<a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (!check_path($mod,"","false")) fn_die("FNADDUSEREDITPERM","\$mod is not valid!",__FILE__,__LINE__);
	if (!check_username($user)) fn_die("FNADDUSEREDITPERM","\$user is not valid!",__FILE__,__LINE__);
	echo "";
	if (!is_dir(get_fn_dir("sections")."/$mod")) fn_die("FNADDUSEREDITPERM","\$mod is not a valid directory!",__FILE__,__LINE__);
	
	$userseditperms = array();
	$userseditperms = load_user_edit_permissions($mod);
	if (!in_array($user,$userseditperms)){
		$userseditperms[] = $user;
// 		print_r($usersviewperms);
		save_user_edit_permissions($mod,$userseditperms);
		fnlog("Section manage","$addr||".get_username()."||Added edit permission in section $mod for user $user ");
		
		//ora proteggi il file section.php per evitare accessi diretti alla sezione senza passare da index.php
		protect_file(get_fn_dir("sections")."/$mod/section.php");
		
		echo "<div align=\"center\">";
		echo  _FNUSERADDED.": <b>$user</b><br /><br />";
		echo "<a href=\"index.php?mod=".rawurlencodepath($mod)."\" title=\""._GOTOSECTION.": ".rawurlencodepath($mod)."\">"._GOTOSECTION.": <b>$mod</b></a>";
		echo "</div>";
		echo "<meta http-equiv=\"Refresh\" content=\"1; URL=index.php?mod=".rawurlencodepath($mod)."\" >";
	}
	else {
		return;
	}
}


/**
 * Rimuove l'utente indicato nel form dall'elenco degli utenti autorizzati a modificare la sezione
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_remove_user_edit_perm(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$mod = getparam("mod",PAR_POST,SAN_FLAT);
	$mod = rawurldecode($mod);
	$user = getparam("fnremoveuseredit",PAR_POST,SAN_FLAT);
	
	if ($user=="---") {
		echo "<div align=\"center\"><b>"._FNCHOOSEUSER."</b><br /><br />";
		echo "<a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (!check_path($mod,"","false")) fn_die("FNREMOVEUSEREDITPERM","\$mod is not valid!",__FILE__,__LINE__);
	if (!check_username($user)) fn_die("FNREMOVEUSEREDITPERM","\$user is not valid!",__FILE__,__LINE__);
	
	if (!is_dir(get_fn_dir("sections")."/$mod")) fn_die("FNREMOVEUSEREDITPERM","\$mod is not a valid directory!",__FILE__,__LINE__);
	
	$userseditperms = array();
	$userseditperms = load_user_edit_permissions($mod);
	if (in_array($user,$userseditperms)){
		$newperms=array();
		for ($count=0;$count<count($userseditperms);$count++){
			if ($userseditperms[$count]==$user) continue;
			$newperms[]=$userseditperms[$count];
		}
		
// 		print_r($usersviewperms);
		save_user_edit_permissions($mod,$newperms);
		fnlog("Section manage","$addr||".get_username()."||Removed permission in section $mod for user $user ");
		echo "<div align=\"center\">";
		echo  _FNUSERREMOVED.": <b>$user</b><br /><br />";
		echo "<a href=\"index.php?mod=".rawurlencodepath($mod)."\" title=\""._GOTOSECTION.": ".rawurlencodepath($mod)."\">"._GOTOSECTION.": <b>$mod</b></a>";
		echo "</div>";
		echo "<meta http-equiv=\"Refresh\" content=\"1; URL=index.php?mod=".rawurlencodepath($mod)."\" >";
	}
	else {
		return;
	}
}


/**
 * Aggiunge l'utente specificato nel form alla lista degli utenti autorizzati a visualizzare la sezione
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_add_user_view_perm(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$mod = getparam("mod",PAR_POST,SAN_FLAT);
	$mod = rawurldecode($mod);
	$user = getparam("fnadduser",PAR_POST,SAN_FLAT);
	
	if ($user=="---") {
		echo "<div align=\"center\"><b>"._FNCHOOSEUSER."</b><br /><br />";
		echo "<a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (!check_path($mod,"","false")) fn_die("FNADDUSERVIEWPERM","\$mod is not valid!",__FILE__,__LINE__);
	if (!check_username($user)) fn_die("FNADDUSERVIEWPERM","\$user is not valid!",__FILE__,__LINE__);
	
	if (!is_dir(get_fn_dir("sections")."/$mod")) fn_die("FNADDUSERVIEWPERM","\$mod is not a valid directory!",__FILE__,__LINE__);
	
	$usersviewperms = array();
	$usersviewperms = load_user_view_permissions($mod);
	if (!in_array($user,$usersviewperms)){
		$usersviewperms[] = $user;
// 		print_r($usersviewperms);
		save_user_view_permissions($mod,$usersviewperms);
		fnlog("Section manage","$addr||".get_username()."||Added view permission in section $mod for user $user ");
		
		//ora proteggi il file section.php per evitare accessi diretti alla sezione senza passare da index.php
		protect_file(get_fn_dir("sections")."/$mod/section.php");
		
		echo "<div align=\"center\">";
		echo  _FNUSERADDED.": <b>$user</b><br /><br />";
		echo "<a href=\"index.php?mod=".rawurlencodepath($mod)."\" title=\""._GOTOSECTION.": ".rawurlencodepath($mod)."\">"._GOTOSECTION.": <b>$mod</b></a>";
		echo "</div>";
		echo "<meta http-equiv=\"Refresh\" content=\"1; URL=index.php?mod=".rawurlencodepath($mod)."\" >";
	}
	else {
		return;
	}
}


/**
 * Rimuove l'utente indicato nel form dall'elenco degli utenti autorizzati a visualizzare la sezione
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_remove_user_view_perm(){
	if (!is_admin()) return;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	$mod = getparam("mod",PAR_POST,SAN_FLAT);
	$mod = rawurldecode($mod);
	$user = getparam("fnremoveuser",PAR_POST,SAN_FLAT);
	
	if ($user=="---") {
		echo "<div align=\"center\"><b>"._FNCHOOSEUSER."</b><br /><br />";
		echo "<a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	
	if (!check_path($mod,"","false")) fn_die("FNREMOVEUSERVIEWPERM","\$mod is not valid!",__FILE__,__LINE__);
	if (!check_username($user)) fn_die("FNREMOVEUSERVIEWPERM","\$user is not valid!",__FILE__,__LINE__);
	
	if (!is_dir(get_fn_dir("sections")."/$mod")) fn_die("FNREMOVEUSERVIEWPERM","\$mod is not a valid directory!",__FILE__,__LINE__);
	
	$usersviewperms = array();
	$usersviewperms = load_user_view_permissions($mod);
	if (in_array($user,$usersviewperms)){
		$newperms=array();
		for ($count=0;$count<count($usersviewperms);$count++){
			if ($usersviewperms[$count]==$user) continue;
			$newperms[]=$usersviewperms[$count];
		}
		
// 		print_r($usersviewperms);
		save_user_view_permissions($mod,$newperms);
		fnlog("Section manage","$addr||".get_username()."||Removed view permission in section $mod for user $user ");
		echo "<div align=\"center\">";
		echo  _FNUSERREMOVED.": <b>$user</b><br /><br />";
		echo "<a href=\"index.php?mod=".rawurlencodepath($mod)."\" title=\""._GOTOSECTION.": ".rawurlencodepath($mod)."\">"._GOTOSECTION.": <b>$mod</b></a>";
		echo "</div>";
		echo "<meta http-equiv=\"Refresh\" content=\"1; URL=index.php?mod=".rawurlencodepath($mod)."\" >";
	}
	else {
		return;
	}
}


/**
 * Maschera che permette di cambiare il tipo di sezione specificata
 * 
 * @param string $mod il $mod della sezione di cui modificare il tipo
 * @author Aldo Boccacci
 * @since 2.7
 */
function choose_sect_type_interface($mod){
	if (!is_admin()) die();
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) fndie("\$mod is not valid!",__FILE__,__LINE__);
	
	if (!is_dir(get_fn_dir("sections")."/$mod")){
		echo _THEDIR." <b>".strip_tags($mod)."</b> "._DOESNTEXISTS."!";
		return;
	}
	
	echo "<b>".strip_tags($mod)."</b>: cambia il tipo di sezione<br /><br />";	
	echo "<form action=\"index.php\" method=\"post\">";
	echo "<input type=\"hidden\" readonly name=\"fnaction\" value=\"fnchangesecttype\" />";
	echo "<input type=\"hidden\" readonly name=\"fnsectpath\" value=\"".rawurlencodepath($mod)."\" />";
	echo "<select id=\"fnsecttype\" name=\"fnsecttype\">
		<option value=\"standard\">Standard</option>
		<option value=\"download\" title=\""._DOWNLOADMAINTITLE."\"";
		if (file_exists(get_fn_dir("sections")."/$mod/download"))
			echo " selected=\"selected\"";
		echo ">"._DOWNLOADMAIN."</option>
		<option value=\"downloadsection\" title=\""._DOWNLOADSINGLETITLE."\"";
		if (file_exists(get_fn_dir("sections")."/$mod/downloadsection"))
			echo " selected=\"selected\"";
		echo ">"._DOWNLOADSINGLE."</option>
		<option value=\"forum\"";
		if (file_exists(get_fn_dir("sections")."/$mod/forum"))
			echo " selected=\"selected\"";
		echo ">Forum</option>
		<option value=\"gallery\"";
		if (file_exists(get_fn_dir("sections")."/$mod/gallery"))
			echo " selected=\"selected\"";
		echo ">Gallery</option>";
	echo "</select><br /><br />";
	echo "<input type=\"submit\" name=\"fnok\" value=\"OK\" />";
	echo "</form>";
}


/**
 * Modifica il tipo di sezione
 *
 * @author Aldo Boccacci
 * @since 2.7 
 */
function change_section_type(){
	if (!is_admin()) die();
	
	$fnsectpath = getparam("fnsectpath",PAR_POST,SAN_FLAT);
	if (!check_path($fnsectpath,"","false")) fn_die("CHANGESECTTYPE","The section's name is not valid! (".strip_tags($fnsectpath).")",__FILE__,__LINE__);
	
	$secttype = getparam("fnsecttype",PAR_POST,SAN_FLAT);
	if (!eregi("^standard$|^download$|^downloadsection$|^forum$|^gallery$",$secttype)) fn_die("CHANGESECTTYPE","\$secttype is not valid!",__FILE__,__LINE__);
	
	if (!file_exists(get_fn_dir("sections")."/$fnsectpath")){
		echo "<div style=\"text-align:center;\"><b>"._ATTENTION."</b>: "._THEDIR." ".strip_tags($fnsectpath)." "._DOESNTEXISTS."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}

	if (!is_dir(get_fn_dir("sections")."/$fnsectpath")){
		echo "<div style=\"text-align:center;\"><b>"._ATTENTION."</b>: ".strip_tags($fnsectpath)." "._ISNOTADIR."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}

	if (!is_writable(get_fn_dir("sections")."/$fnsectpath")){
		echo "<div style=\"text-align:center;\"><b>"._ATTENTION."</b>: "._THEDIR." ".strip_tags($fnsectpath)." "._NOTWRITABLE."!";
		echo "<br /><a href=\"javascript:history.back();\">&lt;&lt; "._INDIETRO."</a></div>";
		return;
	}
	//gestisce lui la scrittura e gli errori
	set_section_type($fnsectpath,$secttype);
	
	echo "<br /><div style=\"text-align:center;\"><a href=\"index.php?mod=".rawurlencodepath($fnsectpath)."\" title=\""._GOTOSECTION.": ".rawurlencodepath($fnsectpath)."\">"._GOTOSECTION." <b>$fnsectpath</b></a></div>";
}


/**
 * Questa funzione mostra il pannello per amministrare la sezione corrente
 * (solo amministratori)
 * 
 * @author Aldo Boccacci
 * @since 2.7
 */
function section_admin_panel(){
	if (!is_admin()) return;
	$mod = getparam("mod",PAR_GET,SAN_FLAT);
	$file = getparam("file",PAR_GET,SAN_FLAT);
	//if ($mod=="") return;
	global $home_section;
	if ($mod=="") $mod = $home_section;

	if (!check_path($mod,"","false")) return;
	if (!check_path($file,"","true") and $file !="") return;

	echo "<input type=\"button\" value=\""._MANAGESECTION."\" onclick=\"ShowHideDiv('sectadminpanel');\" />";
	echo "<div id=\"sectadminpanel\" style=\"display:none;\" >";
	echo "<fieldset title=\""._FNMANAGESECTTITLE."\"><legend><b>"._MANAGESECTION."</b></legend>";
	echo "<i>"._MANAGESECTNOTE."</i><br /><br />";
	
	if ($file==""){
		if(is_writable("sections/$mod/section.php") and !fn_is_system_dir($mod)){
			print "<div style='float:left;padding:2px;'><form action='index.php' method='get'>
			<input type='hidden' name='mod' value='modcont' />
			<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
			<input type='hidden' name='file' value='sections/$mod/section.php' />
			<input type='submit' value='"._FNEDITSECTION."' title=\""._FNEDITSECTION."\" />";
			
			//SCELTA DELL'EDITOR
			if ((file_exists("include/plugins/editors/FCKeditor/fckeditor.php") or file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")) and file_exists("sections/$mod/section.php") and is_writable("sections/$mod/section.php")){
				echo "&nbsp;<select name=\"fneditor\" title=\""._FNCHOOSEEDITOR."\">";
				echo "<option value=\"html\" title=\""._EDITHTML."\">html</option>";
				$checkstring = get_file("sections/$mod/section.php");
				$thereisphp = eregi("\<\?",get_unprotected_text($checkstring));
				
				if (file_exists("include/plugins/editors/FCKeditor/fckeditor.php")){
					if (!$thereisphp)
						echo "<option value=\"fckeditor\" title=\""._EDITFCKEDITOR."\" selected=\"selected\">FCKeditor</option>";
					else echo "<option value=\"fckeditor\" disabled=\"disabled\">FCKeditor</option>";
				}
				
				if (file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")){
					if (!$thereisphp)
						echo "<option value=\"tinymce\">Tinymce</option>";
					else echo "<option value=\"tinymce\" disabled=\"disabled\">Tinymce</option>";
				}
				echo "</select>";
			}
			echo "</form></div>";
		}
	}
	else if ($file!=""){
		if(is_writable("sections/$mod/$file") and !fn_is_system_dir($mod)){
			echo "<div style='float:left;padding:2px;'><form action='index.php' method='get'>
			<input type='hidden' name='mod' value='modcont' />
			<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
			<input type='hidden' name='file' value='sections/$mod/$file' />
			<input type='submit' value='"._MODIFICA."' title=\""._FNEDITFILE."\" />";
			
			//SCELTA DELL'EDITOR
			if ((file_exists("include/plugins/editors/FCKeditor/fckeditor.php") or file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")) and file_exists("sections/$mod/$file") and is_writable("sections/$mod/$file")){
				echo "&nbsp;<select name=\"fneditor\" title=\""._FNCHOOSEEDITOR."\">";
				echo "<option value=\"html\" title=\""._EDITHTML."\">html</option>";
				$checkstring = get_file("sections/$mod/$file");
				$thereisphp = eregi("\<\?",get_unprotected_text($checkstring));
				
				if (file_exists("include/plugins/editors/FCKeditor/fckeditor.php")){
					if (!$thereisphp)
						echo "<option value=\"fckeditor\" title=\""._EDITFCKEDITOR."\" selected=\"selected\">FCKeditor</option>";
					else echo "<option value=\"fckeditor\" disabled=\"disabled\">FCKeditor</option>";
				}
				
				if (file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")){
					if (!$thereisphp)
						echo "<option value=\"tinymce\">Tinymce</option>";
					else echo "<option value=\"tinymce\" disabled=\"disabled\">Tinymce</option>";
				}
				echo "</select>";
			}
			echo "</form></div>";
		}
	}
	
	echo "<form action=\"index.php\" method=\"get\" style=\"float:right;padding:4px;\">";
	echo "<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />";
	echo "<input type='hidden' name='sect' value='$mod' />";
	echo "<input type='hidden' name='fnfile' value='sections/$mod/$file' />";
	echo "<select id=\"mod\" name=\"mod\" >";
	echo "<option disabled=\"disabled\" selected=\"selected\" >"._CHOOSEACTION."</option>";
	if (!fn_is_system_dir($mod) and trim($file)==""){
		echo "<option value=\"fnnewsectinterface\"";
		if (!is_writable("sections/$mod")) echo " disabled=\"disabled\"";
		echo ">"._FNCREATESUBSECTION."</option>";
		
		echo "<option value=\"fndeletesectinterface\"";
		if (!is_writable("sections/$mod")) echo " disabled=\"disabled\"";
		echo ">"._FNDELETESECTION."</option>";
		
		echo "<option value=\"fnrenamesectinterface\"";
		if (!is_writable("sections/$mod")) echo " disabled=\"disabled\"";
		echo ">"._FNRENAMESECTION."</option>";
		
		echo "<option value=\"fnmovesectinterface\"";
		if (!is_writable("sections/$mod")) echo " disabled=\"disabled\"";
		echo ">"._FNMOVESECTION."</option>";
		
		echo "<option value=\"fnchoosesecttypeinterface\"";
		if (!is_writable("sections/$mod")) echo " disabled=\"disabled\"";
		echo ">"._CHANGESECTTYPE."</option>";
		
		echo "<option disabled=\"disabled\">---</option>";
		
		echo "<option value=\"fnnewfileinterface\"";
		if (!is_writable("sections/$mod")) echo " disabled=\"disabled\"";
		echo ">"._FNCREATEFILE."</option>";
	}
	
	if (!fn_is_system_dir($mod) and trim($file)!=""){
		echo "<option value=\"fnnewfileinterface\"";
		if (!is_writable("sections/$mod")) echo " disabled=\"disabled\"";
		echo ">"._FNCREATEFILE."</option>";
		
		echo "<option value=\"fnrenamefileinterface\"";
		if (!is_writable("sections/$mod/$file")) echo " disabled=\"disabled\"";
		echo ">"._FNRENAMEFILE."</option>";
		
		echo "<option value=\"fndeletefileinterface\"";
		if (!is_writable("sections/$mod/$file")) echo " disabled=\"disabled\"";
		echo ">"._FNDELETEFILE."</option>";
		
		echo "<option value=\"fnmovefileinterface\"";
		if (!is_writable("sections/$mod/$file")) echo " disabled=\"disabled\"";
		echo ">"._FNMOVEFILE."</option>";
	}
	echo "</select>";
	echo "&nbsp;<input type=\"submit\" value=\""._EXEC."\" />";
	echo "</form></fieldset>";

	//------------------------------------------------------
	//PERMESSI VISIONE SEZIONI
	//------------------------------------------------------
	if (!fn_is_system_dir($mod)){
		echo "<fieldset title=\""._FNMANAGEVIEWPERMSTITLE."\"><legend><b>"._FNVIEWPERMS."</b></legend>";
		//stampa elenco utenti abilitati alla visione
		$usersperms = load_user_view_permissions($mod);
		if (count($usersperms)>0){
			echo "<b>"._USERS."</b>: ";
			for ($count=0;$count<count($usersperms);$count++){
				if ($count!=0) echo ", ";
				echo "<a href=\"index.php?mod=none_Login&amp;action=viewprofile&amp;user=".$usersperms[$count]."\" title=\""._VIEW_USERPROFILE."\">".$usersperms[$count]."</a>";
			}
			echo "<br /><br />";
		}
		
		//aggiungi/togli utenti
		echo "<form action='index.php' method='post'>
		<input type='hidden' name='fnaction' value='fnaddusersectperm' />
		<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
		<input type='hidden' name='mod' value='$mod' />";
		echo "<input type='submit' value='"._FNADDUSER."' title=\""._FNADDUSER."\"/>&nbsp;";
		$allusers = array();
		$allusers = list_users();
		echo "<select id=\"fnadduser\" name=\"fnadduser\">";
		echo "<option>---</option>";
		for ($count=0;$count<count($allusers);$count++){
			if (getlevel($allusers[$count],"home")=="10") continue;
			if (in_array($allusers[$count],$usersperms)) continue;
			echo "<option>".$allusers[$count]."</option>";
		}
		echo "</select>";
		echo "</form><br />";
		
		echo "<form action='index.php' method='post'>
		<input type='hidden' name='fnaction' value='fnremoveusersectperm' />
		<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
		<input type='hidden' name='mod' value='$mod' />";
		echo "<input type='submit' value='"._FNREMOVEUSER."' title=\""._FNREMOVEUSER."\"";
		if (count($usersperms)==0) echo " disabled=\"disabled\" ";
		echo "/>&nbsp;";
		echo "<select id=\"fnremoveuser\" name=\"fnremoveuser\"";
		if (count($usersperms)==0) echo " disabled=\"disabled\" ";
		echo ">";
		echo "<option>---</option>";
		for ($count=0;$count<count($usersperms);$count++){
			echo "<option>".$usersperms[$count]."</option>";
		}
		echo "</select>";
		echo "</form><br />";
		
		// manage section's level
		$level = getsectlevel($mod);
		print "<div style='float:left;'><form action='verify.php' method='post'>";
		print "<input type='hidden' name='mod' value='modlevel' />";
		print "<input type='hidden' name='section' value='$mod' />";
		print "<b>"._LEVEL."</b>: ";
		if(!is_writeable("sections/$mod")) {
			print "<select name='level' disabled></select> "._FIG_ALERTNOTWR;
			print "</form></div>";
		} else {
			print "<select name='level'>";
			print "<option value='-1'>---</option>";
			for($i=0;$i<11;$i++){
				if($level==$i)
					print "<option value='$i' selected='selected'>$i</option>";
				else
					print "<option value='$i' >$i</option>";
			}
			print "</select>";
			print "&nbsp;<input type='submit' value='OK' />";
			print "</form></div>";
		}
		echo "</fieldset>";
	}


	//------------------------------------------------------
	//SCRITTURA SEZIONI
	//------------------------------------------------------
	if (!fn_is_system_dir($mod)){
		echo "<fieldset title=\""._FNMANAGEEDITPERMSTITLE."\"><legend><b>"._FNEDITPERMS."</b></legend>";
		//stampa elenco utenti abilitati alla visione
		$usersperms = load_user_edit_permissions($mod);
		if (count($usersperms)>0){
			echo "<b>"._USERS."</b>: ";
			for ($count=0;$count<count($usersperms);$count++){
				if ($count!=0) echo ", ";
				echo "<a href=\"index.php?mod=none_Login&amp;action=viewprofile&amp;user=".$usersperms[$count]."\" title=\""._VIEW_USERPROFILE."\">".$usersperms[$count]."</a>";
			}
			echo "<br /><br />";
		}
		
		//aggiungi/togli utenti
		echo "<form action='index.php' method='post'>
		<input type='hidden' name='fnaction' value='fnaddusereditsectpermconfirm' />
		<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
		<input type='hidden' name='mod' value='$mod' />";
		echo "<input type='submit' value='"._FNADDUSER."' title=\""._FNADDUSER."\"/>&nbsp;";
		$allusers = array();
		$allusers = list_users();
		echo "<select id=\"fnadduseredit\" name=\"fnadduseredit\">";
		echo "<option>---</option>";
		for ($count=0;$count<count($allusers);$count++){
			if (getlevel($allusers[$count],"home")=="10") continue;
			if (!user_can_view_section($mod,$allusers[$count])) continue;
			if (in_array($allusers[$count],$usersperms)) continue;
			echo "<option>".$allusers[$count]."</option>";
		}
		echo "</select>";
		echo "</form><br />";
		
		echo "<form action='index.php' method='post'>
		<input type='hidden' name='fnaction' value='fnremoveusereditsectperm' />
		<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
		<input type='hidden' name='mod' value='$mod' />";
		echo "<input type='submit' value='"._FNREMOVEUSER."' title=\""._FNREMOVEUSER."\"";
		if (count($usersperms)==0) echo " disabled=\"disabled\" ";
		echo "/>&nbsp;";
		echo "<select id=\"fnremoveuseredit\" name=\"fnremoveuseredit\"";
		if (count($usersperms)==0) echo " disabled=\"disabled\" ";
		echo ">";
		echo "<option>---</option>";
		for ($count=0;$count<count($usersperms);$count++){
			echo "<option>".$usersperms[$count]."</option>";
		}
		echo "</select>";
		echo "</form><br />";
		echo "</fieldset>";
	}

	//div finale
	echo "</div>";
}


/**
 * Questa funzione mostra il pulsante modifica se l'utente e' abilitato a modificare la sezione corrente
 *
 * @author Aldo Boccacci
 * @since 2.7
 */
function section_user_edit_panel(){
	if (!is_user()) return;
	$mod = get_mod();
	$file = get_file_var();
	
	if (!user_can_view_section($mod,get_username())) return;
	if (!user_can_edit_section($mod,get_username())) return;
	
	if ($file==""){
		if(is_writable("sections/$mod/section.php") and !fn_is_system_dir($mod)){
			print "<div style='float:left;padding:2px;'><form action='index.php' method='get'>
			<input type='hidden' name='mod' value='usermodcont' />
			<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
			<input type='hidden' name='file' value='sections/$mod/section.php' />
			<input type='submit' value='"._FNEDITSECTION."' title=\""._FNEDITSECTION."\" ";
			$text = get_unprotected_text(get_file("sections/$mod/section.php"));
			if (eregi("\<\?|\?\>",$text)) echo " disabled = disabled ";
			echo "/>";
			
			//SCELTA DELL'EDITOR
			if ((file_exists("include/plugins/editors/FCKeditor/fckeditor.php") or file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")) and file_exists("sections/$mod/section.php") and is_writable("sections/$mod/section.php")){
				echo "&nbsp;<select name=\"fneditor\" title=\""._FNCHOOSEEDITOR."\">";
				echo "<option value=\"html\" title=\""._EDITHTML."\">html</option>";
				$checkstring = get_file("sections/$mod/section.php");
				$thereisphp = eregi("\<\?",get_unprotected_text($checkstring));
				
				if (file_exists("include/plugins/editors/FCKeditor/fckeditor.php")){
					if (!$thereisphp)
						echo "<option value=\"fckeditor\" title=\""._EDITFCKEDITOR."\">FCKeditor</option>";
					else echo "<option value=\"fckeditor\" disabled=\"disabled\">FCKeditor</option>";
				}
				
				if (file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")){
					if (!$thereisphp)
						echo "<option value=\"tinymce\">Tinymce</option>";
					else echo "<option value=\"tinymce\" disabled=\"disabled\">Tinymce</option>";
				}
				echo "</select>";
			}
			echo "</form></div>";
		}
	}
	else if ($file!=""){
		if(is_writable("sections/$mod/$file") and !fn_is_system_dir($mod)){
			print "<div style='float:left;padding:2px;'><form action='index.php' method='get'>
			<input type='hidden' name='mod' value='usermodcont' />
			<input type='hidden' name='from' value='".str_replace("&","&amp;",getparam("REQUEST_URI", PAR_SERVER, SAN_FLAT))."' />
			<input type='hidden' name='file' value='sections/$mod/$file' />
			<input type='submit' value='"._MODIFICA."' title=\""._FNEDITFILE."\" ";
			$text = get_unprotected_text(get_file("sections/$mod/section.php"));
			if (eregi("\<\?|\?\>",$text)) echo " disabled = disabled ";
			echo "/>";
			
			//SCELTA DELL'EDITOR
			if ((file_exists("include/plugins/editors/FCKeditor/fckeditor.php") or file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")) and file_exists("sections/$mod/$file") and is_writable("sections/$mod/$file")){
				echo "&nbsp;<select name=\"fneditor\" title=\""._FNCHOOSEEDITOR."\">";
				echo "<option value=\"html\" title=\""._EDITHTML."\">html</option>";
				$checkstring = get_file("sections/$mod/$file");
				$thereisphp = eregi("\<\?",get_unprotected_text($checkstring));
				
				if (file_exists("include/plugins/editors/FCKeditor/fckeditor.php")){
					if (!$thereisphp)
						echo "<option value=\"fckeditor\" title=\""._EDITFCKEDITOR."\">FCKeditor</option>";
					else echo "<option value=\"fckeditor\" disabled=\"disabled\">FCKeditor</option>";
				}
				
				if (file_exists("include/plugins/editors/tiny_mce/tiny_mce_gzip.js")){
					if (!$thereisphp)
						echo "<option value=\"tinymce\">Tinymce</option>";
					else echo "<option value=\"tinymce\" disabled=\"disabled\">Tinymce</option>";
				}
				echo "</select>";
			}
			echo "</form></div>";
		}
	}
}


/**
 * Questa funzione restituisce TRUE se il $mod passato come parametro e' una sezione protetta del sistema
 * che non deve essere rinominata/eliminata/spostata/modificata
 * 
 * @param string $mod il $mod della sezione da verificare
 * @return TRUE se il $mod appartiene a una sezione di sistema, FALSE in caso contrario
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_is_system_dir($mod){
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) return TRUE;
	$mod = eregi_replace("^/","",$mod);
	$mod = eregi_replace("/$","",$mod);
	if (eregi("^none_Login$|^none_Admin$|^none_Admin/none_.*$|^none_Calendar$|^none_Search$|^none_Fdplus$|^none_Images$",$mod)){
		return TRUE;
	}
	else return FALSE;
}


/**
 * Questa funzione inserisce nelle sezioni il codice php
 * adeguato ad impedire che i file vengano visualizzati direttamente,
 * scavalcando i meccanismi di protezione di flatnuke
 * 
 * @param string $path il percorso del file da proteggere
 * @author Aldo Boccacci
 * @since 2.7
 */
function protect_file($path){
	if (!check_path($path,get_fn_dir("sections"),"true")) return;
	if (!is_file($path)) return;
	if (!eregi("\.php$",$path)) return;
	$text = get_file($path);
	$string = '<?
	if (eregi("'.basename($path).'",$_SERVER[\'PHP_SELF\'])) die();
?>';
	//solo se il file non contiene gia' il codice di controllo...lo aggiungo!
	if (!ereg("\<\?.*eregi\(.*die().*\?\>",$text)){
		fnwrite($path, $string.$text,"w",array("nonull"));
	}
}


/**
 * Restituisce la stringa passata come parametro dopo aver rimosso
 * il codice di protezione inserito dalla funzione protect_file($path)
 * Funzione creata da Aldo Boccacci
 * 
 * @param string $test_protected il testo protetto
 * @return il testo senza la protezione iniziale
 * @author Aldo Boccacci
 * @since 2.7
 */
function get_unprotected_text($text_protected){
	$text_unprotected = ereg_replace("\<\?\n\tif \(eregi\(.*die\(\);\n\?\>","",$text_protected);
	return $text_unprotected;
}


/**
 * Purifica la stringa passata e la restituisce una volta eliminati tutti i codici non esplicitamente permessi
 * 
 * @param string $text il testo da purificare
 * @param string $mode la modalita' di purificazione:
 * 		 admin: se l'utente e' admin (attualmente non usata)
 * 		 user: e' permesso un numero minore di tag html
 * @author Aldo Boccacci
 * @since 2.7
 */
function fn_purge_html_string($text,$mode="user"){
	$text = getparam($text,PAR_NULL,SAN_FLAT);
	$mode = getparam($mode,PAR_NULL,SAN_FLAT);
	if (!eregi("^admin$|^user$",$mode)) return;
	
	$userallowed = array('a' => array ('href' => array (), 'title' => array (), 'rel' => array (), 'rev' => array (), 'name' => array ()),'b' => array (), 'big' => array (), 'blockquote' => array ('cite' => array ()), 'br' => array (),'div' => array ('align' => array (),'style' => array ()),'h1' => array ('align' => array ()), 'h2' => array ('align' => array ()), 'h3' => array ('align' => array ()), 'h4' => array ('align' => array ()), 'h5' => array ('align' => array ()), 'h6' => array ('align' => array ()), 'hr' => array ('align' => array (), 'noshade' => array (), 'size' => array (), 'width' => array ()), 'i' => array (),'p' => array ('align' => array ()), 'pre' => array ('width' => array ()),'strike' => array (), 'strong' => array (),'u' => array (),'ul' => array (), 'ol' => array (),'li' =>array());
	
	if (file_exists("include/php_filters/kses.php")){
		include_once("include/php_filters/kses.php");
	return kses(stripslashes($text), $userallowed);
	}
	else return strip_tags($text,"br");
}


/**
 * Imposta il tipo di sezione da visualizzare
 * 
 * @param string $mod il mod della sezione da impostare
 * @param string $type il tipo di sezione. Puo' essere: standard, download, downloadsection, forum, gallery
 * 
 * @author Aldo Boccacci
 * @since 2.7
 */
function set_section_type($mod,$type){
	$mod = getparam($mod,PAR_NULL,SAN_FLAT);
	if (!check_path($mod,"","false")) return FALSE;
	$type = getparam($type,PAR_NULL,SAN_FLAT);
	if (!eregi("^standard$|^forum$|^download$|^downloadsection$|^gallery$",$type)) return FALSE;
	$addr=getparam("REMOTE_ADDR",PAR_SERVER,SAN_FLAT);
	//prima devo azzerare la sezione
	@unlink("sections/$mod/forum");
	@unlink("sections/$mod/download");
	@unlink("sections/$mod/downloadsection");
	@unlink("sections/$mod/gallery");
	
	if ($type=="standard"){
		//ho gia' rimosso tutto piu' sopra
		fnlog("Section manage","$addr||".get_username()."||The section ".strip_tags("$mod")." now is standard");
	}
	else if ($type=="forum"){
		fnwrite("sections/$mod/forum"," ","w",array());
		fnlog("Section manage","$addr||".get_username()."||Created forum in section ".strip_tags("$mod"));
	}
	else if ($type=="gallery"){
		fnwrite("sections/$mod/gallery"," ","w",array());
		fnlog("Section manage","$addr||".get_username()."||Created gallery in section ".strip_tags("$mod"));
	}
	else if ($type=="download"){
		fnwrite("sections/$mod/download"," ","w",array());
		fnlog("Section manage","$addr||".get_username()."||Created main download section in section ".strip_tags("$mod"));
	}
	else if ($type=="downloadsection"){
		fnwrite("sections/$mod/downloadsection"," ","w",array());
		fnlog("Section manage","$addr||".get_username()."||Created single download section in section ".strip_tags("$mod"));
	}
}

?>
