Jump to content

MIME email with CID imgs, I need to convert the CID Attribute to URLs, any help?


Ahmed Nasr

Recommended Posts

Hello, I'm just new here, I was searching for any good documentation for imap functions, but I couldn't find any. any how, I need a help for this case:

I have a website where members can publish contents via email, they are sending a message with html body and embeded imgs in, but in case these imgs are having cid numbers, instead of urls, they can't be visible.

 

I tried a simple prototype to resolve this, by using some functions of www.squirrelmail.org, but I couldn't make them work.

 

do you have a way to solve?

now this is the code I have:

 

<?
   $ServerName = "{www.redcherry.com.sa:143/notls}"; // For a IMAP connection    (PORT 143)   
   $UserName = "user";
   $PassWord = "pass";
   
   $mbox = imap_open($ServerName, $UserName,$PassWord) or die("Could not open Mailbox - try again later!"); 
   if ($hdr = imap_check($mbox)) {
   echo "Num Messages " . $hdr->Nmsgs ."\n\n<br><br>";
   	$msgCount = $hdr->Nmsgs;
   } else {
   	echo "failed";
   }
   if (!$_GET['n']){
   $MN=$msgCount;
   $overview=imap_fetch_overview($mbox,"1:$MN",0);
   $size=sizeof($overview);
   
   echo "<table border=\"0\" cellspacing=\"0\" width=\"582\">";
   
   for($i=$size-1;$i>=0;$i--){
   	$val=$overview[$i];
	$msg=$val->msgno;
   	$from=$val->from;
  		$date=$val->date;
	$subj=$val->subject;
   	$seen=$val->seen;
   
   $from = ereg_replace("\"","",$from);
   
   // MAKE DANISH DATE DISPLAY
   	list($dayName,$day,$month,$year,$time) = split(" ",$date); 
	$time = substr($time,0,5);
   	$date = $day ." ". $month ." ". $year . " ". $time;
   
   	if ($bgColor == "#F0F0F0") {
   		$bgColor = "#FFFFFF";
   	} else {
		$bgColor = "#F0F0F0";
	}
   
	if (strlen($subj) > 60) {
   		$subj = substr($subj,0,59) ."...";
	}
   
   	echo "<tr bgcolor=\"$bgColor\"><td colspan=\"2\">$from</td><td colspan=\"2\"><a href=\"?n=$msg\">$subj</a></td>
   		 <td class=\"tblContent\" colspan=\"2\">$date</td></tr>\n";
   }
echo "</table><p>";
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
else if ($_GET['n']){ //if message selected
$msgno=$_GET['n'];
   // GET TEXT BODY
   $dataTxt = get_part($mbox, $msgno, "TEXT/PLAIN");
   
   /////////////////////////////////////////////////////////////////
   $fetchedArray=imap_fetchstructure($mbox,$msgno);
   
   if ($fetchedArray->dparameters)
   $attr=$fetchedArray->dparameters;
   else
   $attr=$fetchedArray->parameters;
   
   //print_r($attr1);
   //echo "<br />second<br/>";

   foreach ($attr as $attname=>$attvalue){
   $cidhttp=sq_cid2http($attname, $msgno, $attvalue, $mbox);						//////////////////////////////////////////////////sq_cid2http
   echo "<img src=\"$cidhttp\">";
   }
   /////////////////////////////////////////////////////////////////
   
   
   // GET HTML BODY
   $dataHtml = get_part($mbox, $msgno, "TEXT/HTML");
   
   if ($dataHtml != "") {
   $msgBody = $dataHtml;
   	$mailformat = "html";
   } else {
   	$msgBody = ereg_replace("\n","<br>",$dataTxt);
   	$mailformat = "text";
   }
// To out put the message body to the user simply print $msgBody like this.
   
   if ($mailformat == "text") {
   	echo "<html><head><title>Messagebody</title></head><body bgcolor=\"white\">$msgBody</body></html>";
   } else {
   	echo $msgBody; // It contains all HTML HEADER tags so we don't have to make them.
   }
   
   //////////////////////////////////////////////////////////////////////// Attachments \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
$struct = imap_fetchstructure($mbox,$msgno);
   $contentParts = count($struct->parts);
   
   if ($contentParts >= 2) {
   for ($i=2;$i<=$contentParts;$i++) {
   	$att[$i-2] = imap_bodystruct($mbox,$msgno,$i);
   	}
   	for ($k=0;$k<sizeof($att);$k++) {
   		if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value    == "US-ASCII") {
   			if ($att[$k]->parameters[1]->value != "") {
   				$selectBoxDisplay[$k] = $att[$k]->parameters[1]->value;
   			}
   		} elseif ($att[$k]->parameters[0]->value != "iso-8859-1" &&    $att[$k]->parameters[0]->value != "ISO-8859-1") {
   			$selectBoxDisplay[$k] = $att[$k]->parameters[0]->value;
   		}
   	}
   }
   
   if (sizeof($selectBoxDisplay) > 0) {
   	echo "<select name=\"attachments\" size=\"3\" class=\"tblContent\" style=\"width:170;\">";
   	for ($j=0;$j<sizeof($selectBoxDisplay);$j++) {
   		echo "\n<option value=\"$j\">". $selectBoxDisplay[$j]    ."</option>";
   	}
   	echo "</select>";
   }
   
   } //Message body page end
   imap_close($mbox);

?>
<?
   function get_mime_type(&$structure) {
   $primary_mime_type = array("TEXT", "MULTIPART","MESSAGE", "APPLICATION", "AUDIO","IMAGE", "VIDEO", "OTHER");
   if($structure->subtype) {
   	return $primary_mime_type[(int) $structure->type] . '/' .$structure->subtype;
   }
   	return "TEXT/PLAIN";
   }
   function get_part($stream, $msg_number, $mime_type, $structure = false,$part_number    = false) {
   
   	if(!$structure) {
   		$structure = imap_fetchstructure($stream, $msg_number);
   	}
   	if($structure) {
   		if($mime_type == get_mime_type($structure)) {
   			if(!$part_number) {
   				$part_number = "1";
   			}
   			$text = imap_fetchbody($stream, $msg_number, $part_number);
   			if($structure->encoding == 3) {
   				return imap_base64($text);
   			} else if($structure->encoding == 4) {
   				return imap_qprint($text);
   			} else {
   			return $text;
   		}
   	}
   
	if($structure->type == 1) /* multipart */ {
   		while(list($index, $sub_structure) = each($structure->parts)) {
   			if($part_number) {
   				$prefix = $part_number . '.';
   			}
   			$data = get_part($stream, $msg_number, $mime_type, $sub_structure,$prefix .    ($index + 1));
   			if($data) {
   				return $data;
   			}
   		} // END OF WHILE
   		} // END OF MULTIPART
   	} // END OF STRUTURE
   	return false;
   } // END OF FUNCTION
   
   
///////////////////////////////////////// sq functions\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\   
   
   function sq_cid2http($message, $id, $cidurl, $mailbox){
    /**
     * Get rid of quotes.
     */

 print_r($cidurl);
    $quotchar = substr($cidurl, 0, 1);
    if ($quotchar == '"' || $quotchar == "'"){
        $cidurl = str_replace($quotchar, "", $cidurl);
    } else {
        $quotchar = '';
    }
    $cidurl = substr(trim($cidurl), 4);

    $match_str = '/\{.*?\}\//';
    $str_rep = '';
    $cidurl = preg_replace($match_str, $str_rep, $cidurl);

    $linkurl = find_ent_id($cidurl, $message);
    /* in case of non-safe cid links $httpurl should be replaced by a sort of
       unsafe link image */
    $httpurl = '';

    /**
     * This is part of a fix for Outlook Express 6.x generating
     * cid URLs without creating content-id headers. These images are
     * not part of the multipart/related html mail. The html contains
     * <img src="cid:{some_id}/image_filename.ext"> references to
     * attached images with as goal to render them inline although
     * the attachment disposition property is not inline.
     */

    if (empty($linkurl)) {
        if (preg_match('/{.*}\//', $cidurl)) {
            $cidurl = preg_replace('/{.*}\//','', $cidurl);
            if (!empty($cidurl)) {
                $linkurl = find_ent_id($cidurl, $message);
            }
        }
    }

    if (!empty($linkurl)) {
        $httpurl = $quotchar . "../" . 'src/download.php?absolute_dl=true&' .
            "passed_id=$id&mailbox=" . urlencode($mailbox) .
            '&ent_id=' . $linkurl . $quotchar;
    } else {
        /**
        * If we couldn't generate a proper img url, drop in a blank image
         * instead of sending back empty, otherwise it causes unusual behaviour
         */
        $httpurl = $quotchar . "../" . 'images/blank.png' . $quotchar;
    }

    return $httpurl;
}

function find_ent_id($id, $message) {
    for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
        if ($message->entities[$i]->header->type0 == 'multipart')  {
            $ret = find_ent_id($id, $message->entities[$i]);
        } else {
            if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
//                if (sq_check_save_extension($message->entities[$i])) {
                return $message->entities[$i]->entity_id;
//                }
            } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
                /**
                 * This is part of a fix for Outlook Express 6.x generating
                 * cid URLs without creating content-id headers
                 * @@JA - 20050207
                 */
                if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
                    return $message->entities[$i]->entity_id;
                }
            }
        }
    }
    return $ret;
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.