@@ -588,6 +588,46 @@ private function getEncoding($structure) {
588588 return null ;
589589 }
590590
591+ /**
592+ * Find the folder containing this message.
593+ *
594+ * @param null|Folder $folder where to start searching from (top-level inbox by default)
595+ * @return null|Folder
596+ */
597+ public function getContainingFolder (Folder $ folder = null )
598+ {
599+ $ folder = $ folder ?: $ this ->client ->getFolders ()->first ();
600+ $ this ->client ->checkConnection ();
601+
602+ // Try finding the message by uid in the current folder
603+ $ client = new Client ;
604+ $ client ->openFolder ($ folder );
605+ $ uidMatches = imap_fetch_overview ($ client ->getConnection (), $ this ->uid , $ this ->fetch_options );
606+ $ uidMatch = count ($ uidMatches )
607+ ? new Message ($ uidMatches [0 ]->uid , $ uidMatches [0 ]->msgno , $ client )
608+ : null ;
609+ $ client ->disconnect ();
610+
611+ // imap_fetch_overview() on a parent folder will return the matching message
612+ // even when the message is in a child folder so we need to recursively
613+ // search the children
614+ foreach ($ folder ->children as $ child ) {
615+ $ childFolder = $ this ->getContainingFolder ($ child );
616+
617+ if ($ childFolder ) {
618+ return $ childFolder ;
619+ }
620+ }
621+
622+ // before returning the parent
623+ if ($ this ->is ($ uidMatch )) {
624+ return $ folder ;
625+ }
626+
627+ // or signalling that the message was not found in any folder
628+ return null ;
629+ }
630+
591631 /**
592632 * Move the Message into an other Folder
593633 *
@@ -813,4 +853,24 @@ public function getSender() {
813853 public function getBodies () {
814854 return $ this ->bodies ;
815855 }
856+
857+ /**
858+ * Does this message match another one?
859+ *
860+ * A match means same uid, message id, subject and date/time.
861+ *
862+ * @param null|static $message
863+ * @return boolean
864+ */
865+ public function is (Message $ message = null )
866+ {
867+ if (is_null ($ message )) {
868+ return false ;
869+ }
870+
871+ return $ this ->uid == $ message ->uid
872+ && $ this ->message_id == $ message ->message_id
873+ && $ this ->subject == $ message ->subject
874+ && $ this ->date ->eq ($ message ->date );
875+ }
816876}
0 commit comments