Page 1 sur 1

Récupération de pièce jointe

Posté : lun. 21 juil. 2014 10:25
par maxiloo
Bonjour,

J'ai fait un tour sur le forum et ne crois pas avoir vu de post concernant ce problème.

Nous effectuons un support technique sur des automates et avons besoin régulièrement d'affecter une programmation d'automate à un ticket.

Le problème se trouve dans la récupération de ce fichier, en effet il est impossible (ou je n'ai pas trouvé) de récupérer une pièce jointe affectée au ticket.

Avez-vous une solution?

Merci d'avance
[3.0.9]

Re: Récupération de pièce jointe

Posté : dim. 1 févr. 2015 12:04
par GMo
Bonjour,

Je viens de modifier mail2ticket.php

Si vous voulez vous en insprirer (attention, il y a d'autres modifs dedans ..)
Pour la récupération des pièces jointes : ligne 43 : fonctione extract_attachments
et ligne 171

Code : Tout sélectionner

<?php
################################################################################
# @Name : mail2ticket.php
# @Desc : convert mail in ticket
# @call : /index_auth.php
# @paramters : 
# @Autor : Flox
# @Create : 07/04/2013
# @Update : 16/07/2014
# @Version : 3.0.10
################################################################################

//initialize counter
$count=0;

//connexion script with database parameters
require "connect.php";

//define current time
$datetime = date("Y-m-d H:i:s");

//load parameters table
$qparameters = mysql_query("SELECT * FROM `tparameters`"); 
$rparameters= mysql_fetch_array($qparameters);

//hostname building
//$hostname = '{'.$rparameters['imap_server'].':'.$rparameters['imap_port'].'}'.$rparameters['imap_inbox'].'';
$hostname = '{'.$rparameters['imap_server'].':'.$rparameters['imap_port'].'}'.$rparameters['imap_inbox'].'';


//connect to inbox

//default case
//$inbox = imap_open($hostname,$rparameters['imap_user'],$rparameters['imap_password']) or die('Impossible de se connecter au serveur de Messagerie: ' . imap_last_error());
//$inbox = imap_open($hostname/novalidate-cert,$rparameters['imap_user'],$rparameters['imap_password']) or die('Impossible de se connecter au serveur de Messagerie: ' . imap_last_error());
$inbox = imap_open("{xxxxxxxxx/imap/novalidate-cert}",$rparameters['imap_user'],$rparameters['imap_password']) or die('Impossible de se connecter au serveur de Messagerie: ' . imap_last_error());

// Exchange 2010
//echo $rparameters['imap_port']  ;
//$inbox = imap_open('{'.$rparameters['imap_server'].':'.$rparameters['imap_port'].'/pop3/novalidate-cert}'.$rparameters['imap_inbox'].'', $rparameters['imap_user'], $rparameters['imap_password'],NULL,1,array('DISABLE_AUTHENTICATOR'=>'GSSAPI')) or die('Impossible de se connecter au serveur de Messagerie: ' . imap_last_error());

// Fonction attach :
function extract_attachments($connection, $message_number) {
   
    $attachments = array();
    $structure = imap_fetchstructure($connection, $message_number);
   
    if(isset($structure->parts) && count($structure->parts)) {
   
        for($i = 0; $i < count($structure->parts); $i++) {
   
            $attachments[$i] = array(
                'is_attachment' => false,
                'filename' => '',
                'name' => '',
                'attachment' => ''
            );
           
            if($structure->parts[$i]->ifdparameters) {
                foreach($structure->parts[$i]->dparameters as $object) {
                    if(strtolower($object->attribute) == 'filename') {
                        $attachments[$i]['is_attachment'] = true;
                        $attachments[$i]['filename'] = $object->value;
                    }
                }
            }
           
            if($structure->parts[$i]->ifparameters) {
                foreach($structure->parts[$i]->parameters as $object) {
                    if(strtolower($object->attribute) == 'name') {
                        $attachments[$i]['is_attachment'] = true;
                        $attachments[$i]['name'] = $object->value;
                    }
                }
            }
           
            if($attachments[$i]['is_attachment']) {
                $attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
                if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
                    $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                }
                elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
                    $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                }
            }
           
        }
       
    }
   
    return $attachments;
   
}

// EOL Attach




//display header
echo'
<html lang="fr">
	<head>
		<meta charset="UTF-8" />
	</head>
';

if($inbox) 
{ 
	//grab mail
	echo "<u></u>Connexion à la boite au lettre en cours: <font color=green>ok</font><br /><br />";
	$emails = imap_search($inbox,'ALL');
	 //if emails are returned
    if($emails) {
		//for every email...
		foreach($emails as $email_number) {
			//get information specific to this email
			$overview = imap_fetch_overview($inbox, $email_number, 0);
			$seen=$overview[0]->seen;
			//if message is not read
			if ($seen==0)
			{
				$count=$count+1;
				//get mail data
				$message = imap_fetchbody($inbox, $email_number, 1);
				//$fileatt = imap_fetchbody($inbox, $email_number, 2);
				$header = imap_headerinfo($inbox, $email_number);
				$subject = $overview[0] -> subject;
				$from = $header->from[0]->mailbox . "@" . $header->from[0]->host;
				
				//special char convert
				$message=quoted_printable_decode($message);
				$subject=mb_decode_mimeheader($subject);
				$subject = str_replace('_', ' ', $subject);
				
				//Escape special char to SQL query
				$message=mysql_real_escape_string($message);
				$subject=mysql_real_escape_string($subject);
			
				//find gestsup userid from mail address
				$query= mysql_query("SELECT id FROM `tusers` where mail='$from' ");
				$row=mysql_fetch_array($query);
				if($row[0])
				{
					$user_id=$row[0];
				} else {
					$user_id='';
					//add GMO : create user
						$salt = substr(md5(uniqid(rand(), true)), 0, 5); // Generate a random key
						$password=md5($salt . md5('xxxxxxxx')); // store in md5, md5 password + salt
						$requete = "INSERT INTO tusers (lastname,password,salt,mail,profile,login) VALUES ('$from','$password','$salt','$from','2','$from')";
						$execution = mysql_query($requete) or die('Erreur SQL !<br /><br />'.mysql_error());
						$query1= mysql_query("SELECT id FROM `tusers` where mail='$from' ");
						$row1=mysql_fetch_array($query1);
						if($row1[0])
							{
								$user_id=$row1[0];
							}
					//
					$message='De '.$from.':\n'.$message;	
				}
				
				// create ticket
				$query= "INSERT INTO tincidents 
				(user,technician,title,description,date_create,techread,state,criticality,disable) 
				VALUES
				('$user_id','0','$subject', '$message','$datetime','0','5','4','0')";
				$exec = mysql_query($query) or die('Erreur SQL !<br />'.mysql_error());
				$id_ticket=mysql_insert_id();
				
				$attachement = extract_attachments($inbox,$email_number);
				echo $id_ticket;
				echo "&nbsp> Import du message $count: $subject: <font color=green>ok</font><br />";
				$img='0';
				foreach ($attachement as &$attachement) {
					echo $attachement['is_attachment'].'<br>';
					echo $attachement['filename'].'<br>';
					$filenameSQL=$attachement['filename'];
					if ($filenameSQL != '') {
						echo $attachement['name'].'<br>';
						//echo $attachement['attachment'];
							mkdir("./upload/".$id_ticket);
	        		echo 'Le répertoire ./upload/'.$id_ticket.' vient d\'être créé!<br>';      
	       	
						$myfile = fopen("./upload/".$id_ticket."/".$attachement['filename'], "x");// or die("Unable to open file!");
						fwrite($myfile, $attachement['attachment']);
						fclose($myfile);
						
						//echo $filenameSQL.'<br>';
						$imgtext='img'.$img;
						echo $imgtext.'<br>';
						$requete = "UPDATE tincidents SET $imgtext = '$filenameSQL' WHERE id = '$id_ticket'";
						//$requete = "UPDATE tusers set disable=1 WHERE id = '$_GET[id]'";
						echo $requete.'<br>';
						$execution = mysql_query($requete) or die('Erreur SQL !<br /><br />'.mysql_error());
					}
					$img=$img+1;
				} 
				
			}
		}
	}
	imap_close($inbox);
	echo "<br />Total: Récupération de $count messages depuis <b>$rparameters[imap_server]</b> depuis le port <b>$rparameters[imap_port]</b><br />";

} else {
	echo "Erreur de connexion IMAP";
}
echo '</html>';
?>