<?php

######################################################################
# Modulo Splatt Forum per PHP-NUKE ver.5.X
#-------------------------
# Versione: 3.1
#
# Copyright (c) 2002 by:
#
# Giorgio Ciranni (~Splatt~)
# (http://www.splatt.it)
# (webmaster@splatt.it)
# 
#
# Supporto tecnico disponibile sul Forum di www.splatt.it
######################################################################
# PHP-NUKE Add-On 2.0 :
# =====================
#
#              PHPBB Integration 1.0.BETA
#        Brought to you by PHPNuke Add-On Team
#
# Copyright (c) 2000 by Richard Tirtadji AKA King Richard (rtirtadji@hotmail.com)
#                       Hutdik Hermawan AKA hotFix (hutdik76@hotmail.com)
# http://www.phpnuke.web.id
#
#
######################################################################
# PHPBB
#
# Copyright (C) 2000 by James Atkinson (james@totalgeek.org)
# http://www.phpbb.com
#
#
######################################################################
######################################################################
# Gestione Attachment
# -------------------------------------------------------------------
# Realizzato da  : JoyDivision
#            url : http://www.bergamoblog.it
#          email : gava@bergamoblog.it
######################################################################
# Splatt Forum is free software. You can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License.
# Splatt Forum is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA   
# 02111-1307  USA
######################################################################
# Variabili Globali :
# $AtchCookieName          = Attachment Cookie Name
# $AtchTempDir             = Attachment Temporary Directory
#                            (If you wnat to change it you must craete
#                            phisically the directory with the right permissions)
# AtchDir                  = Attachment Directory
#                            (If you wnat to change it you must craete
#                            phisically the directory with the right permissions)
# $AtchUnpermittedFileType = MIME Type File Not Accepted :
#                            Possible Coiche : File Eseguibili      - application/octet-stream
#                                              File Word            - application/msword
#                                              File Excel           - application/x-msexcel
#                                              File Testo Generali  - text/
#                                              File Testo           - text/plain
#                                              File Html            - text/html
#                                              File Zip             - application/x-zip-compressed
#                                              File Gzip            - application/gzip
#                                              File Tar             - application/x-tar
#                                              Immagini generali    - image/
#                                              Immagini Gif         - image/gif
#                                              Immagini Jpeg        - image/jpeg
#                                              (*to Coplete ??*)
#                            Insert Mime type separated by (":")
# $AtchMaxUploadSize       = Total Maximum File Size Allowed (in Kb)
######################################################################
$AtchCookieName = "AtchForumC";
$AtchTempDir = "modules/$name/downloadtemp";
$AtchDir = "modules/$name/attachment";
$AtchUnpermittedFileType = "application/octet-stream";
/*
$AtchMaxUploadSize       = 300;
*/

$result = mysql_query("select max_upfile from ${prefix}_config");
    list($max_upfile) = mysql_fetch_row($result);

$AtchMaxUploadSize = $max_upfile;

require_once("mainfile.php");
include_once("modules/$name/functions.php");
include_once("modules/$name/auth.php");

######################################################################
# Funzione : CheckCookieEnabled()
# Input    : NONE
# Outut    : True  - Cookie Abilitati
#            False - Cookie NonAbilitati
#
# Il Modulo di Upload File funziona esclusivamente se il client ha
# abilitato i cookie.
# Questa funzione verifica questa condizione tornando un Boolean di
# Vero (abilitati) o Falso (Disabilitati)
######################################################################
function CheckCookieEnabled(){
         global $AtchCookieName, $AtchOp, $RealAtchOp, $name;
         if (isset($GLOBALS["$AtchCookieName"])){
            if ($AtchOp=="testcookie"){
                $AtchOp = $RealAtchOp;
                echo "<html><body><script language='javascript'>document.location.href='modules.php?op=modload&name=$name&file=attachment&AtchOp=$AtchOp&".time()."';</script></body></html>";
                exit;
            }
            return (true);
         } else {
            if ($AtchOp=="testcookie"){
                echo "<html><body><center><h3>"._FORUMENABLECOOKIE
                    ."<br><a href='javascript:window.close();'>"._FORUMCLOSE."</a></hr3></center></body></html>";
            } else {
                $better_token = base64_encode(md5(uniqid(mt_rand())).":0");
                setcookie($AtchCookieName,"$better_token");
                echo "<html><body><script language='javascript'>document.location.href='modules.php?op=modload&name=$name&file=attachment&AtchOp=testcookie&RealAtchOp=$AtchOp&".time()."';</script></body></html>";
            }
            return (false);
         }
}

######################################################################
# Funzione : decodeAtchCookie()
# Input    : $AtchCookie - Attachment Cookie Var
# Outut    : NONE
#
# Converte la Variabile cookie in Array
######################################################################
function decodeAtchCookie($AtchCookie) {
   $xarr = base64_decode($AtchCookie);
   return(explode(":", $xarr));
}

######################################################################
# Funzione : checkUserModEnabled()
# Input    : $postid - Posti Unique Id
# Outut    : NONE
#
# Controlla se l'utente č abilitato per la modifica degli attachment
######################################################################
function checkUserModEnabled($postid){
   global $db, $moderators, $user, $prefix;
   $sql = "SELECT poster_id FROM ${prefix}_posts WHERE (post_id = '$postid')";
   if(!$result = mysql_query($sql, $db)){
       return(false);
   }
   list($puid) = mysql_fetch_array($result);
   if (isset($user)) {
      if (!is_array($user)){
           $userdata = base64_decode($user);
           $userdata = explode(":", $userdata);
      } else {
           $userdata = $user;
      }
      if ($userdata[0]==$puid){
         return(true);
      }
//$moderators= array($moderators);
      reset ($moderators);
      while(list($null, $mods) = each($moderators)) {
            while(list($mod_id, $mod_name) = each($mods)) {
                 if ($userdata[0] == $mod_id) {
                    $mod = $mod_id;
                    break 2;
                 }
            }
      }
       if ($userdata[0]==$mod){
         return(true);
       } else {
         return(false);
       }
   }
   return(false);
}

######################################################################
# Funzione : manageAttach()
# Input    : NONE
# Outut    : NONE
#
# Funzione per la gestione dei File Attachment
######################################################################
function manageAttach($IdAtchPostId=null){
   global $AtchOp, $xremove, $xcancel, $xattach, $xattachlist, $attfile, $AtchTempDir, $AtchDir, $totattsize,
          $AtchCookieName, $name, $HTTP_POST_FILES, $AtchUnpermittedFileType, $AtchMaxUploadSize,$Default_Theme, $user;
   //Cancella eventuali file spazzatura
   garbageAtchFile();
   // Recupero Informazioni del tema
   if(is_user($user)) {
     $user2 = base64_decode($user);
     $cookie = explode(":", $user2);
     if($cookie[9]=="") $cookie[9]=$Default_Theme;
     if(isset($theme)) $cookie[9]=$theme;
     if(!$file=@opendir("themes/$cookie[9]")) {
         $ThemeSel = $Default_Theme;
     } else {
         $ThemeSel = $cookie[9];
     }
   } else {
     $ThemeSel = $Default_Theme;
   }
   include_once("themes/$ThemeSel/theme.php");
   $StyleSheetTag = "<LINK REL=\"StyleSheet\" HREF=\"themes/$ThemeSel/style/style.css\" TYPE=\"text/css\">";
   $arrAtchCookie=decodeAtchCookie($GLOBALS["$AtchCookieName"]);
   if ($arrAtchCookie[1]==0 && $IdAtchPostId!=null){
       $arrAtchCookie[1]=getTotAtchSize($IdAtchPostId)/1024;
   }
   $AtchError ="";
   $AtchDisanled ="";
   if ($xremove){
      //cancella il file selezionato
      $arrAtchCookie[1] -= filesize(realpath($AtchTempDir)."/".$xattachlist)/ 1024;
	//gio
	if (isset($xattachlist)){
	//gio
      if (file_exists(realpath($AtchTempDir)."/".$xattachlist)){
         $res = unlink(realpath($AtchTempDir)."/".$xattachlist);
         $cont=-1;
	}
      foreach ($arrAtchCookie as $eleVal){
         if ($eleVal!=$xattachlist){
            $cont++;
            $NewarrAtchCookie[] =$eleVal;
         }
      }
      $arrAtchCookie = $NewarrAtchCookie;
      unset($NewarrAtchCookie);
   }
//gio
}
//gio
   if ($xcancel){
      //cancella tutti i file con lo stesso token
      $cont=-1;
      foreach ($arrAtchCookie as $eleVal){
         $cont++;
         if ($cont>1){
            if(file_exists(realpath($AtchTempDir)."/".$eleVal)){
               $res = unlink(realpath($AtchTempDir)."/".$eleVal);
            }
         } else {
           $NewarrAtchCookie[]=$eleVal;
         }
      }
      $NewarrAtchCookie[1]=0;
      $arrAtchCookie = $NewarrAtchCookie;
      unset($NewarrAtchCookie);
   }
   if ($xattach){
       if(is_uploaded_file($attfile)) {
          include("modules/$name/mime.inc.php");
          $xprog = 0;
          if ($AtchMaxUploadSize>round($arrAtchCookie[1]+(basename($HTTP_POST_FILES['attfile']['size'])/1024))){
              $AtchFileName =basename($HTTP_POST_FILES['attfile']['name']);
              $AtchFileType = $HTTP_POST_FILES['attfile']['type'];
              $arrTmp = explode(".",$AtchFileName);
              $AtchFileExt = $arrTmp[count($arrTmp)-1];
              unset($arrTmp);
              SetMime($AtchFileExt,$AtchFileType);
              $AtchFileName .=".atch";
              if (false===strpos($AtchUnpermittedFileType,$AtchFileType)){
                  while (file_exists(realpath($AtchTempDir)."/".$arrAtchCookie[0].".".$xprog.".".$AtchFileName)){
                      $xprog++;
                  }
                  $res = move_uploaded_file($attfile, realpath($AtchTempDir)."/".$arrAtchCookie[0].".".$xprog.".".$AtchFileName);
                  $arrAtchCookie[] =$arrAtchCookie[0].".".$xprog.".".$AtchFileName;
                  $arrAtchCookie[1] += basename($HTTP_POST_FILES['attfile']['size'])/ 1024;
              } else {
                  $AtchError = _FORUMATCHMERRINVFILETYPE;
              }
          } else {
              $AtchError = _FORUMATCHMERRMAXSIZEREACH;
          }
       }
   }
   $cookiestr ="";
   $cont=-1;
   foreach ($arrAtchCookie as $eleVal){
       $cont++;
       if ($cont>0){
          $cookiestr .= ":";
       }
       $cookiestr .= $eleVal;
   }
   header ("Cache-Control: no-cache, must-revalidate");
   setcookie($AtchCookieName,base64_encode($cookiestr));
   if ($xcancel){
      echo"<html><body><script language='javascript'>window.close();</script></body></html>";
      exit();
   }
   if ($AtchMaxUploadSize<$arrAtchCookie[1]){
      $AtchDisanled ="disabled";
   }
   echo "<html>\n"
       ."$StyleSheetTag\n"
       ."<body bgcolor='$bgcolor4'>";
   echo "<FORM action='modules.php?op=modload&name=$name&file=attachment&AtchOp=$AtchOp' enctype='multipart/form-data' method='post' name=doattach>\n"
       ."<INPUT TYPE='hidden' name='MAX_FILE_SIZE' value='".($AtchMaxUploadSize*1024)."'>"
       ."<TABLE border=0 cellPadding=0 cellSpacing=0 width=600><TR>\n"
       ."<TD rowspan=7 width=15>&nbsp;</TD>\n"
       ."<TD colspan=5>"._FORUMATCHMMODEINFO."\n"
       ."<HR color=#00008b size=1><BR></TD></TR>\n"
       ."<TR><TD valign=top>1.</TD>\n"
       ."<TD valign=top width='48%'>"._FORUMATCHMMODEINFO1."</TD>\n"
       ."<TD valign=top>2.</TD>\n"
       ."<TD colspan=2 width='48%'>"._FORUMATCHMMODEINFO2."<BR><BR></TD></TR>\n"
       ."<TR><TD></TD>\n"
       ."<TD rowspan=2 valign=top>"._FORUMATCHMFINDFILE.":<BR><INPUT name=attfile type=file><br><b>$AtchError</b></TD>\n"
       ."<TD></TD>\n"
       ."<TD></TD>\n"
       ."<TD>"._FORUMATCHM.":</TD></TR>\n"
       ."<TR>\n"
       ."<TD></TD>\n"
       ."<TD></TD>\n"
       ."<TD align=middle valign=top><INPUT $AtchDisanled class=sbttn name=xattach type=submit value='"._FORUMATCHMUPLOAD."'>\n"
       ."<P>\n"
       ."<INPUT class=sbttn name=xremove type=submit value='"._FORUMATCHMREMOVE."'>\n"
       ."</P></TD>\n"
       ."<TD valign=top align=left><SELECT name=xattachlist size=5>\n";
       $xpos=-1;
       foreach ($arrAtchCookie as $eleVal){
          $xpos++;
          if ($xpos>1){
             $splitEle = explode(".",$eleVal);
             $AtchName="";
             $numEle = count($splitEle);
             for($cont=2;$cont<$numEle-1;$cont++){
                 if ($cont>2){
                    $AtchName .=".";
                 }
                 $AtchName .=$splitEle[$cont];
             }
             echo "<OPTION value='$eleVal'>$AtchName</OPTION>";
          }
       }
       if ($xpos<2){
           echo "<OPTION value=nOT>"._FORUMATCHMEMPTY."</OPTION>";
       }
   echo "</SELECT></td></tr>\n"
       ."<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>"
       ._FORUMATCHMTOTSIZE." = <B>".round($arrAtchCookie[1])." K</B><br>($AtchMaxUploadSize K "._FORUMATCHMMAXSIZE.")</TD></TR>\n"
       ."<TR>\n"
       ."<TD align=right colspan=5>\n"
       ."<HR color=#00008b SIZE=1>\n"
       ."<INPUT name=xdone type=button value=' OK ' onclick='window.close();'>&nbsp;<INPUT name=xcancel type=submit value='"._FORUMATCHMCANCEL."'>\n"
       ."<P></P></TD></TR>\n"
       ."</TABLE></FORM>\n";
   echo "</body></html>";
}

######################################################################
# Funzione : ConfirmAttach()
# Input    : $idForumPost : Post Unique Id
# Outut    : NONE
#
# Trasferisce gli attachment dalla temporary Directory a quella definitiva
######################################################################
function ConfirmAttach($idForumPost){
   global $AtchCookieName, $AtchTempDir, $AtchDir;
   $arrAtchCookie=decodeAtchCookie($GLOBALS["$AtchCookieName"]);
   $cont=-1;
   foreach ($arrAtchCookie as $eleVal){
       $cont++;
       if ($cont>1){
           $splitEle = explode(".",$eleVal);
           $AtchPref=md5($idForumPost);
           $AtchName="";
           for($cont=2;$cont<count($splitEle);$cont++){
              $AtchName .=".";
              $AtchName .=$splitEle[$cont];
           }
           while (file_exists(realpath($AtchDir)."/".$AtchPref.".".$splitEle[1].$AtchName)){
              $splitEle[1]++;
           }
           $res = rename(realpath($AtchTempDir)."/".$eleVal,realpath($AtchDir)."/".$AtchPref.".".$splitEle[1].$AtchName);
       }
   }
   setcookie($AtchCookieName);
}

######################################################################
# Funzione : ShowAttach()
# Input    : $idForumPost : Post Unique Id
#            $AtchModify  : indica se abilitare l'opzione di Cancellazione
#            $FormName    : nome della form da invocare per la sottomissione
#                           della cancellazione (se lasciato vuoto verrā
#                           invocata una chiamata GET)
# Outut    : NONE
#
# Mostra gli attachment in forma tabellare
######################################################################
function ShowAttach($idForumPost,$AtchModify=false, $FormName=""){
   global $AtchDir, $name, $file, $topic, $forum, $bgcolor2;
   // Define how many Cols Must be used
   $numCol =3;
   if ($AtchModify){
      $canDelete = checkUserModEnabled($idForumPost);
      if($FormName!=""){
        echo "<script language='javascript'>
              function delAtch(AtchName, AtchNum){
                   if (confirm('"._FORUMATCHMDELCONFIRM." $AtchName ?')){
                      document.forms['$FormName'].AtchOp.value ='delAthcFile';
                      document.forms['$FormName'].AtchName.value =AtchName;
                      document.forms['$FormName'].AtchNum.value =AtchNum;
                      document.forms['$FormName'].submit();
                   }
              }
              </script>
              <input type='hidden' name='AtchOp' value=''>
              <input type='hidden' name='IdAtchPostId' value='$idForumPost'>

              <input type='hidden' name='AtchName' value=''>
              <input type='hidden' name='AtchNum' value=''>
              ";
      }
   } else {
      $canDelete = false;
   }
   $imgArr = array("avi","exe","gzip","htm","img","mp3","pdf","txt","word","xls","zip", "php");
   $ShowAtchStr="";
   $Adir = @opendir(realpath($AtchDir));
   $countTD =0;
   $countTR =1;
   while(false!==($Afile=readdir($Adir))) {
      $splitEle = explode(".",$Afile);
      if ($splitEle[0]==md5($idForumPost)){
          $AtchName = "";
          $AtchNum =$splitEle[1];
          $countTD++;
          for($cont=2;$cont<count($splitEle)-1;$cont++){
              if ($cont>2){
                  $AtchName .=".";
              }
             $AtchName .=$splitEle[$cont];
          }
          $fext =$splitEle[--$cont];
          // normalizzo l'estensione del file per recuperare l'immagine
          if ($fext=="jpg"||$fext=="gif"||$fext=="psn"||$fext=="bmp") $fext ="img";
          if ($fext=="html"||$fext=="phtml") $fext ="htm";
          if ($fext=="doc"||$fext=="rtf") $fext ="word";
          if ($fext=="tar") $fext ="gzip";
          if ($fext=="gz") $fext ="zip";
          if ($fext=="ini"||$fext=="inc") $fext ="txt";
		  if ($fext=="php3") $fext ="php";	
          if  (!in_array($fext,$imgArr)){
                $fext="unknown";
          }
          $ShowAtchStr.="<td width=30% bgcolor=$bgcolor2 align='left' valign=center>";
          if ($canDelete){
              if ($FormName==""){
                  $ShowAtchStr.="<a href=\"javascript:if(confirm('"._FORUMATCHMDELCONFIRM." $AtchName ?')){document.location.href='modules.php?op=modload&name=$name&file=$file&AtchOp=delAthcFile&postid=$idForumPost&IdAtchPostId=$idForumPost&AtchName=$AtchName&AtchNum=$AtchNum&topic=$topic&forum=$forum';}\" title='Cancella File'><img src='images/forum/attach/delete.gif' border=0></a>&nbsp;";
              } else {
                  $ShowAtchStr.="<a href=\"javascript:delAtch('$AtchName','$AtchNum');\" title='Cancella File'><img src='images/forum/attach/delete.gif' border=0></a>&nbsp;";
              }
          }
          $ShowAtchStr.="<a href='modules.php?op=modload&name=$name&file=attachment&AtchOp=get&postid=$idForumPost&AtchName=$AtchName&AtchNum=$AtchNum'   title='"._FORUMATCHMDOWNFILE."'><img src='images/forum/attach/download.gif' border=0></a>&nbsp;<a href='modules.php?op=modload&name=$name&file=attachment&AtchOp=show&postid=$idForumPost&fext=$fext&AtchName=$AtchName&AtchNum=$AtchNum'title='"._FORUMATCHMOPENFILE."' target=\"_blank\"><img src='images/forum/attach/$fext.gif' border=0></a>&nbsp;$AtchName</td>";
          if ($countTD==$numCol){
              $countTD=0;
              $countTR++;
              $ShowAtchStr.="</td><tr>";
          }
      }
   }
   if ($ShowAtchStr!=""){
       if ($countTD!=0 && $countTD!=$numCol){
          for ($td=$countTD;$td<=$numCol;$td++){
              $ShowAtchStr.="<td width=25%>&nbsp;</td>";
          }
          $ShowAtchStr.="</tr>";
       }else{
          $countTR--;
       }
       $ShowAtchStr = "<table border=0 width=100%><tr><td bgcolor=\"aqua\" width=10% rowspan=$countTR valign=middle align=right>"._FORUMATCHM." :</td>".$ShowAtchStr."</table><HR>\n";
   }
   return($ShowAtchStr);
   closedir($Adir);
}

######################################################################
# Funzione : getAtchFile()
# Input    : $postid      : Post Unique Id
#            $AtchName    : File Name
#            $AtchNum     : File Id number
#            $AtchMode    : Attachment mode
#                           must be ""  or "attachment;" (to directly download file);
# Outut    : NONE
#
# Funzione permette la visualizzazione (quando possibile) o il download
# del file richiesto.
######################################################################
function getAtchFile($postid,$AtchName,$AtchNum, $AtchMode =""){
    global $AtchDir, $name, $fext;
    include("modules/$name/mime.inc.php");
    $fname=md5($postid).".".$AtchNum.".".$AtchName.".atch";
    $arrTmp = explode(".",$AtchName);
		if($fext == "php"){
			$fsize=filesize(realpath($AtchDir)."/$fname");
		//	echo"<body bgcolor=\"E1ECEC\">";
			echo"<center><h2>$AtchName <i>( $fsize Bytes )</i></h2></center><hr>";
   			highlight_file(realpath($AtchDir)."/$fname");
			echo"<hr><center><b>Splatt Forum 3.0 PHP Code Viewer</b></center><br>";
		}
	else{
 		$AtchMimeType = GetMime($arrTmp[count($arrTmp)-1]);
    	header("Content-disposition: $AtchMode filename=$AtchName");
    	header("Content-Type: $AtchMimeType");
    	header("Content-Length: ".filesize(realpath($AtchDir)."/$fname"));
    	readfile(realpath($AtchDir)."/$fname");
	}
}

######################################################################
# Funzione : getTotAtchSize()
# Input    : $postid      : Post Unique Id
#
# Outut    : NONE
#
# Ritorna la dimensione totale degli allegati
######################################################################
function getTotAtchSize($postid){
   global $AtchDir;
   $Adir = @opendir(realpath($AtchDir));
   $tot=0;
   $positd =md5($postid);
   while(false!==($Afile=readdir($Adir))) {
         $splitEle = explode(".",$Afile);
         if ($splitEle[0]==$positd){
            $tot += filesize(realpath($AtchDir)."/$Afile");
         }
   }
   closedir($Adir);
   return($tot);
}

######################################################################
# Funzione : delAllAtchFile()
# Input    : $postid      : Post Unique Id
#
# Outut    : NONE
#
# Cancella fisicamente tutti i file Allegati al Post (controlla se
# l'utente č abilitato)
######################################################################
function delAllAtchFile($postid){
   global $AtchDir;
   if (checkUserModEnabled($postid)){
       $Adir = @opendir(realpath($AtchDir));
       $postid=md5($postid);
       while(false!==($Afile=readdir($Adir))) {
             $splitEle = explode(".",$Afile);
             if ($splitEle[0]==$postid){
                $fp=fopen(realpath($AtchDir)."/$Afile","w");
                fclose($fp);
                if(file_exists(realpath($AtchDir)."/$Afile")){
                   $res = unlink(realpath($AtchDir)."/$Afile");
                }
             }
       }
       closedir($Adir);
   }
}

######################################################################
# Funzione : delAtchFile()
# Input    : $postid      : Post Unique Id
#            $AtchName    : File Name
#            $AtchNum     : File Id number
#
# Outut    : NONE
#
# Cancella fisicamente il file richiesto (controlla se l'utente č
# abilitato)
######################################################################
function delAtchFile($postid,$AtchName,$AtchNum){
    global $AtchDir;
    if (checkUserModEnabled($postid)){
        $fname=md5($postid).".".$AtchNum.".".$AtchName.".atch";
        $fp=fopen(realpath($AtchDir)."/$fname","w");
        fclose($fp);
        if (file_exists(realpath($AtchDir)."/$fname")){
            $res = unlink(realpath($AtchDir)."/$fname");
        }
   }
}

######################################################################
# Funzione : resetAtchCookie()
# Input    : NONE
#
# Outut    : NONE
#
# Resetta la variabile Cookie cancellando eventuali file presenti
# nella directory temporanea
######################################################################
function resetAtchCookie(){
    global $AtchCookieName,$AtchTempDir;
    $better_token = base64_encode(md5(uniqid(mt_rand())).":0");
    setcookie($AtchCookieName,"$better_token");
    if (isset($GLOBALS["$AtchCookieName"])){
       $arrAtchCookie=decodeAtchCookie($GLOBALS["$AtchCookieName"]);
       //cancella tutti i file con lo stesso token
       $cont=-1;
       foreach ($arrAtchCookie as $eleVal){
         $cont++;
         if ($cont>1){
             if (file_exists(realpath($AtchTempDir)."/".$eleVal)){
                unlink(realpath($AtchTempDir)."/".$eleVal);
             }
         }
       }
    }
    $better_token = base64_encode(md5(uniqid(mt_rand())).":0");
    setcookie($AtchCookieName,"$better_token");
}

######################################################################
# Funzione : garbageAtchFile()
# Input    : NONE
#
# Outut    : NONE
#
# Controlla la Directory temporanea cancellando eventuali file
# mai confermati (file spazzatura!)
######################################################################
function garbageAtchFile(){
   global $AtchTempDir;
   $maxMinutes = 20;
   $Adir = @opendir(realpath($AtchTempDir));
   $checkTime = time() - ($maxMinutes*60);
   while(false!==($Afile=readdir($Adir))) {
      if (($Afile!=".")&&($Afile!="..")&&($Afile!="index.htm")&&($Afile!="index.html")){
         $ftime = filectime(realpath($AtchTempDir)."/".$Afile);
         if ($ftime<=$checkTime){
            if (file_exists(realpath($AtchTempDir)."/".$Afile)){
                $res = unlink(realpath($AtchTempDir)."/".$Afile);
            }
         }
      }
   }
   closedir($Adir);
}
function getAttachCode($postid=null){
   global $name;
   $poststr="";
   if($postid!=null){
     $poststr="&IdAtchPostId=$postid";
   }
   return("<input type=button name=cattach value='"._FORUMATCHM."' onclick='window.open(\"modules.php?op=modload&name=$name&file=attachment&AtchOp=manage$poststr\",\"fattach\",\"height=400,width=610,location=0,menubar=0,scrollbars=0,status=0,titlebar=0,toolbar=0,top=50,left=50\");'>&nbsp;"._FORUMATCHMCODE);
}

switch ($AtchOp){
   case "manage" :
        if (CheckCookieEnabled()){
           manageAttach($IdAtchPostId);
        }
        break;
   case "show" :
        getAtchFile($postid,$AtchName,$AtchNum);
        break;
   case "get"  :
        getAtchFile($postid,$AtchName,$AtchNum,"attachment;");
        break;
   case "delAthcFile";
        delAtchFile($IdAtchPostId,$AtchName,$AtchNum, $fext);
        break;
   case "testcookie" :
        CheckCookieEnabled();
        break;
}
?>