Playing with PEAR Net_IMAP

when it comes to IMAP programming, you should be very careful about IMAP commands you are issuing, an unneeded call can make your page much slower, that’s why usually IMAP Developers avoid programming with the php IMAP functions, yes they are written in C (c-client), but they don’t give you the commands you want exactly, so usually you would go for native IMAP (i.e. writing commands to a socket, and parsing the output).
Parsing is never an easy job, lot’s of cases and lot’s of bugs can appear, PEAR have a nice library called Net_IMAP, but of course, it doesn’t give you the freedom you need, so I use the IMAPProtocol class from it, as what I need is parsing only, I know the command, I just want to issue them, and to get them parsed.
for example to fetch the headers of a message

<?php
$imap->cmdConnect($mailhost,$mailport);
$imap->cmdLogin(“$username@$domainname” , $password);
$imap->cmdSelect($mailbox);
$msgHeader = $imap->cmdUidFetch($message_uid,’BODY[HEADER]’);
$imap->cmdLogout();
?>

That looks fine, but Imagine this case, you have to sort the mailbox according to the From header, well of course you can do something like the code above, i.e. fetch the headers of all the messages, and parse for the From header, and sort accordingly, but the headers of messages are not a small part, you can have 25 lines for each message while you only need 1, which would slow down your page. if you have some experience with IMAP you would know that you code do this with a command like

A0001 FETCH 1:* (uid body.peek[header.fields (From)])

OK if you try this on IMAPProtocol, in the standard way, i.e $imap->cmdFetch(“1:*”,”(uid body.peek[header.fields (From)])”);
you would get lots of errors telling you that it’s not supported, so what should you do????
well here you have to do parsing yourself, but how can you do that, take a look at the code below:

<?php
$imap->_getCmdId();
$imap->_putCMD($cmdid,’FETCH 1:* (uid body.peek[header.fields (From)])’);
$nsarray=explode(“\n”,$imap->_getRawResponse( $cmdid ));
foreach ($nsarray as $line) {
if(strstr($line,”FETCH (UID “)) {
$UID_array[] = (int) (substr($line,strpos($line,”UID “) + 4));
}
if(strstr($line,”From: “)) {
$msgs_to=trim(strtolower(str_replace(“From: “,””,$line)));
$from_array[]=$msgs_to;
}
}
?>

Why would I do that, well My page is full of IMAPProtocol code, and I want to add the feature of sorting, I can’t just drop the whole page, and I want to make the best performance I can, in the less time I can.
Hope it was useful.