From b6638cf499e41b6979b86f78975c9a84d66964e8 Mon Sep 17 00:00:00 2001
From: SL-Gundam <slgundam@gmail.com>
Date: Thu, 18 Apr 2019 01:22:55 +0200
Subject: [PATCH] Optimized IMAP email sorting Fix email processing order

---
 core/mail_api.php | 37 +++++++++++--------------------------
 doc/CHANGELOG.txt |  2 ++
 2 files changed, 13 insertions(+), 26 deletions(-)

diff --git a/core/mail_api.php b/core/mail_api.php
index fc531d5..02d2ff0 100644
--- a/core/mail_api.php
+++ b/core/mail_api.php
@@ -346,7 +346,7 @@ class ERP_mailbox_api
 
 						if ( !$this->pear_error( 'Retrieve list of messages', $t_ListMsgs ) )
 						{
-							while ( $t_Msg = array_pop( $t_ListMsgs ) )
+							while ( $t_Msg = array_shift( $t_ListMsgs ) )
 							{
 								$t_emailresult = $this->process_single_email( $t_Msg[ 'msg_id' ] );
 
@@ -445,7 +445,7 @@ class ERP_mailbox_api
 											{
 												$t_flags = $this->_mailserver->getFlags();
 
-												while ( $t_Msg = array_pop( $t_ListMsgs ) )
+												while ( $t_Msg = array_shift( $t_ListMsgs ) )
 												{
 													$t_isDeleted = $this->isDeleted( $t_Msg[ 'msg_id' ], $t_flags );
 
@@ -536,35 +536,20 @@ class ERP_mailbox_api
 	# Needed a workaround to sort IMAP emails in a certain order
 	private function getListing()
 	{
-		$t_ListMsgs = NULL;
+		$t_ListMsgs = $this->_mailserver->getListing();
 
-		if ( $this->_mailbox[ 'mailbox_type' ] === 'IMAP' )
+		if ( !PEAR::isError( $t_ListMsgs ) )
 		{
-			$t_getSummary = $this->_mailserver->getSummary();
-
-			if ( !$this->pear_error( 'IMAP Get folder info', $t_getSummary ) )
+			if ( $this->_mailbox[ 'mailbox_type' ] === 'IMAP' )
 			{
-				$t_nummsg = count( $t_getSummary );
-				$t_ListMsgs = array();
-				for ( $i = 0; $i < $t_nummsg; $i++ )
-				{
-					$t_getSummary[ $i ][ 'DATE' ] = strtotime( $t_getSummary[ $i ][ 'DATE' ] );
-					// If strtotime fails we default back to the current time. 
-					if ( $t_getSummary[ $i ][ 'DATE' ] === FALSE )
-					{
-						$t_getSummary[ $i ][ 'DATE' ] = time();
-					}
-
-					$t_ListMsgs[ $t_getSummary[ $i ][ 'DATE' ] ] = array( 'msg_id' => (int) $t_getSummary[ $i ][ 'MSG_NUM' ] );
-				}
-
-				krsort( $t_ListMsgs );
+				$t_ListMsgs = array_column( $t_ListMsgs, NULL, 'uidl' );
+			}
+			else
+			{
+				$t_ListMsgs = array_column( $t_ListMsgs, NULL, 'msg_id' );
 			}
-		}
 
-		if ( $t_ListMsgs === NULL )
-		{
-			$t_ListMsgs = $this->_mailserver->getListing();
+			ksort( $t_ListMsgs );
 		}
 
 		return( $t_ListMsgs );
diff --git a/doc/CHANGELOG.txt b/doc/CHANGELOG.txt
index b136245..1f38eec 100644
--- a/doc/CHANGELOG.txt
+++ b/doc/CHANGELOG.txt
@@ -12,6 +12,8 @@ Sep 2018 - EmailReporting-0.11.0
 	- Limited max length of message id (#25433)
 	- Add support for Windows-1257 charset
 	- Enable the caching of IMAP flags
+	- Optimized IMAP email sorting
+	- Fix email processing order
 
 May 2018 - EmailReporting-0.10.1
 	- Added error if, on installation, 'api/soap/mc_file_api.php' is missing
-- 
2.21.0.windows.1

