Completed
Push — master ( d3465e...7588c9 )
by Klaus
37:37
created
api/src/Mail.php 2 patches
Braces   +1821 added lines, -544 removed lines patch added patch discarded remove patch
@@ -199,7 +199,10 @@  discard block
 block discarded – undo
199 199
 	public static function getInstance($_restoreSession=true, &$_profileID=0, $_validate=true, $_oldImapServerObject=false, $_reuseCache=null)
200 200
 	{
201 201
 		//$_restoreSession=false;
202
-		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
202
+		if (is_null($_reuseCache))
203
+		{
204
+			$_reuseCache = $_restoreSession;
205
+		}
203 206
 		//error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID.'/'.Mail\Account::get_default_acc_id().' for user:'.$GLOBALS['egw_info']['user']['account_lid'].' called from:'.function_backtrace());
204 207
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_oldImapServerObject));
205 208
 		self::$profileDefunct = Cache::getCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),5*1);
@@ -230,9 +233,15 @@  discard block
 block discarded – undo
230 233
 			{
231 234
 				$profileID = Mail\Account::get_default_acc_id();
232 235
 			}
233
-			if ($profileID!=$_profileID) $_restoreSession==false;
236
+			if ($profileID!=$_profileID)
237
+			{
238
+				$_restoreSession==false;
239
+			}
234 240
 			$_profileID=$profileID;
235
-			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' called with profileID==0 using '.$profileID.' instead->'.function_backtrace());
241
+			if (self::$debug)
242
+			{
243
+				error_log(__METHOD__.' ('.__LINE__.') '.' called with profileID==0 using '.$profileID.' instead->'.function_backtrace());
244
+			}
236 245
 		}
237 246
 		// no validation or restoreSession for old ImapServer Object, just fetch it and return it
238 247
 		if ($_oldImapServerObject===true)
@@ -271,7 +280,8 @@  discard block
 block discarded – undo
271 280
 				// TODO: merge mailprefs into userprefs, for easy treatment
272 281
 				self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
273 282
 				self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
274
-			} catch (\Exception $e)
283
+			}
284
+			catch (\Exception $e)
275 285
 			{
276 286
 				$newprofileID = Mail\Account::get_default_acc_id();
277 287
 				// try loading the default profile for the user
@@ -289,9 +299,15 @@  discard block
 block discarded – undo
289 299
 			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate );
290 300
 		}
291 301
 		self::$instances[$_profileID]->profileID = $_profileID;
292
-		if (!isset(self::$instances[$_profileID]->idna2)) self::$instances[$_profileID]->idna2 = new Horde_Idna;
302
+		if (!isset(self::$instances[$_profileID]->idna2))
303
+		{
304
+			self::$instances[$_profileID]->idna2 = new Horde_Idna;
305
+		}
293 306
 		//if ($_profileID==0); error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID);
294
-		if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
307
+		if (is_null(self::$mailConfig))
308
+		{
309
+			self::$mailConfig = Config::read('mail');
310
+		}
295 311
 		return self::$instances[$_profileID];
296 312
 	}
297 313
 
@@ -316,14 +332,20 @@  discard block
 block discarded – undo
316 332
 			}
317 333
 			catch (\Exception $e)
318 334
 			{
319
-				if ($_profileID != Mail\Account::get_default_acc_id()) $_profileID = Mail\Account::get_default_acc_id();
335
+				if ($_profileID != Mail\Account::get_default_acc_id())
336
+				{
337
+					$_profileID = Mail\Account::get_default_acc_id();
338
+				}
320 339
 				error_log(__METHOD__.__LINE__.' '.$e->getMessage());
321 340
 				return false;
322 341
 			}
323 342
 		}
324 343
 		if ($oldProfileID != $_profileID)
325 344
 		{
326
-			if ($oldProfileID && $_profileID==0) $_profileID = $oldProfileID;
345
+			if ($oldProfileID && $_profileID==0)
346
+			{
347
+				$_profileID = $oldProfileID;
348
+			}
327 349
 			$GLOBALS['egw']->preferences->add('mail','ActiveProfileID',$_profileID,'user');
328 350
 			// save prefs
329 351
 			$GLOBALS['egw']->preferences->save_repository(true);
@@ -353,11 +375,17 @@  discard block
 block discarded – undo
353 375
 				{
354 376
 					return $_acc_id;
355 377
 				}
356
-				if (self::$debug) error_log(__METHOD__."($_acc_id) account NOT valid, no imap-host!");
378
+				if (self::$debug)
379
+				{
380
+					error_log(__METHOD__."($_acc_id) account NOT valid, no imap-host!");
381
+				}
357 382
 			}
358 383
 			catch (\Exception $e) {
359 384
 				unset($e);
360
-				if (self::$debug) error_log(__METHOD__."($_acc_id) account NOT found!");
385
+				if (self::$debug)
386
+				{
387
+					error_log(__METHOD__."($_acc_id) account NOT found!");
388
+				}
361 389
 			}
362 390
 		}
363 391
 		// no account specified or specified account not found or not valid
@@ -366,11 +394,17 @@  discard block
 block discarded – undo
366 394
 		{
367 395
 			if (!empty($imap_host) && ($account = Mail\Account::read($acc_id)) && $account->is_imap())
368 396
 			{
369
-				if (self::$debug && $_acc_id) error_log(__METHOD__."($_acc_id) using $acc_id instead");
397
+				if (self::$debug && $_acc_id)
398
+				{
399
+					error_log(__METHOD__."($_acc_id) using $acc_id instead");
400
+				}
370 401
 				return $acc_id;
371 402
 			}
372 403
 		}
373
-		if (self::$debug) error_log(__METHOD__."($_acc_id) NO valid account found!");
404
+		if (self::$debug)
405
+		{
406
+			error_log(__METHOD__."($_acc_id) NO valid account found!");
407
+		}
374 408
 		return 0;
375 409
 	}
376 410
 
@@ -386,10 +420,19 @@  discard block
 block discarded – undo
386 420
 	 */
387 421
 	private function __construct($_displayCharset='utf-8',$_restoreSession=true, $_profileID=0, $_oldImapServerObject=false, $_reuseCache=null)
388 422
 	{
389
-		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
390
-		if (!empty($_displayCharset)) self::$displayCharset = $_displayCharset;
423
+		if (is_null($_reuseCache))
424
+		{
425
+			$_reuseCache = $_restoreSession;
426
+		}
427
+		if (!empty($_displayCharset))
428
+		{
429
+			self::$displayCharset = $_displayCharset;
430
+		}
391 431
 		// not nummeric, we assume we only want an empty class object
392
-		if (!is_numeric($_profileID)) return true;
432
+		if (!is_numeric($_profileID))
433
+		{
434
+			return true;
435
+		}
393 436
 		if ($_restoreSession)
394 437
 		{
395 438
 			//error_log(__METHOD__." Session restore ".function_backtrace());
@@ -404,7 +447,10 @@  discard block
 block discarded – undo
404 447
 			$firstMessage = $this->sessionData['previewMessage'];
405 448
 			$this->sessionData = array();
406 449
 		}
407
-		if (!$_reuseCache) $this->forcePrefReload($_profileID,!$_reuseCache);
450
+		if (!$_reuseCache)
451
+		{
452
+			$this->forcePrefReload($_profileID,!$_reuseCache);
453
+		}
408 454
 		try
409 455
 		{
410 456
 			$this->profileID = self::validateProfileID($_profileID);
@@ -428,7 +474,10 @@  discard block
 block discarded – undo
428 474
 			$_profileID = $this->profileID = $GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $this->icServer->ImapServerId;
429 475
 		}
430 476
 
431
-		if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
477
+		if (is_null(self::$mailConfig))
478
+		{
479
+			self::$mailConfig = Config::read('mail');
480
+		}
432 481
 	}
433 482
 
434 483
 	/**
@@ -457,7 +506,10 @@  discard block
 block discarded – undo
457 506
 		// unset the mail_preferences session object, to force the reload/rebuild
458 507
 		Cache::setSession('mail','mail_preferences',serialize(array()));
459 508
 		Cache::setSession('emailadmin','session_data',serialize(array()));
460
-		if ($_resetFolderObjects) self::resetFolderObjectCache($_profile_id);
509
+		if ($_resetFolderObjects)
510
+		{
511
+			self::resetFolderObjectCache($_profile_id);
512
+		}
461 513
 	}
462 514
 
463 515
 	/**
@@ -467,7 +519,10 @@  discard block
 block discarded – undo
467 519
 	{
468 520
 		$this->sessionData = array();//Cache::getCache(Cache::SESSION,'mail','session_data',$callback=null,$callback_params=array(),$expiration=60*60*1);
469 521
 		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
470
-		if (!empty(self::$activeFolderCache[$this->profileID])) $this->sessionData['mailbox'] = self::$activeFolderCache[$this->profileID];
522
+		if (!empty(self::$activeFolderCache[$this->profileID]))
523
+		{
524
+			$this->sessionData['mailbox'] = self::$activeFolderCache[$this->profileID];
525
+		}
471 526
 	}
472 527
 
473 528
 	/**
@@ -476,7 +531,10 @@  discard block
 block discarded – undo
476 531
 	function saveSessionData()
477 532
 	{
478 533
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($this->sessionData)));
479
-		if (!empty($this->sessionData['mailbox'])) self::$activeFolderCache[$this->profileID]=$this->sessionData['mailbox'];
534
+		if (!empty($this->sessionData['mailbox']))
535
+		{
536
+			self::$activeFolderCache[$this->profileID]=$this->sessionData['mailbox'];
537
+		}
480 538
 		if (isset(self::$activeFolderCache) && is_array(self::$activeFolderCache))
481 539
 		{
482 540
 			Cache::setCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),self::$activeFolderCache, 60*60*10);
@@ -497,8 +555,14 @@  discard block
 block discarded – undo
497 555
 	 */
498 556
 	static function unsetCachedObjects($_profileID=null)
499 557
 	{
500
-		if (is_null($_profileID)) $_profileID = Mail\Account::get_default_acc_id();
501
-		if (is_array($_profileID) && $_profileID['account_id']) $account_id = $_profileID['account_id'];
558
+		if (is_null($_profileID))
559
+		{
560
+			$_profileID = Mail\Account::get_default_acc_id();
561
+		}
562
+		if (is_array($_profileID) && $_profileID['account_id'])
563
+		{
564
+			$account_id = $_profileID['account_id'];
565
+		}
502 566
 		//error_log(__METHOD__.__LINE__.' called with ProfileID:'.array2string($_profileID).' from '.function_backtrace());
503 567
 		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID,'tracker_')===false)))
504 568
 		{
@@ -531,7 +595,10 @@  discard block
 block discarded – undo
531 595
 				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),$vacationCached, $expiration=60*60*24*1);
532 596
 			}
533 597
 
534
-			if (isset(self::$instances[$_profileID])) unset(self::$instances[$_profileID]);
598
+			if (isset(self::$instances[$_profileID]))
599
+			{
600
+				unset(self::$instances[$_profileID]);
601
+			}
535 602
 		}
536 603
 		if (is_array($_profileID) && $_profileID['location'] == 'clear_cache')
537 604
 		{
@@ -560,7 +627,10 @@  discard block
 block discarded – undo
560 627
 	static function resetConnectionErrorCache($_ImapServerId=null,$account_id=null)
561 628
 	{
562 629
 		//error_log(__METHOD__.' ('.__LINE__.') '.' for Profile:'.array2string($_ImapServerId) .' for user:'.trim($account_id));
563
-		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
630
+		if (is_null($account_id))
631
+		{
632
+			$account_id = $GLOBALS['egw_info']['user']['account_id'];
633
+		}
564 634
 		if (is_array($_ImapServerId))
565 635
 		{
566 636
 			// called via hook
@@ -599,7 +669,10 @@  discard block
 block discarded – undo
599 669
 	static function resetFolderObjectCache($_ImapServerId=null,$account_id=null)
600 670
 	{
601 671
 		//error_log(__METHOD__.' ('.__LINE__.') '.' called for Profile:'.array2string($_ImapServerId).'->'.function_backtrace());
602
-		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
672
+		if (is_null($account_id))
673
+		{
674
+			$account_id = $GLOBALS['egw_info']['user']['account_id'];
675
+		}
603 676
 		// on [location] => verify_settings we coud either use [prefs] => Array([ActiveProfileID] => 9, .. as $_ImapServerId
604 677
 		// or treat it as not given. we try that path
605 678
 		if (is_null($_ImapServerId)||is_array($_ImapServerId))
@@ -673,10 +746,14 @@  discard block
 block discarded – undo
673 746
 
674 747
 		$userEMailAdresses = array($acc['ident_email']=>$acc['ident_realname']);
675 748
 
676
-		foreach($identities as $ik => $ident) {
749
+		foreach($identities as $ik => $ident)
750
+		{
677 751
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
678 752
 			$identity = Mail\Account::read_identity($ik);
679
-			if (!empty($identity['ident_email']) && !isset($userEMailAdresses[$identity['ident_email']])) $userEMailAdresses[$identity['ident_email']] = $identity['ident_realname'];
753
+			if (!empty($identity['ident_email']) && !isset($userEMailAdresses[$identity['ident_email']]))
754
+			{
755
+				$userEMailAdresses[$identity['ident_email']] = $identity['ident_realname'];
756
+			}
680 757
 		}
681 758
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($userEMailAdresses));
682 759
 		return $userEMailAdresses;
@@ -694,13 +771,20 @@  discard block
 block discarded – undo
694 771
 		foreach(Mail\Account::search($only_current_user=($_accountToSearch?$_accountToSearch:true), $just_name=true) as $acc_id => $identity_name)
695 772
 		{
696 773
 			$acc = Mail\Account::read($acc_id,($_accountToSearch?$_accountToSearch:null));
697
-			if (!$resolve_placeholders) $userEMailAdresses[$acc['ident_id']] = array('acc_id'=>$acc_id,'ident_id'=>$acc['ident_id'],'ident_email'=>$acc['ident_email'],'ident_org'=>$acc['ident_org'],'ident_realname'=>$acc['ident_realname'],'ident_signature'=>$acc['ident_signature'],'ident_name'=>$acc['ident_name']);
774
+			if (!$resolve_placeholders)
775
+			{
776
+				$userEMailAdresses[$acc['ident_id']] = array('acc_id'=>$acc_id,'ident_id'=>$acc['ident_id'],'ident_email'=>$acc['ident_email'],'ident_org'=>$acc['ident_org'],'ident_realname'=>$acc['ident_realname'],'ident_signature'=>$acc['ident_signature'],'ident_name'=>$acc['ident_name']);
777
+			}
698 778
 
699
-			foreach(Mail\Account::identities($acc) as $ik => $ident) {
779
+			foreach(Mail\Account::identities($acc) as $ik => $ident)
780
+			{
700 781
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
701 782
 				$identity = Mail\Account::read_identity($ik,$resolve_placeholders);
702 783
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
703
-				if (!isset($userEMailAdresses[$identity['ident_id']])) $userEMailAdresses[$identity['ident_id']] = array('acc_id'=>$acc_id,'ident_id'=>$identity['ident_id'],'ident_email'=>$identity['ident_email'],'ident_org'=>$identity['ident_org'],'ident_realname'=>$identity['ident_realname'],'ident_signature'=>$identity['ident_signature'],'ident_name'=>$identity['ident_name']);
784
+				if (!isset($userEMailAdresses[$identity['ident_id']]))
785
+				{
786
+					$userEMailAdresses[$identity['ident_id']] = array('acc_id'=>$acc_id,'ident_id'=>$identity['ident_id'],'ident_email'=>$identity['ident_email'],'ident_org'=>$identity['ident_org'],'ident_realname'=>$identity['ident_realname'],'ident_signature'=>$identity['ident_signature'],'ident_name'=>$identity['ident_name']);
787
+				}
704 788
 			}
705 789
 		}
706 790
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($userEMailAdresses));
@@ -720,12 +804,16 @@  discard block
 block discarded – undo
720 804
 			$account = Mail\Account::read($account);
721 805
 		}
722 806
 		$userEMailAdresses = array();
723
-		foreach(Mail\Account::identities($account, true, 'params') as $ik => $ident) {
807
+		foreach(Mail\Account::identities($account, true, 'params') as $ik => $ident)
808
+		{
724 809
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
725 810
 			$identity = Mail\Account::read_identity($ik,true,null,$account);
726 811
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
727 812
 			// standardIdentity has ident_id==acc_id (as it is done within account->identities)
728
-			if (empty($identity['ident_id'])) $identity['ident_id'] = $identity['acc_id'];
813
+			if (empty($identity['ident_id']))
814
+			{
815
+				$identity['ident_id'] = $identity['acc_id'];
816
+			}
729 817
 			if (!isset($userEMailAdresses[$identity['ident_id']]))
730 818
 			{
731 819
 				$userEMailAdresses[$identity['ident_id']] = array('acc_id'=>$identity['acc_id'],
@@ -768,15 +856,25 @@  discard block
 block discarded – undo
768 856
 		// account select box
769 857
 		$selectedID = $this->profileID;
770 858
 		$allAccountData = Mail\Account::search($only_current_user=true, false, null);
771
-		if ($allAccountData) {
859
+		if ($allAccountData)
860
+		{
772 861
 			$rememberFirst=$selectedFound=null;
773 862
 			foreach ($allAccountData as $tmpkey => $icServers)
774 863
 			{
775
-				if (is_null($rememberFirst)) $rememberFirst = $tmpkey;
776
-				if ($tmpkey == $selectedID) $selectedFound=true;
864
+				if (is_null($rememberFirst))
865
+				{
866
+					$rememberFirst = $tmpkey;
867
+				}
868
+				if ($tmpkey == $selectedID)
869
+				{
870
+					$selectedFound=true;
871
+				}
777 872
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($icServers->acc_imap_host));
778 873
 				$host = $icServers->acc_imap_host;
779
-				if (empty($host)) continue;
874
+				if (empty($host))
875
+				{
876
+					continue;
877
+				}
780 878
 				$identities[$icServers->acc_id] = $icServers['ident_realname'].' '.$icServers['ident_org'].' <'.$icServers['ident_email'].'>';
781 879
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($identities[$icServers->acc_id]));
782 880
 			}
@@ -836,7 +934,10 @@  discard block
 block discarded – undo
836 934
 	 */
837 935
 	function reopen($_foldername)
838 936
 	{
839
-		if (self::$debugTimes) $starttime = microtime (true);
937
+		if (self::$debugTimes)
938
+		{
939
+			$starttime = microtime (true);
940
+		}
840 941
 
841 942
 		//error_log(__METHOD__.' ('.__LINE__.') '."('$_foldername') ".function_backtrace());
842 943
 		// TODO: trying to reduce traffic to the IMAP Server here, introduces problems with fetching the bodies of
@@ -846,12 +947,16 @@  discard block
 block discarded – undo
846 947
 		//{
847 948
 			//error_log( __METHOD__.' ('.__LINE__.') '." $_foldername ".function_backtrace());
848 949
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Connected with icServer for Profile:'.$this->profileID.'?'.print_r($this->icServer->_connected,true));
849
-			if ($this->folderIsSelectable($_foldername)) {
950
+			if ($this->folderIsSelectable($_foldername))
951
+			{
850 952
 				$this->icServer->openMailbox($_foldername);
851 953
 			}
852 954
 			$folderOpened = $_foldername;
853 955
 		//}
854
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'Folder:'.$_foldername,__METHOD__.' ('.__LINE__.') ');
956
+		if (self::$debugTimes)
957
+		{
958
+			self::logRunTimes($starttime,null,'Folder:'.$_foldername,__METHOD__.' ('.__LINE__.') ');
959
+		}
855 960
 	}
856 961
 
857 962
 
@@ -866,13 +971,22 @@  discard block
 block discarded – undo
866 971
 	{
867 972
 		//error_log( "-------------------------->open connection ".function_backtrace());
868 973
 		//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.array2string($this->icServer));
869
-		if (self::$debugTimes) $starttime = microtime (true);
974
+		if (self::$debugTimes)
975
+		{
976
+			$starttime = microtime (true);
977
+		}
870 978
 		$mailbox=null;
871 979
 		try
872 980
 		{
873
-			if(isset($this->sessionData['mailbox'])&&$this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
874
-			if (empty($mailbox)) $mailbox = $this->icServer->getCurrentMailbox();
875
-/*
981
+			if(isset($this->sessionData['mailbox'])&&$this->folderExists($this->sessionData['mailbox']))
982
+			{
983
+				$mailbox = $this->sessionData['mailbox'];
984
+			}
985
+			if (empty($mailbox))
986
+			{
987
+				$mailbox = $this->icServer->getCurrentMailbox();
988
+			}
989
+			/*
876 990
 			if (isset(Mail\Imap::$supports_keywords[$_icServerID]))
877 991
 			{
878 992
 				$this->icServer->openMailbox($mailbox);
@@ -897,7 +1011,10 @@  discard block
 block discarded – undo
897 1011
 			error_log(__METHOD__.' ('.__LINE__.') '."->open connection for Server with profileID:".$_icServerID." trying to examine ($mailbox) failed!".$e->getMessage());
898 1012
 			throw new Exception(__METHOD__." failed to ".__METHOD__." on Profile to $_icServerID while trying to examine $mailbox:".$e->getMessage());
899 1013
 		}
900
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'ProfileID:'.$_icServerID,__METHOD__.' ('.__LINE__.') ');
1014
+		if (self::$debugTimes)
1015
+		{
1016
+			self::logRunTimes($starttime,null,'ProfileID:'.$_icServerID,__METHOD__.' ('.__LINE__.') ');
1017
+		}
901 1018
 	}
902 1019
 
903 1020
 	/**
@@ -909,7 +1026,10 @@  discard block
 block discarded – undo
909 1026
 	function getQuotaRoot()
910 1027
 	{
911 1028
 		static $quota;
912
-		if (isset($quota)) return $quota;
1029
+		if (isset($quota))
1030
+		{
1031
+			return $quota;
1032
+		}
913 1033
 		if (isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID]))
914 1034
 		{
915 1035
 			// something is wrong. Do not proceed. either no folder or profile is marked as defunct for this request
@@ -918,7 +1038,8 @@  discard block
 block discarded – undo
918 1038
 		try
919 1039
 		{
920 1040
 			$this->icServer->getCurrentMailbox();
921
-			if(!$this->icServer->hasCapability('QUOTA')) {
1041
+			if(!$this->icServer->hasCapability('QUOTA'))
1042
+			{
922 1043
 				$quota = false;
923 1044
 				return false;
924 1045
 			}
@@ -936,12 +1057,15 @@  discard block
 block discarded – undo
936 1057
 			}
937 1058
 		}
938 1059
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($quota));
939
-		if(is_array($quota)) {
1060
+		if(is_array($quota))
1061
+		{
940 1062
 			$quota = array(
941 1063
 				'usage'	=> $quota['USED'],
942 1064
 				'limit'	=> $quota['QMAX'],
943 1065
 			);
944
-		} else {
1066
+		}
1067
+		else
1068
+		{
945 1069
 			$quota = false;
946 1070
 		}
947 1071
 		return $quota;
@@ -957,7 +1081,11 @@  discard block
 block discarded – undo
957 1081
 	static function getTimeOut($_use='IMAP')
958 1082
 	{
959 1083
 		$timeout = $GLOBALS['egw_info']['user']['preferences']['mail']['connectionTimeout'];
960
-		if (empty($timeout)) $timeout = ($_use=='SIEVE'?10:20); // this is the default value
1084
+		if (empty($timeout))
1085
+		{
1086
+			$timeout = ($_use=='SIEVE'?10:20);
1087
+		}
1088
+		// this is the default value
961 1089
 		return $timeout;
962 1090
 	}
963 1091
 
@@ -975,9 +1103,13 @@  discard block
 block discarded – undo
975 1103
 		$foldersNameSpace = array();
976 1104
 		$delimiter = $this->getHierarchyDelimiter();
977 1105
 		// TODO: cache by $this->icServer->ImapServerId
978
-		if (is_null($nameSpace)) $nameSpace = $this->icServer->getNameSpaceArray();
1106
+		if (is_null($nameSpace))
1107
+		{
1108
+			$nameSpace = $this->icServer->getNameSpaceArray();
1109
+		}
979 1110
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($nameSpace));
980
-		if (is_array($nameSpace)) {
1111
+		if (is_array($nameSpace))
1112
+		{
981 1113
 			foreach($nameSpace as $type => $singleNameSpaceArray)
982 1114
 			{
983 1115
 				foreach ($singleNameSpaceArray as $singleNameSpace)
@@ -994,7 +1126,9 @@  discard block
 block discarded – undo
994 1126
 						$_foldersNameSpace['prefix_present'] = 'forced';
995 1127
 						// uw-imap server with mailbox prefix or dovecot maybe
996 1128
 						$_foldersNameSpace['prefix'] = 'mail';
997
-					} else {
1129
+					}
1130
+					else
1131
+					{
998 1132
 						$_foldersNameSpace['prefix_present'] = !empty($singleNameSpace['name']);
999 1133
 						$_foldersNameSpace['prefix'] = $singleNameSpace['name'];
1000 1134
 					}
@@ -1021,7 +1155,10 @@  discard block
 block discarded – undo
1021 1155
 		foreach($nameSpace as &$singleNameSpace)
1022 1156
 		{
1023 1157
 			//if (substr($singleNameSpace['prefix'],0,strlen($folderName))==$folderName) return $singleNameSpace['prefix'];
1024
-			if (substr($folderName,0,strlen($singleNameSpace['prefix']))==$singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1158
+			if (substr($folderName,0,strlen($singleNameSpace['prefix']))==$singleNameSpace['prefix'])
1159
+			{
1160
+				return $singleNameSpace['prefix'];
1161
+			}
1025 1162
 		}
1026 1163
 		return "";
1027 1164
 	}
@@ -1035,8 +1172,14 @@  discard block
 block discarded – undo
1035 1172
 	function getHierarchyDelimiter($_useCache=true)
1036 1173
 	{
1037 1174
 		static $HierarchyDelimiter = null;
1038
-		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1039
-		if ($_useCache===false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1175
+		if (is_null($HierarchyDelimiter))
1176
+		{
1177
+			$HierarchyDelimiter = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1178
+		}
1179
+		if ($_useCache===false)
1180
+		{
1181
+			unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1182
+		}
1040 1183
 		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId])&&!empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1041 1184
 		{
1042 1185
 			return $HierarchyDelimiter[$this->icServer->ImapServerId];
@@ -1070,14 +1213,19 @@  discard block
 block discarded – undo
1070 1213
 	{
1071 1214
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$this->icServer->ImapServerId.' Connected:'.$this->icServer->_connected);
1072 1215
 		static $_specialUseFolders = null;
1073
-		if (is_null($_specialUseFolders)||empty($_specialUseFolders)) $_specialUseFolders = Cache::getCache(Cache::INSTANCE,'email','specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1216
+		if (is_null($_specialUseFolders)||empty($_specialUseFolders))
1217
+		{
1218
+			$_specialUseFolders = Cache::getCache(Cache::INSTANCE,'email','specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1219
+		}
1074 1220
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_trash));
1075 1221
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_sent));
1076 1222
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_draft));
1077 1223
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_template));
1078 1224
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1079 1225
 		if (isset($_specialUseFolders[$this->icServer->ImapServerId]) && !empty($_specialUseFolders[$this->icServer->ImapServerId]))
1080
-			return $_specialUseFolders[$this->icServer->ImapServerId];
1226
+		{
1227
+					return $_specialUseFolders[$this->icServer->ImapServerId];
1228
+		}
1081 1229
 		$_specialUseFolders[$this->icServer->ImapServerId]=array();
1082 1230
 		//if (!empty($this->icServer->acc_folder_trash) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]))
1083 1231
 			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]='Trash';
@@ -1105,7 +1253,8 @@  discard block
 block discarded – undo
1105 1253
 	function folderIsSelectable($folderToSelect)
1106 1254
 	{
1107 1255
 		$retval = true;
1108
-		if($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect,false,true))) {
1256
+		if($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect,false,true)))
1257
+		{
1109 1258
 			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']),'noselect')!==false)
1110 1259
 			{
1111 1260
 				$retval = false;
@@ -1158,7 +1307,10 @@  discard block
 block discarded – undo
1158 1307
 	 */
1159 1308
 	function getFolderStatus($_folderName,$ignoreStatusCache=false,$basicInfoOnly=false,$fetchSubscribedInfo=true)
1160 1309
 	{
1161
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." called with:$_folderName,$ignoreStatusCache,$basicInfoOnly");
1310
+		if (self::$debug)
1311
+		{
1312
+			error_log(__METHOD__.' ('.__LINE__.') '." called with:$_folderName,$ignoreStatusCache,$basicInfoOnly");
1313
+		}
1162 1314
 		if (!is_string($_folderName) || empty($_folderName)||(isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID])))
1163 1315
 		{
1164 1316
 			// something is wrong. Do not proceed. either no folder or profile is marked as defunct for this request
@@ -1170,7 +1322,10 @@  discard block
 block discarded – undo
1170 1322
 		{
1171 1323
 			$folderInfoCache = $folderBasicInfo[$this->profileID];
1172 1324
 		}
1173
-		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache==false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1325
+		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache==false && $basicInfoOnly)
1326
+		{
1327
+			return $folderInfoCache[$_folderName];
1328
+		}
1174 1329
 		$retValue = array();
1175 1330
 		$retValue['subscribed'] = false;
1176 1331
 /*
@@ -1199,7 +1354,10 @@  discard block
 block discarded – undo
1199 1354
 			if (is_array($ret))
1200 1355
 			{
1201 1356
 				$retkeys = array_keys($ret);
1202
-				if ($retkeys[0]==$_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1357
+				if ($retkeys[0]==$_folderName)
1358
+				{
1359
+					$folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1360
+				}
1203 1361
 			}
1204 1362
 			else
1205 1363
 			{
@@ -1208,7 +1366,8 @@  discard block
 block discarded – undo
1208 1366
 		}
1209 1367
 		$folderInfo = $folderInfoCache[$_folderName];
1210 1368
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($folderInfo).'->'.function_backtrace());
1211
-		if($ignoreStatusCache||!$folderInfo|| !is_array($folderInfo)) {
1369
+		if($ignoreStatusCache||!$folderInfo|| !is_array($folderInfo))
1370
+		{
1212 1371
 			try
1213 1372
 			{
1214 1373
 				$folderInfo = $this->_getStatus($_folderName,$ignoreStatusCache);
@@ -1243,7 +1402,8 @@  discard block
 block discarded – undo
1243 1402
 		$retValue['shortName']		= array_pop($shortNameParts);
1244 1403
 		$retValue['displayName']	= $_folderName;
1245 1404
 		$retValue['shortDisplayName']	= $retValue['shortName'];
1246
-		if(strtoupper($retValue['shortName']) == 'INBOX') {
1405
+		if(strtoupper($retValue['shortName']) == 'INBOX')
1406
+		{
1247 1407
 			$retValue['displayName']	= lang('INBOX');
1248 1408
 			$retValue['shortDisplayName']	= lang('INBOX');
1249 1409
 		}
@@ -1252,7 +1412,10 @@  discard block
 block discarded – undo
1252 1412
 		{
1253 1413
 			$retValue['displayName'] = $retValue['shortDisplayName'] = lang($retValue['shortName']);
1254 1414
 		}
1255
-		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName]=$retValue;
1415
+		if ($folderInfo)
1416
+		{
1417
+			$folderBasicInfo[$this->profileID][$_folderName]=$retValue;
1418
+		}
1256 1419
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.$_folderName.array2string($retValue['attributes']));
1257 1420
 		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']),'noselect')!==false))
1258 1421
 		{
@@ -1264,24 +1427,34 @@  discard block
 block discarded – undo
1264 1427
 		static $subscribedFolders = null;
1265 1428
 		static $nameSpace = null;
1266 1429
 		static $prefix = null;
1267
-		if (is_null($nameSpace) || empty($nameSpace[$this->profileID])) $nameSpace[$this->profileID] = $this->_getNameSpaces();
1430
+		if (is_null($nameSpace) || empty($nameSpace[$this->profileID]))
1431
+		{
1432
+			$nameSpace[$this->profileID] = $this->_getNameSpaces();
1433
+		}
1268 1434
 		if (!empty($nameSpace[$this->profileID]))
1269 1435
 		{
1270 1436
 			$nsNoPersonal=array();
1271 1437
 			foreach($nameSpace[$this->profileID] as &$ns)
1272 1438
 			{
1273
-				if ($ns['type']!='personal') $nsNoPersonal[]=$ns;
1439
+				if ($ns['type']!='personal')
1440
+				{
1441
+					$nsNoPersonal[]=$ns;
1442
+				}
1274 1443
 			}
1275 1444
 			$nameSpace[$this->profileID]=$nsNoPersonal;
1276 1445
 		}
1277
-		if (is_null($prefix) || empty($prefix[$this->profileID]) || empty($prefix[$this->profileID][$_folderName])) $prefix[$this->profileID][$_folderName] = $this->getFolderPrefixFromNamespace($nameSpace[$this->profileID], $_folderName);
1446
+		if (is_null($prefix) || empty($prefix[$this->profileID]) || empty($prefix[$this->profileID][$_folderName]))
1447
+		{
1448
+			$prefix[$this->profileID][$_folderName] = $this->getFolderPrefixFromNamespace($nameSpace[$this->profileID], $_folderName);
1449
+		}
1278 1450
 
1279 1451
 		if ($fetchSubscribedInfo && is_null($subscribedFolders) || empty($subscribedFolders[$this->profileID]))
1280 1452
 		{
1281 1453
 			$subscribedFolders[$this->profileID] = $this->icServer->listSubscribedMailboxes();
1282 1454
 		}
1283 1455
 
1284
-		if($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName,$subscribedFolders[$this->profileID])) {
1456
+		if($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName,$subscribedFolders[$this->profileID]))
1457
+		{
1285 1458
 			$retValue['subscribed'] = true;
1286 1459
 		}
1287 1460
 
@@ -1300,8 +1473,7 @@  discard block
 block discarded – undo
1300 1473
 				(isset($this->mailPreferences['trustServersUnseenInfo']) &&
1301 1474
 				$this->mailPreferences['trustServersUnseenInfo']==2 &&
1302 1475
 				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName,$prefix[$this->profileID][$_folderName]) !== false)
1303
-			)
1304
-			{
1476
+			) {
1305 1477
 				//error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($prefix,true).' TS:'.$this->mailPreferences['trustServersUnseenInfo']);
1306 1478
 				// we filter for the combined status of unseen and undeleted, as this is what we show in list
1307 1479
 				try
@@ -1313,13 +1485,19 @@  discard block
 block discarded – undo
1313 1485
 				}
1314 1486
 				catch (\Exception $ee)
1315 1487
 				{
1316
-					if (self::$debug) error_log(__METHOD__." could not fetch/calculate unseen counter for $_folderName Reason:'".$ee->getMessage()."' but requested.");
1488
+					if (self::$debug)
1489
+					{
1490
+						error_log(__METHOD__." could not fetch/calculate unseen counter for $_folderName Reason:'".$ee->getMessage()."' but requested.");
1491
+					}
1317 1492
 				}
1318 1493
 			}
1319 1494
 		}
1320 1495
 		catch (\Exception $e)
1321 1496
 		{
1322
-			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(),true));
1497
+			if (self::$debug)
1498
+			{
1499
+				error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(),true));
1500
+			}
1323 1501
 		}
1324 1502
 
1325 1503
 		return $retValue;
@@ -1344,8 +1522,14 @@  discard block
 block discarded – undo
1344 1522
 	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly=null, $_cacheResult=true, $_fetchPreviews=false)
1345 1523
 	{
1346 1524
 		//self::$debug=true;
1347
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.function_backtrace());
1348
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$_folderName,$_startMessage, $_numberOfMessages, $_sort, $_reverse, ".array2string($_filter).", $_thisUIDOnly");
1525
+		if (self::$debug)
1526
+		{
1527
+			error_log(__METHOD__.' ('.__LINE__.') '.function_backtrace());
1528
+		}
1529
+		if (self::$debug)
1530
+		{
1531
+			error_log(__METHOD__.' ('.__LINE__.') '."$_folderName,$_startMessage, $_numberOfMessages, $_sort, $_reverse, ".array2string($_filter).", $_thisUIDOnly");
1532
+		}
1349 1533
 		$reverse = (bool)$_reverse;
1350 1534
 		// get the list of messages to fetch
1351 1535
 		$this->reopen($_folderName);
@@ -1366,21 +1550,34 @@  discard block
 block discarded – undo
1366 1550
 				//$_filter['range'] ="$start:$end";
1367 1551
 				//$_filter['range'] ="$_startMessage:*";
1368 1552
 			}
1369
-			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_sort, $reverse, ".array2string($_filter).", $rByUid");
1370
-			if (self::$debug||self::$debugTimes) $starttime = microtime (true);
1553
+			if (self::$debug)
1554
+			{
1555
+				error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_sort, $reverse, ".array2string($_filter).", $rByUid");
1556
+			}
1557
+			if (self::$debug||self::$debugTimes)
1558
+			{
1559
+				$starttime = microtime (true);
1560
+			}
1371 1561
 			//see this example below for a 12 week datefilter (since)
1372 1562
 			//$_filter = array('status'=>array('UNDELETED'),'type'=>"SINCE",'string'=> date("d-M-Y", $starttime-(3600*24*7*12)));
1373 1563
 			$_sortResult = $this->getSortedList($_folderName, $_sort, $reverse, $_filter, $rByUid, $_cacheResult);
1374 1564
 			$sortResult = $_sortResult['match']->ids;
1375 1565
 			//$modseq = $_sortResult['modseq'];
1376 1566
 			//error_log(__METHOD__.' ('.__LINE__.') '.'Modsequence:'.$modseq);
1377
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly),__METHOD__.' ('.__LINE__.') ');
1567
+			if (self::$debug||self::$debugTimes)
1568
+			{
1569
+				self::logRunTimes($starttime,null,' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly),__METHOD__.' ('.__LINE__.') ');
1570
+			}
1378 1571
 
1379
-			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1572
+			if (self::$debug)
1573
+			{
1574
+				error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1575
+			}
1380 1576
 			#$this->icServer->setDebug(false);
1381 1577
 			#print "</pre>";
1382 1578
 			// nothing found
1383
-			if(!is_array($sortResult) || empty($sortResult)) {
1579
+			if(!is_array($sortResult) || empty($sortResult))
1580
+			{
1384 1581
 				$retValue = array();
1385 1582
 				$retValue['info']['total']	= 0;
1386 1583
 				$retValue['info']['first']	= 0;
@@ -1392,7 +1589,8 @@  discard block
 block discarded – undo
1392 1589
 			#_debug_array($sortResult);
1393 1590
 			#_debug_array(array_slice($sortResult, -5, -2));
1394 1591
 			//error_log("REVERSE: $reverse");
1395
-			if($reverse === true) {
1592
+			if($reverse === true)
1593
+			{
1396 1594
 				if  ($_startMessage<=$total)
1397 1595
 				{
1398 1596
 					$startMessage = $_startMessage-1;
@@ -1404,7 +1602,10 @@  discard block
 block discarded – undo
1404 1602
 					{
1405 1603
 						$numberOfMessages = $total%$_numberOfMessages;
1406 1604
 						//$numberOfMessages = abs($_startMessage-$total-1);
1407
-						if ($numberOfMessages>0 && $numberOfMessages<=$_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1605
+						if ($numberOfMessages>0 && $numberOfMessages<=$_numberOfMessages)
1606
+						{
1607
+							$_numberOfMessages = $numberOfMessages;
1608
+						}
1408 1609
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1409 1610
 					}
1410 1611
 					$startMessage=($total-$_numberOfMessages)-1;
@@ -1418,19 +1619,36 @@  discard block
 block discarded – undo
1418 1619
 					//$retValue['info']['first'] = $startMessage;
1419 1620
 					//$retValue['info']['last'] = $total;
1420 1621
 				}
1421
-				if($startMessage > 0) {
1422
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+$startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1622
+				if($startMessage > 0)
1623
+				{
1624
+					if (self::$debug)
1625
+					{
1626
+						error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+$startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1627
+					}
1423 1628
 					$sortResult = array_slice($sortResult, -($_numberOfMessages+$startMessage), -$startMessage);
1424
-				} else {
1425
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+($_startMessage-1))).', AllTheRest, Number of Messages:'.count($sortResult));
1629
+				}
1630
+				else
1631
+				{
1632
+					if (self::$debug)
1633
+					{
1634
+						error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+($_startMessage-1))).', AllTheRest, Number of Messages:'.count($sortResult));
1635
+					}
1426 1636
 					$sortResult = array_slice($sortResult, -($_numberOfMessages+($_startMessage-1)));
1427 1637
 				}
1428 1638
 				$sortResult = array_reverse($sortResult);
1429
-			} else {
1430
-				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage-1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1639
+			}
1640
+			else
1641
+			{
1642
+				if (self::$debug)
1643
+				{
1644
+					error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage-1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1645
+				}
1431 1646
 				$sortResult = array_slice($sortResult, $_startMessage-1, $_numberOfMessages);
1432 1647
 			}
1433
-			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1648
+			if (self::$debug)
1649
+			{
1650
+				error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1651
+			}
1434 1652
 		}
1435 1653
 		else
1436 1654
 		{
@@ -1439,7 +1657,10 @@  discard block
 block discarded – undo
1439 1657
 
1440 1658
 
1441 1659
 		// fetch the data for the selected messages
1442
-		if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1660
+		if (self::$debug||self::$debugTimes)
1661
+		{
1662
+			$starttime = microtime(true);
1663
+		}
1443 1664
 		try
1444 1665
 		{
1445 1666
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -1463,7 +1684,10 @@  discard block
 block discarded – undo
1463 1684
 			$fquery->flags();
1464 1685
 			$fquery->imapDate();// needed to ensure getImapDate fetches the internaldate, not the current time
1465 1686
 			// if $_fetchPreviews is activated fetch part of the messages too
1466
-			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true,'length'=>((int)$_fetchPreviews<5000?5000:$_fetchPreviews),'start'=>0));
1687
+			if ($_fetchPreviews)
1688
+			{
1689
+				$fquery->fullText(array('peek'=>true,'length'=>((int)$_fetchPreviews<5000?5000:$_fetchPreviews),'start'=>0));
1690
+			}
1467 1691
 			$headersNew = $this->icServer->fetch($_folderName, $fquery, array(
1468 1692
 				'ids' => $uidsToFetch,
1469 1693
 			));
@@ -1486,14 +1710,20 @@  discard block
 block discarded – undo
1486 1710
 
1487 1711
 		$cnt = 0;
1488 1712
 
1489
-		foreach((array)$sortResult as $uid) {
1713
+		foreach((array)$sortResult as $uid)
1714
+		{
1490 1715
 			$sortOrder[$uid] = $cnt++;
1491 1716
 		}
1492 1717
 
1493 1718
 		$count = 0;
1494
-		if (is_object($headersNew)) {
1495
-			if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1496
-			foreach($headersNew->ids() as $id) {
1719
+		if (is_object($headersNew))
1720
+		{
1721
+			if (self::$debug||self::$debugTimes)
1722
+			{
1723
+				$starttime = microtime(true);
1724
+			}
1725
+			foreach($headersNew->ids() as $id)
1726
+			{
1497 1727
 				$_headerObject = $headersNew->get($id);
1498 1728
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject));
1499 1729
 				$headerObject = array();
@@ -1506,7 +1736,10 @@  discard block
 block discarded – undo
1506 1736
 				// Get already cached headers, 'fetchHeaders' is a label matchimg above
1507 1737
 				$headerForPrio = $_headerObject->getHeaders('fetchHeaders',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1508 1738
 				// Try to fetch header with key='' as some servers might have no fetchHeaders index. e.g. yandex.com
1509
-				if (empty($headerForPrio)) $headerForPrio = $_headerObject->getHeaders('',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1739
+				if (empty($headerForPrio))
1740
+				{
1741
+					$headerForPrio = $_headerObject->getHeaders('',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1742
+				}
1510 1743
 				//fetch the fullMsg part if all conditions match to be available in case $_headerObject->getHeaders returns
1511 1744
 				//nothing worthwhile (as it does for googlemail accounts, when preview is switched on
1512 1745
 				if ($_fetchPreviews)
@@ -1517,12 +1750,16 @@  discard block
 block discarded – undo
1517 1750
 					if (empty($headerForPrio)||(is_array($headerForPrio)&&count($headerForPrio)===1&&$headerForPrio['']))
1518 1751
 					{
1519 1752
 						$length = strpos($bodyPreview, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
1520
-						if ($length===false) $length = strlen($bodyPreview);
1753
+						if ($length===false)
1754
+						{
1755
+							$length = strlen($bodyPreview);
1756
+						}
1521 1757
 						$headerForPrio =  Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0,$length))->toArray();
1522 1758
 					}
1523 1759
 				}
1524 1760
 				$headerForPrio = array_change_key_case($headerForPrio, CASE_UPPER);
1525
-				if (self::$debug) {
1761
+				if (self::$debug)
1762
+				{
1526 1763
 					error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject).'UID:'.$_headerObject->getUid().' Size:'.$_headerObject->getSize().' Date:'.$_headerObject->getImapDate().'/'.DateTime::to($_headerObject->getImapDate(),'Y-m-d H:i:s'));
1527 1764
 					error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerForPrio));
1528 1765
 				}
@@ -1532,11 +1769,16 @@  discard block
 block discarded – undo
1532 1769
 					$total--;
1533 1770
 					continue;
1534 1771
 				}
1535
-				if ( isset($headerForPrio['DISPOSITION-NOTIFICATION-TO']) ) {
1772
+				if ( isset($headerForPrio['DISPOSITION-NOTIFICATION-TO']) )
1773
+				{
1536 1774
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['DISPOSITION-NOTIFICATION-TO']));
1537
-				} else if ( isset($headerForPrio['RETURN-RECEIPT-TO']) ) {
1775
+				}
1776
+				else if ( isset($headerForPrio['RETURN-RECEIPT-TO']) )
1777
+				{
1538 1778
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['RETURN-RECEIPT-TO']));
1539
-				} else if ( isset($headerForPrio['X-CONFIRM-READING-TO']) ) {
1779
+				}
1780
+				else if ( isset($headerForPrio['X-CONFIRM-READING-TO']) )
1781
+				{
1540 1782
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['X-CONFIRM-READING-TO']));
1541 1783
 				} /*else $sent_not = "";*/
1542 1784
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
@@ -1568,7 +1810,11 @@  discard block
 block discarded – undo
1568 1810
 						$rfcAddr = self::parseAddressList($ad); // does some fixing of known problems too
1569 1811
 						foreach ($rfcAddr as $_rfcAddr)
1570 1812
 						{
1571
-							if (!$_rfcAddr->valid)	continue; // skip. not a valid address
1813
+							if (!$_rfcAddr->valid)
1814
+							{
1815
+								continue;
1816
+							}
1817
+							// skip. not a valid address
1572 1818
 							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox,$_rfcAddr->host,$_rfcAddr->personal);
1573 1819
 						}
1574 1820
 					}
@@ -1584,7 +1830,10 @@  discard block
 block discarded – undo
1584 1830
 				{
1585 1831
 					// $bodyPreview is populated at the beginning of the loop, as it may be
1586 1832
 					// needed to parse the Headers of the Message
1587
-					if (empty($bodyPreview)) $bodyPreview = $_headerObject->getFullMsg();
1833
+					if (empty($bodyPreview))
1834
+					{
1835
+						$bodyPreview = $_headerObject->getFullMsg();
1836
+					}
1588 1837
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($bodyPreview));
1589 1838
 					$base = Horde_Mime_Part::parseMessage($bodyPreview);
1590 1839
 					foreach($base->partIterator() as $part)
@@ -1597,7 +1846,8 @@  discard block
 block discarded – undo
1597 1846
 												'encode' => Horde_Mime_Part::ENCODE_BINARY,	// otherwise we cant recode charset
1598 1847
 											)), $charset, 'utf-8');
1599 1848
 							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Translation::convert_jsonsafe($buffer),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1600
-						} elseif (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'multipart')
1849
+						}
1850
+						elseif (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'multipart')
1601 1851
 						{
1602 1852
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part));
1603 1853
 						}
@@ -1613,7 +1863,10 @@  discard block
 block discarded – undo
1613 1863
 				$messageMimeType='';
1614 1864
 				foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
1615 1865
 				{
1616
-					if ($mime_id==0 || $messageMimeType==='') $messageMimeType = $mime_type;
1866
+					if ($mime_id==0 || $messageMimeType==='')
1867
+					{
1868
+						$messageMimeType = $mime_type;
1869
+					}
1617 1870
 					$part = $mailStructureObject->getPart($mime_id);
1618 1871
 					$partdisposition = $part->getDisposition();
1619 1872
 					$partPrimaryType = $part->getPrimaryType();
@@ -1623,7 +1876,8 @@  discard block
 block discarded – undo
1623 1876
 					// bodypreview could be found (multipart/....)
1624 1877
 					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW'])&&($partPrimaryType == 'text') &&
1625 1878
 						((intval($mime_id) === 1) || !$mime_id) &&
1626
-						($partdisposition !== 'attachment')) {
1879
+						($partdisposition !== 'attachment'))
1880
+					{
1627 1881
 							$_structure=$part;
1628 1882
 							$this->fetchPartContents($uid, $_structure, false,true);
1629 1883
 							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
@@ -1645,10 +1899,19 @@  discard block
 block discarded – undo
1645 1899
 					if ($mime_type=='message/rfc822')
1646 1900
 					{
1647 1901
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
1648
-						foreach($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
1902
+						foreach($part->contentTypeMap() as $sub_id => $sub_type)
1903
+						{
1904
+if ($sub_id != $mime_id)
1905
+						{
1906
+							$skipParts[$sub_id] = $sub_type;
1907
+						}
1908
+						}
1649 1909
 					}
1650 1910
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType.' Skip:'.array2string($skipParts));
1651
-					if (array_key_exists($mime_id,$skipParts)) continue;
1911
+					if (array_key_exists($mime_id,$skipParts))
1912
+					{
1913
+						continue;
1914
+					}
1652 1915
 					if ($partdisposition=='attachment' ||
1653 1916
 						($partdisposition=='inline'&&$partPrimaryType == 'image'&&$mime_type=='image/tiff') || // as we are not able to display tiffs
1654 1917
 						($partdisposition=='inline'&&$partPrimaryType == 'image'&&empty($cid)) ||
@@ -1659,7 +1922,10 @@  discard block
 block discarded – undo
1659 1922
 						$headerObject['ATTACHMENTS'][$mime_id]['uid']=$uid;
1660 1923
 						$headerObject['ATTACHMENTS'][$mime_id]['cid'] = $cid;
1661 1924
 						$headerObject['ATTACHMENTS'][$mime_id]['partID']=$mime_id;
1662
-						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))$headerObject['ATTACHMENTS'][$mime_id]['name']=$part->getName();
1925
+						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))
1926
+						{
1927
+							$headerObject['ATTACHMENTS'][$mime_id]['name']=$part->getName();
1928
+						}
1663 1929
 						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'],'winmail.dat') ||
1664 1930
 							$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=='application/ms-tnef')
1665 1931
 						{
@@ -1673,18 +1939,27 @@  discard block
 block discarded – undo
1673 1939
 				//error_log(__METHOD__.' ('.__LINE__.') '.' FindBody (plain):'.array2string($mailStructureObject->findBody('plain')));
1674 1940
 				//error_log(__METHOD__.' ('.__LINE__.') '.' FindBody (html):'.array2string($mailStructureObject->findBody('html')));
1675 1941
 				//if($count == 0) error_log(__METHOD__.array2string($headerObject));
1676
-				if (empty($headerObject['UID'])) continue;
1942
+				if (empty($headerObject['UID']))
1943
+				{
1944
+					continue;
1945
+				}
1677 1946
 				//$uid = ($rByUid ? $headerObject['UID'] : $headerObject['MSG_NUM']);
1678 1947
 				// make dates like "Mon, 23 Apr 2007 10:11:06 UT" working with strtotime
1679
-				if(substr($headerObject['DATE'],-2) === 'UT') {
1948
+				if(substr($headerObject['DATE'],-2) === 'UT')
1949
+				{
1680 1950
 					$headerObject['DATE'] .= 'C';
1681 1951
 				}
1682
-				if(substr($headerObject['INTERNALDATE'],-2) === 'UT') {
1952
+				if(substr($headerObject['INTERNALDATE'],-2) === 'UT')
1953
+				{
1683 1954
 					$headerObject['INTERNALDATE'] .= 'C';
1684 1955
 				}
1685 1956
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$headerObject['SUBJECT'].'->'.$headerObject['DATE'].'<->'.$headerObject['INTERNALDATE'] .'#');
1686 1957
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$this->decode_subject($headerObject['SUBJECT']).'->'.$headerObject['DATE']);
1687
-				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][]=$a;}
1958
+				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS']))
1959
+				{
1960
+					foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][]=$a;
1961
+				}
1962
+				}
1688 1963
 				$retValue['header'][$sortOrder[$uid]]['subject']	= $this->decode_subject($headerObject['SUBJECT']);
1689 1964
 				$retValue['header'][$sortOrder[$uid]]['size'] 		= $headerObject['SIZE'];
1690 1965
 				$retValue['header'][$sortOrder[$uid]]['date']		= self::_strtotime(($headerObject['DATE']&&!($headerObject['DATE']=='NIL')?$headerObject['DATE']:$headerObject['INTERNALDATE']),'ts',true);
@@ -1695,25 +1970,35 @@  discard block
 block discarded – undo
1695 1970
 				$retValue['header'][$sortOrder[$uid]]['bodypreview']		= $headerObject['BODYPREVIEW'];
1696 1971
 				$retValue['header'][$sortOrder[$uid]]['priority']		= ($headerObject['PRIORITY']?$headerObject['PRIORITY']:3);
1697 1972
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.array2string($retValue['header'][$sortOrder[$uid]]));
1698
-				if (isset($headerObject['DISPOSITION-NOTIFICATION-TO'])) $retValue['header'][$sortOrder[$uid]]['disposition-notification-to'] = $headerObject['DISPOSITION-NOTIFICATION-TO'];
1699
-				if (is_array($headerObject['FLAGS'])) {
1973
+				if (isset($headerObject['DISPOSITION-NOTIFICATION-TO']))
1974
+				{
1975
+					$retValue['header'][$sortOrder[$uid]]['disposition-notification-to'] = $headerObject['DISPOSITION-NOTIFICATION-TO'];
1976
+				}
1977
+				if (is_array($headerObject['FLAGS']))
1978
+				{
1700 1979
 					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]],self::prepareFlagsArray($headerObject));
1701 1980
 				}
1702 1981
 				//error_log(__METHOD__.' ('.__LINE__.') '.$headerObject['SUBJECT'].'->'.array2string($_headerObject->getEnvelope()->__get('from')));
1703
-				if(is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1982
+				if(is_array($headerObject['FROM']) && $headerObject['FROM'][0])
1983
+				{
1704 1984
 					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0],true);
1705 1985
 				}
1706
-				if(is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0]) {
1986
+				if(is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0])
1987
+				{
1707 1988
 					$retValue['header'][$sortOrder[$uid]]['reply_to_address'] = self::decode_header($headerObject['REPLY-TO'][0],true);
1708 1989
 				}
1709
-				if(is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1990
+				if(is_array($headerObject['TO']) && $headerObject['TO'][0])
1991
+				{
1710 1992
 					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0],true);
1711 1993
 					if (count($headerObject['TO'])>1)
1712 1994
 					{
1713 1995
 						$ki=0;
1714 1996
 						foreach($headerObject['TO'] as $k => $add)
1715 1997
 						{
1716
-							if ($k==0) continue;
1998
+							if ($k==0)
1999
+							{
2000
+								continue;
2001
+							}
1717 2002
 							//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1718 2003
 							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add,true);
1719 2004
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
@@ -1721,7 +2006,8 @@  discard block
 block discarded – undo
1721 2006
 						}
1722 2007
 					}
1723 2008
 				}
1724
-				if(is_array($headerObject['CC']) && count($headerObject['CC'])>0) {
2009
+				if(is_array($headerObject['CC']) && count($headerObject['CC'])>0)
2010
+				{
1725 2011
 					$ki=0;
1726 2012
 					foreach($headerObject['CC'] as $k => $add)
1727 2013
 					{
@@ -1735,27 +2021,41 @@  discard block
 block discarded – undo
1735 2021
 
1736 2022
 				$count++;
1737 2023
 			}
1738
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' fetching Headers and stuff for Folder:'.$_folderName,__METHOD__.' ('.__LINE__.') ');
2024
+			if (self::$debug||self::$debugTimes)
2025
+			{
2026
+				self::logRunTimes($starttime,null,' fetching Headers and stuff for Folder:'.$_folderName,__METHOD__.' ('.__LINE__.') ');
2027
+			}
1739 2028
 			//self::$debug=false;
1740 2029
 			// sort the messages to the requested displayorder
1741
-			if(is_array($retValue['header'])) {
2030
+			if(is_array($retValue['header']))
2031
+			{
1742 2032
 				$countMessages = $total;
1743
-				if (isset($_filter['range'])) $countMessages = self::$folderStatusCache[$this->profileID][$_folderName]['messages'];
2033
+				if (isset($_filter['range']))
2034
+				{
2035
+					$countMessages = self::$folderStatusCache[$this->profileID][$_folderName]['messages'];
2036
+				}
1744 2037
 				ksort($retValue['header']);
1745 2038
 				$retValue['info']['total']	= $total;
1746 2039
 				//if ($_startMessage>$total) $_startMessage = $total-($count-1);
1747 2040
 				$retValue['info']['first']	= $_startMessage;
1748 2041
 				$retValue['info']['last']	= $_startMessage + $count - 1 ;
1749 2042
 				return $retValue;
1750
-			} else {
2043
+			}
2044
+			else
2045
+			{
1751 2046
 				$retValue = array();
1752 2047
 				$retValue['info']['total']	= 0;
1753 2048
 				$retValue['info']['first']	= 0;
1754 2049
 				$retValue['info']['last']	= 0;
1755 2050
 				return $retValue;
1756 2051
 			}
1757
-		} else {
1758
-			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew,TRUE));
2052
+		}
2053
+		else
2054
+		{
2055
+			if ($headersNew == null && empty($_thisUIDOnly))
2056
+			{
2057
+				error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew,TRUE));
2058
+			}
1759 2059
 			$retValue = array();
1760 2060
 			$retValue['info']['total']  = 0;
1761 2061
 			$retValue['info']['first']  = 0;
@@ -1772,7 +2072,10 @@  discard block
 block discarded – undo
1772 2072
 	 */
1773 2073
 	static function prepareFlagsArray($headerObject)
1774 2074
 	{
1775
-		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower',$headerObject['FLAGS']);
2075
+		if (is_array($headerObject['FLAGS']))
2076
+		{
2077
+			$headerFlags = array_map('strtolower',$headerObject['FLAGS']);
2078
+		}
1776 2079
 		$retValue = array();
1777 2080
 		$retValue['recent']		= in_array('\\recent', $headerFlags);
1778 2081
 		$retValue['flagged']	= in_array('\\flagged', $headerFlags);
@@ -1823,26 +2126,45 @@  discard block
 block discarded – undo
1823 2126
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Filter:'.array2string($_filter));
1824 2127
 		$try2useCache = true;
1825 2128
 		static $eMailListContainsDeletedMessages = null;
1826
-		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2129
+		if (is_null($eMailListContainsDeletedMessages))
2130
+		{
2131
+			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2132
+		}
1827 2133
 		// this indicates, that there is no Filter set, and the returned set/subset should not contain DELETED Messages, nor filtered for UNDELETED
1828 2134
 		if ($setSession==true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1829 2135
 		{
1830
-			if (self::$debugTimes) $starttime = microtime(true);
1831
-			if (is_null($eMailListContainsDeletedMessages) || empty($eMailListContainsDeletedMessages[$this->profileID]) || empty($eMailListContainsDeletedMessages[$this->profileID][$_folderName])) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2136
+			if (self::$debugTimes)
2137
+			{
2138
+				$starttime = microtime(true);
2139
+			}
2140
+			if (is_null($eMailListContainsDeletedMessages) || empty($eMailListContainsDeletedMessages[$this->profileID]) || empty($eMailListContainsDeletedMessages[$this->profileID][$_folderName]))
2141
+			{
2142
+				$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2143
+			}
1832 2144
 			$five=true;
1833 2145
 			$dReverse=1;
1834 2146
 			$deletedMessages = $this->getSortedList($_folderName, 0, $dReverse, array('status'=>array('DELETED')),$five,false);
1835
-			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') Found DeletedMessages:'.array2string($eMailListContainsDeletedMessages));
1836
-			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] =$deletedMessages['count'];
1837
-			Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),$eMailListContainsDeletedMessages, 60*60*1);
1838
-			if (self::$debugTimes) self::logRunTimes($starttime,null,'setting eMailListContainsDeletedMessages for Profile:'.$this->profileID.' Folder:'.$_folderName.' to '.$eMailListContainsDeletedMessages[$this->profileID][$_folderName],__METHOD__.' ('.__LINE__.') ');			//error_log(__METHOD__.' ('.__LINE__.') '.' Profile:'.$this->profileID.' Folder:'.$_folderName.' -> EXISTS/SessStat:'.array2string($folderStatus['MESSAGES']).'/'.self::$folderStatusCache[$this->profileID][$_folderName]['messages'].' ListContDelMsg/SessDeleted:'.$eMailListContainsDeletedMessages[$this->profileID][$_folderName].'/'.self::$folderStatusCache[$this->profileID][$_folderName]['deleted']);
2147
+			if (self::$debug)
2148
+			{
2149
+				error_log(__METHOD__.' ('.__LINE__.') Found DeletedMessages:'.array2string($eMailListContainsDeletedMessages));
2150
+			}
2151
+			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] =$deletedMessages['count'];
2152
+			Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),$eMailListContainsDeletedMessages, 60*60*1);
2153
+			if (self::$debugTimes)
2154
+			{
2155
+				self::logRunTimes($starttime,null,'setting eMailListContainsDeletedMessages for Profile:'.$this->profileID.' Folder:'.$_folderName.' to '.$eMailListContainsDeletedMessages[$this->profileID][$_folderName],__METHOD__.' ('.__LINE__.') ');
2156
+			}
2157
+			//error_log(__METHOD__.' ('.__LINE__.') '.' Profile:'.$this->profileID.' Folder:'.$_folderName.' -> EXISTS/SessStat:'.array2string($folderStatus['MESSAGES']).'/'.self::$folderStatusCache[$this->profileID][$_folderName]['messages'].' ListContDelMsg/SessDeleted:'.$eMailListContainsDeletedMessages[$this->profileID][$_folderName].'/'.self::$folderStatusCache[$this->profileID][$_folderName]['deleted']);
1839 2158
 		}
1840 2159
 		$try2useCache = false;
1841 2160
 		//self::$supportsORinQuery[$this->profileID]=true;
1842 2161
 		if (is_null(self::$supportsORinQuery) || !isset(self::$supportsORinQuery[$this->profileID]))
1843 2162
 		{
1844 2163
 			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
1845
-			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID]=true;
2164
+			if (!isset(self::$supportsORinQuery[$this->profileID]))
2165
+			{
2166
+				self::$supportsORinQuery[$this->profileID]=true;
2167
+			}
1846 2168
 		}
1847 2169
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_filter).' SupportsOrInQuery:'.self::$supportsORinQuery[$this->profileID]);
1848 2170
 		$filter = $this->createIMAPFilter($_folderName, $_filter,self::$supportsORinQuery[$this->profileID]);
@@ -1853,15 +2175,26 @@  discard block
 block discarded – undo
1853 2175
 		}
1854 2176
 		//_debug_array($filter);
1855 2177
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($filter).'#'.array2string($this->icServer->capability()));
1856
-		if($this->icServer->hasCapability('SORT')) {
2178
+		if($this->icServer->hasCapability('SORT'))
2179
+		{
1857 2180
 			// when using an orQuery and we sort by date. sort seems to fail on certain servers => ZIMBRA with Horde_Imap_Client
1858 2181
 			// thus we translate the search request from date to Horde_Imap_Client::SORT_SEQUENCE (which should be the same, if
1859 2182
 			// there is no messing with the dates)
1860 2183
 			//if (self::$supportsORinQuery[$this->profileID]&&$_sort=='date'&&$_filter['type']=='quick'&&!empty($_filter['string']))$_sort='INTERNALDATE';
1861
-			if (self::$debug) error_log(__METHOD__." Mailserver has SORT Capability, SortBy: ".array2string($_sort)." Reverse: $_reverse");
2184
+			if (self::$debug)
2185
+			{
2186
+				error_log(__METHOD__." Mailserver has SORT Capability, SortBy: ".array2string($_sort)." Reverse: $_reverse");
2187
+			}
1862 2188
 			$sortOrder = $this->_getSortString($_sort, $_reverse);
1863
-			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE,$sortOrder)) $_reverse=false; // as we reversed the result already
1864
-			if (self::$debug) error_log(__METHOD__." Mailserver runs SORT: SortBy:".array2string($_sort)."->".array2string($sortOrder)." Filter: ".array2string($filter));
2189
+			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE,$sortOrder))
2190
+			{
2191
+				$_reverse=false;
2192
+			}
2193
+			// as we reversed the result already
2194
+			if (self::$debug)
2195
+			{
2196
+				error_log(__METHOD__." Mailserver runs SORT: SortBy:".array2string($_sort)."->".array2string($sortOrder)." Filter: ".array2string($filter));
2197
+			}
1865 2198
 			try
1866 2199
 			{
1867 2200
 				$sortResult = $this->icServer->search($_folderName, $filter, array(
@@ -1873,7 +2206,10 @@  discard block
 block discarded – undo
1873 2206
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1874 2207
 				$resultByUid = false;
1875 2208
 				$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
1876
-				if ($_reverse) array_unshift($sortOrder,Horde_Imap_Client::SORT_REVERSE);
2209
+				if ($_reverse)
2210
+				{
2211
+					array_unshift($sortOrder,Horde_Imap_Client::SORT_REVERSE);
2212
+				}
1877 2213
 				try
1878 2214
 				{
1879 2215
 					$sortResult = $this->icServer->search($_folderName, $filter, array(
@@ -1885,9 +2221,17 @@  discard block
 block discarded – undo
1885 2221
 					$sortResult = self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'];
1886 2222
 				}
1887 2223
 			}
1888
-			if (self::$debug) error_log(__METHOD__.print_r($sortResult,true));
1889
-		} else {
1890
-			if (self::$debug) error_log(__METHOD__." Mailserver has NO SORT Capability");
2224
+			if (self::$debug)
2225
+			{
2226
+				error_log(__METHOD__.print_r($sortResult,true));
2227
+			}
2228
+		}
2229
+		else
2230
+		{
2231
+			if (self::$debug)
2232
+			{
2233
+				error_log(__METHOD__." Mailserver has NO SORT Capability");
2234
+			}
1891 2235
 			//$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
1892 2236
 			//if ($_reverse) array_unshift($sortOrder,Horde_Imap_Client::SORT_REVERSE);
1893 2237
 			try
@@ -1901,7 +2245,10 @@  discard block
 block discarded – undo
1901 2245
 				// possible error OR Query. But Horde gives no detailed Info :-(
1902 2246
 				self::$supportsORinQuery[$this->profileID]=false;
1903 2247
 				Cache::setCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),self::$supportsORinQuery,60*60*10);
1904
-				if (self::$debug) error_log(__METHOD__.__LINE__." Mailserver seems to have NO OR Capability for Search:".$sortResult->message);
2248
+				if (self::$debug)
2249
+				{
2250
+					error_log(__METHOD__.__LINE__." Mailserver seems to have NO OR Capability for Search:".$sortResult->message);
2251
+				}
1905 2252
 				$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1906 2253
 				try
1907 2254
 				{
@@ -1912,11 +2259,15 @@  discard block
 block discarded – undo
1912 2259
 				{
1913 2260
 				}
1914 2261
 			}
1915
-			if(is_array($sortResult['match'])) {
2262
+			if(is_array($sortResult['match']))
2263
+			{
1916 2264
 					// not sure that this is going so succeed as $sortResult['match'] is a hordeObject
1917 2265
 					sort($sortResult['match'], SORT_NUMERIC);
1918 2266
 			}
1919
-			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
2267
+			if (self::$debug)
2268
+			{
2269
+				error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
2270
+			}
1920 2271
 		}
1921 2272
 		if ($setSession)
1922 2273
 		{
@@ -1945,7 +2296,8 @@  discard block
 block discarded – undo
1945 2296
 		$_reverse=false;
1946 2297
 		if (is_numeric($_sort))
1947 2298
 		{
1948
-			switch($_sort) {
2299
+			switch($_sort)
2300
+			{
1949 2301
 				case 2:
1950 2302
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1951 2303
 					break;
@@ -1967,7 +2319,8 @@  discard block
 block discarded – undo
1967 2319
 		}
1968 2320
 		else
1969 2321
 		{
1970
-			switch(strtoupper($_sort)) {
2322
+			switch(strtoupper($_sort))
2323
+			{
1971 2324
 				case 'FROMADDRESS':
1972 2325
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1973 2326
 					break;
@@ -1993,7 +2346,10 @@  discard block
 block discarded – undo
1993 2346
 					break;
1994 2347
 			}
1995 2348
 		}
1996
-		if ($_reverse) array_unshift($retValue,Horde_Imap_Client::SORT_REVERSE);
2349
+		if ($_reverse)
2350
+		{
2351
+			array_unshift($retValue,Horde_Imap_Client::SORT_REVERSE);
2352
+		}
1997 2353
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.($_reverse?'REVERSE ':'').$_sort.'->'.$retValue);
1998 2354
 		return $retValue;
1999 2355
 	}
@@ -2012,7 +2368,10 @@  discard block
 block discarded – undo
2012 2368
 		$imapFilter->charset('UTF-8');
2013 2369
 
2014 2370
 		//_debug_array($_criterias);
2015
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2371
+		if (self::$debug)
2372
+		{
2373
+			error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2374
+		}
2016 2375
 		if((!is_array($_criterias) || $_criterias['status']=='any') &&
2017 2376
 			(!isset($_criterias['string']) || empty($_criterias['string'])) &&
2018 2377
 			(!isset($_criterias['range'])|| empty($_criterias['range']) ||
@@ -2027,11 +2386,13 @@  discard block
 block discarded – undo
2027 2386
 		// statusQuery MUST be placed first, as search for subject/mailbody and such is
2028 2387
 		// depending on charset. flagSearch is not BUT messes the charset if called afterwards
2029 2388
 		$statusQueryValid = false;
2030
-		foreach((array)$_criterias['status'] as $k => $criteria) {
2389
+		foreach((array)$_criterias['status'] as $k => $criteria)
2390
+		{
2031 2391
 			$imapStatusFilter = new Horde_Imap_Client_Search_Query();
2032 2392
 			$imapStatusFilter->charset('UTF-8');
2033 2393
 			$criteria = strtoupper($criteria);
2034
-			switch ($criteria) {
2394
+			switch ($criteria)
2395
+			{
2035 2396
 				case 'ANSWERED':
2036 2397
 				case 'DELETED':
2037 2398
 				case 'FLAGGED':
@@ -2114,9 +2475,11 @@  discard block
 block discarded – undo
2114 2475
 		$imapSearchFilter = new Horde_Imap_Client_Search_Query();
2115 2476
 		$imapSearchFilter->charset('UTF-8');
2116 2477
 
2117
-		if(!empty($_criterias['string'])) {
2478
+		if(!empty($_criterias['string']))
2479
+		{
2118 2480
 			$criteria = strtoupper($_criterias['type']);
2119
-			switch ($criteria) {
2481
+			switch ($criteria)
2482
+			{
2120 2483
 				case 'BYDATE':
2121 2484
 				case 'QUICK':
2122 2485
 				case 'QUICKWITHCC':
@@ -2124,9 +2487,12 @@  discard block
 block discarded – undo
2124 2487
 					//$imapSearchFilter->charset('UTF-8');
2125 2488
 					$imapFilter2 = new Horde_Imap_Client_Search_Query();
2126 2489
 					$imapFilter2->charset('UTF-8');
2127
-					if($this->isSentFolder($_folder)) {
2490
+					if($this->isSentFolder($_folder))
2491
+					{
2128 2492
 						$imapFilter2->headerText('TO', $_criterias['string'], $not=false);
2129
-					} else {
2493
+					}
2494
+					else
2495
+					{
2130 2496
 						$imapFilter2->headerText('FROM', $_criterias['string'], $not=false);
2131 2497
 					}
2132 2498
 					if ($_supportsOrInQuery)
@@ -2157,7 +2523,10 @@  discard block
 block discarded – undo
2157 2523
 											'GB'=>1024*1000*1000,'G'=>1024*1000*1000,
2158 2524
 											'TB'=>1024*1000*1000*1000,'T'=>1024*1000*1000*1000);
2159 2525
 						$numberinBytes=(float)$_criterias['string'];
2160
-						if (isset($multipleBy[$unit])) $numberinBytes=(float)$_criterias['string']*$multipleBy[$unit];
2526
+						if (isset($multipleBy[$unit]))
2527
+						{
2528
+							$numberinBytes=(float)$_criterias['string']*$multipleBy[$unit];
2529
+						}
2161 2530
 						//error_log(__METHOD__.__LINE__.'#'.$_criterias['string'].'->'.(float)$_criterias['string'].'#'.$unit.' ='.$numberinBytes);
2162 2531
 						$_criterias['string']=$numberinBytes;
2163 2532
 					}
@@ -2194,8 +2563,14 @@  discard block
 block discarded – undo
2194 2563
 					break;
2195 2564
 			}
2196 2565
 		}
2197
-		if ($statusQueryValid && !$queryValid) $queryValid=true;
2198
-		if ($queryValid) $imapFilter->andSearch($imapSearchFilter);
2566
+		if ($statusQueryValid && !$queryValid)
2567
+		{
2568
+			$queryValid=true;
2569
+		}
2570
+		if ($queryValid)
2571
+		{
2572
+			$imapFilter->andSearch($imapSearchFilter);
2573
+		}
2199 2574
 
2200 2575
 		if (isset($_criterias['range']) && !empty($_criterias['range']))
2201 2576
 		{
@@ -2210,7 +2585,8 @@  discard block
 block discarded – undo
2210 2585
 				unset($_criterias['before']);
2211 2586
 				$criteria=$_criterias['range']='ON';
2212 2587
 			}
2213
-			switch ($criteria) {
2588
+			switch ($criteria)
2589
+			{
2214 2590
 				case 'BETWEEN':
2215 2591
 					//try to be smart about missing
2216 2592
 					//enddate
@@ -2246,8 +2622,14 @@  discard block
 block discarded – undo
2246 2622
 					$rangeValid = true;
2247 2623
 					break;
2248 2624
 			}
2249
-			if ($rangeValid && !$queryValid) $queryValid=true;
2250
-			if ($rangeValid) $imapFilter->andSearch($imapRangeFilter);
2625
+			if ($rangeValid && !$queryValid)
2626
+			{
2627
+				$queryValid=true;
2628
+			}
2629
+			if ($rangeValid)
2630
+			{
2631
+				$imapFilter->andSearch($imapRangeFilter);
2632
+			}
2251 2633
 		}
2252 2634
 		if (self::$debug)
2253 2635
 		{
@@ -2255,10 +2637,13 @@  discard block
 block discarded – undo
2255 2637
 			$query_str = $imapFilter->build();
2256 2638
 			//error_log(__METHOD__.' ('.__LINE__.') '.' '.$query_str['query'].' created by Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2257 2639
 		}
2258
-		if($queryValid==false) {
2640
+		if($queryValid==false)
2641
+		{
2259 2642
 			$imapFilter->flag('DELETED', $set=false);
2260 2643
 			return $imapFilter;
2261
-		} else {
2644
+		}
2645
+		else
2646
+		{
2262 2647
 			return $imapFilter;
2263 2648
 		}
2264 2649
 	}
@@ -2315,7 +2700,10 @@  discard block
 block discarded – undo
2315 2700
 					}
2316 2701
 					$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox,Horde_Idna::decode($_rfcAddr->host),$_rfcAddr->personal);
2317 2702
 				}
2318
-				if (!empty($stringA)) $_string = implode(',',$stringA);
2703
+				if (!empty($stringA))
2704
+				{
2705
+					$_string = implode(',',$stringA);
2706
+				}
2319 2707
 			}
2320 2708
 			if ($_tryIDNConversion==='FORCE')
2321 2709
 			{
@@ -2340,7 +2728,10 @@  discard block
 block discarded – undo
2340 2728
 		{
2341 2729
 			return 'No Subject';
2342 2730
 		}
2343
-		if ($decode) $_string = self::decode_header($_string);
2731
+		if ($decode)
2732
+		{
2733
+			$_string = self::decode_header($_string);
2734
+		}
2344 2735
 		// make sure its utf-8
2345 2736
 		$test = @json_encode($_string);
2346 2737
 		if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
@@ -2378,7 +2769,8 @@  discard block
 block discarded – undo
2378 2769
 	 * @param string _parent the parent foldername
2379 2770
 	 * @return ISO-8859-1 / UTF7-IMAP encoded string
2380 2771
 	 */
2381
-	function _encodeFolderName($_folderName) {
2772
+	function _encodeFolderName($_folderName)
2773
+	{
2382 2774
 		return Translation::convert($_folderName, self::$displayCharset, 'ISO-8859-1');
2383 2775
 		#return Translation::convert($_folderName, self::$displayCharset, 'UTF7-IMAP');
2384 2776
 	}
@@ -2394,21 +2786,36 @@  discard block
 block discarded – undo
2394 2786
 	 */
2395 2787
 	function createFolder($_parent, $_folderName, &$_error)
2396 2788
 	{
2397
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."->"."$_parent, $_folderName called from:".function_backtrace());
2789
+		if (self::$debug)
2790
+		{
2791
+			error_log(__METHOD__.' ('.__LINE__.') '."->"."$_parent, $_folderName called from:".function_backtrace());
2792
+		}
2398 2793
 		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2399 2794
 		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2400 2795
 
2401
-		if(empty($parent)) {
2796
+		if(empty($parent))
2797
+		{
2402 2798
 			$newFolderName = $folderName;
2403
-		} else {
2799
+		}
2800
+		else
2801
+		{
2404 2802
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2405 2803
 			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2406 2804
 		}
2407
-		if (empty($newFolderName)) return false;
2408
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.'->'.$newFolderName);
2805
+		if (empty($newFolderName))
2806
+		{
2807
+			return false;
2808
+		}
2809
+		if (self::$debug)
2810
+		{
2811
+			error_log(__METHOD__.' ('.__LINE__.') '.'->'.$newFolderName);
2812
+		}
2409 2813
 		if ($this->folderExists($newFolderName,true))
2410 2814
 		{
2411
-			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." Folder $newFolderName already exists.");
2815
+			if (self::$debug)
2816
+			{
2817
+				error_log(__METHOD__.' ('.__LINE__.') '." Folder $newFolderName already exists.");
2818
+			}
2412 2819
 			return $newFolderName;
2413 2820
 		}
2414 2821
 		try
@@ -2456,13 +2863,19 @@  discard block
 block discarded – undo
2456 2863
 		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2457 2864
 		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2458 2865
 
2459
-		if(empty($parent)) {
2866
+		if(empty($parent))
2867
+		{
2460 2868
 			$newFolderName = $folderName;
2461
-		} else {
2869
+		}
2870
+		else
2871
+		{
2462 2872
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2463 2873
 			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2464 2874
 		}
2465
-		if (self::$debug) error_log("create folder: $newFolderName");
2875
+		if (self::$debug)
2876
+		{
2877
+			error_log("create folder: $newFolderName");
2878
+		}
2466 2879
 		try
2467 2880
 		{
2468 2881
 			$this->icServer->renameMailbox($oldFolderName, $newFolderName);
@@ -2536,8 +2949,14 @@  discard block
 block discarded – undo
2536 2949
 	 */
2537 2950
 	function getFolderObjects($_subscribedOnly=false, $_getCounters=false, $_alwaysGetDefaultFolders=false,$_useCacheIfPossible=true)
2538 2951
 	{
2539
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' ServerID:'.$this->icServer->ImapServerId.", subscribedOnly:$_subscribedOnly, getCounters:$_getCounters, alwaysGetDefaultFolders:$_alwaysGetDefaultFolders, _useCacheIfPossible:$_useCacheIfPossible");
2540
-		if (self::$debugTimes) $starttime = microtime (true);
2952
+		if (self::$debug)
2953
+		{
2954
+			error_log(__METHOD__.' ('.__LINE__.') '.' ServerID:'.$this->icServer->ImapServerId.", subscribedOnly:$_subscribedOnly, getCounters:$_getCounters, alwaysGetDefaultFolders:$_alwaysGetDefaultFolders, _useCacheIfPossible:$_useCacheIfPossible");
2955
+		}
2956
+		if (self::$debugTimes)
2957
+		{
2958
+			$starttime = microtime (true);
2959
+		}
2541 2960
 		static $folders2return;
2542 2961
 		//$_subscribedOnly=false;
2543 2962
 		// always use static on single request if info is available;
@@ -2545,23 +2964,35 @@  discard block
 block discarded – undo
2545 2964
 		// set $_useCacheIfPossible to false !
2546 2965
 		if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2547 2966
 		{
2548
-			if (self::$debugTimes) self::logRunTimes($starttime,null,'using static',__METHOD__.' ('.__LINE__.') ');
2967
+			if (self::$debugTimes)
2968
+			{
2969
+				self::logRunTimes($starttime,null,'using static',__METHOD__.' ('.__LINE__.') ');
2970
+			}
2549 2971
 			return $folders2return[$this->icServer->ImapServerId];
2550 2972
 		}
2551 2973
 
2552 2974
 		if ($_subscribedOnly && $_getCounters===false)
2553 2975
 		{
2554
-			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2976
+			if (is_null($folders2return))
2977
+			{
2978
+				$folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2979
+			}
2555 2980
 			if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2556 2981
 			{
2557 2982
 				//error_log(__METHOD__.' ('.__LINE__.') '.' using Cached folderObjects'.array2string($folders2return[$this->icServer->ImapServerId]));
2558
-				if (self::$debugTimes) self::logRunTimes($starttime,null,'from Cache',__METHOD__.' ('.__LINE__.') ');
2983
+				if (self::$debugTimes)
2984
+				{
2985
+					self::logRunTimes($starttime,null,'from Cache',__METHOD__.' ('.__LINE__.') ');
2986
+				}
2559 2987
 				return $folders2return[$this->icServer->ImapServerId];
2560 2988
 			}
2561 2989
 		}
2562 2990
 		// use $folderBasicInfo for holding attributes and other basic folderinfo $folderBasicInfo[$this->icServer->ImapServerId]
2563 2991
 		static $folderBasicInfo;
2564
-		if (is_null($folderBasicInfo)||!isset($folderBasicInfo[$this->icServer->ImapServerId])) $folderBasicInfo = Cache::getCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2992
+		if (is_null($folderBasicInfo)||!isset($folderBasicInfo[$this->icServer->ImapServerId]))
2993
+		{
2994
+			$folderBasicInfo = Cache::getCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2995
+		}
2565 2996
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($folderBasicInfo[$this->icServer->ImapServerId])));
2566 2997
 
2567 2998
 		$delimiter = $this->getHierarchyDelimiter();
@@ -2574,7 +3005,8 @@  discard block
 block discarded – undo
2574 3005
 		$inboxData->shortFolderName	= 'INBOX';
2575 3006
 		$inboxData->shortDisplayName	= lang('INBOX');
2576 3007
 		$inboxData->subscribed = true;
2577
-		if($_getCounters == true) {
3008
+		if($_getCounters == true)
3009
+		{
2578 3010
 			$inboxData->counter = $this->getMailBoxCounters('INBOX');
2579 3011
 		}
2580 3012
 		// force unsubscribed by preference showAllFoldersInFolderPane
@@ -2593,12 +3025,14 @@  discard block
 block discarded – undo
2593 3025
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2594 3026
 		if (is_array($nameSpace))
2595 3027
 		{
2596
-			foreach($nameSpace as $k => $singleNameSpace) {
3028
+			foreach($nameSpace as $k => $singleNameSpace)
3029
+			{
2597 3030
 				$type = $singleNameSpace['type'];
2598 3031
 				// the following line (assumption that for the same namespace the delimiter should be equal) may be wrong
2599 3032
 				$foldersNameSpace[$type]['delimiter']  = $singleNameSpace['delimiter'];
2600 3033
 
2601
-				if(is_array($singleNameSpace)&&$fetchedAllInOneGo==false) {
3034
+				if(is_array($singleNameSpace)&&$fetchedAllInOneGo==false)
3035
+				{
2602 3036
 					// fetch and sort the subscribed folders
2603 3037
 					// we alway fetch the subscribed, as this provides the only way to tell
2604 3038
 					// if a folder is subscribed or not
@@ -2649,8 +3083,12 @@  discard block
 block discarded – undo
2649 3083
 							}
2650 3084
 						}
2651 3085
 						//error_log(__METHOD__.' ('.__LINE__.') '.' '.$type.'->'.array2string($foldersNameSpace[$type]['subscribed']));
2652
-						if (!is_array($foldersNameSpace[$type]['all'])) $foldersNameSpace[$type]['all'] = array();
2653
-						if ($_subscribedOnly == true && !empty($foldersNameSpace[$type]['subscribed'])) {
3086
+						if (!is_array($foldersNameSpace[$type]['all']))
3087
+						{
3088
+							$foldersNameSpace[$type]['all'] = array();
3089
+						}
3090
+						if ($_subscribedOnly == true && !empty($foldersNameSpace[$type]['subscribed']))
3091
+						{
2654 3092
 							continue;
2655 3093
 						}
2656 3094
 
@@ -2680,7 +3118,8 @@  discard block
 block discarded – undo
2680 3118
 					}
2681 3119
 
2682 3120
 					//error_log(__METHOD__.' ('.__LINE__.') '.' '.$type.'->'.array2string($allMailboxesExt));
2683
-					foreach ($allMailboxesExt as $mbx) {
3121
+					foreach ($allMailboxesExt as $mbx)
3122
+					{
2684 3123
 						if (!isset($folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2685 3124
 						{
2686 3125
 							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]=array(
@@ -2703,20 +3142,33 @@  discard block
 block discarded – undo
2703 3142
 						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']])||
2704 3143
 							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']])||
2705 3144
 							(substr($mbx['MAILBOX'],-1)==$foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'],0,-1)]))
2706
-						) continue;
3145
+						)
3146
+						{
3147
+							continue;
3148
+						}
2707 3149
 
2708 3150
 						//echo '#'.$mbx['MAILBOX'].':'.array2string($mbx)."#<br>";
2709 3151
 						$allMailBoxesExtSorted[$mbx['MAILBOX']] = $mbx;
2710 3152
 					}
2711
-					if (is_array($allMailBoxesExtSorted)) ksort($allMailBoxesExtSorted);
3153
+					if (is_array($allMailBoxesExtSorted))
3154
+					{
3155
+						ksort($allMailBoxesExtSorted);
3156
+					}
2712 3157
 					//_debug_array(array_keys($allMailBoxesExtSorted));
2713 3158
 					$allMailboxes = array();
2714
-					foreach ((array)$allMailBoxesExtSorted as $mbx) {
2715
-						if (!in_array($mbx['MAILBOX'],$allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
3159
+					foreach ((array)$allMailBoxesExtSorted as $mbx)
3160
+					{
3161
+						if (!in_array($mbx['MAILBOX'],$allMailboxes))
3162
+						{
3163
+							$allMailboxes[] = $mbx['MAILBOX'];
3164
+						}
2716 3165
 						//echo "Result:";_debug_array($allMailboxes);
2717 3166
 					}
2718 3167
 					$foldersNameSpace[$type]['all'] = $allMailboxes;
2719
-					if (is_array($foldersNameSpace[$type]['all'])) sort($foldersNameSpace[$type]['all']);
3168
+					if (is_array($foldersNameSpace[$type]['all']))
3169
+					{
3170
+						sort($foldersNameSpace[$type]['all']);
3171
+					}
2720 3172
 				}
2721 3173
 			}
2722 3174
 		}
@@ -2725,24 +3177,50 @@  discard block
 block discarded – undo
2725 3177
 		//echo "<br>FolderNameSpace To Process:";_debug_array($foldersNameSpace);
2726 3178
 		$autoFolderObjects = $folders = array();
2727 3179
 		$autofolder_exists = array();
2728
-		foreach( array('personal', 'others', 'shared') as $type) {
2729
-			if(isset($foldersNameSpace[$type])) {
2730
-				if($_subscribedOnly) {
2731
-					if( !empty($foldersNameSpace[$type]['subscribed']) ) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2732
-				} else {
2733
-					if( !empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2734
-				}
2735
-				foreach((array)$listOfFolders as $folderName) {
3180
+		foreach( array('personal', 'others', 'shared') as $type)
3181
+		{
3182
+			if(isset($foldersNameSpace[$type]))
3183
+			{
3184
+				if($_subscribedOnly)
3185
+				{
3186
+					if( !empty($foldersNameSpace[$type]['subscribed']) )
3187
+					{
3188
+						$listOfFolders = $foldersNameSpace[$type]['subscribed'];
3189
+					}
3190
+				}
3191
+				else
3192
+				{
3193
+					if( !empty($foldersNameSpace[$type]['all']))
3194
+					{
3195
+						$listOfFolders = $foldersNameSpace[$type]['all'];
3196
+					}
3197
+				}
3198
+				foreach((array)$listOfFolders as $folderName)
3199
+				{
2736 3200
 					//echo "<br>FolderToCheck:$folderName<br>";
2737 3201
 					//error_log(__METHOD__.__LINE__.'#Delimiter:'.$delimiter.':#'.$folderName);
2738
-					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue;//when subscribedonly, we fetch all folders in one go.
2739
-					if($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all'])||in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
3202
+					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all']))
3203
+					{
3204
+						continue;
3205
+					}
3206
+					//when subscribedonly, we fetch all folders in one go.
3207
+					if($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all'])||in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all'])))
3208
+					{
2740 3209
 						#echo "$folderName failed to be here <br>";
2741 3210
 						continue;
2742 3211
 					}
2743
-					if (isset($folders[$folderName])) continue;
2744
-					if (isset($autoFolderObjects[$folderName])) continue;
2745
-					if (empty($delimiter)||$delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
3212
+					if (isset($folders[$folderName]))
3213
+					{
3214
+						continue;
3215
+					}
3216
+					if (isset($autoFolderObjects[$folderName]))
3217
+					{
3218
+						continue;
3219
+					}
3220
+					if (empty($delimiter)||$delimiter != $foldersNameSpace[$type]['delimiter'])
3221
+					{
3222
+						$delimiter = $foldersNameSpace[$type]['delimiter'];
3223
+					}
2746 3224
 					$folderParts = explode($delimiter, $folderName);
2747 3225
 					$shortName = array_pop($folderParts);
2748 3226
 
@@ -2750,17 +3228,20 @@  discard block
 block discarded – undo
2750 3228
 					$folderObject->delimiter	= $delimiter;
2751 3229
 					$folderObject->folderName	= $folderName;
2752 3230
 					$folderObject->shortFolderName	= $shortName;
2753
-					if(!$_subscribedOnly) {
3231
+					if(!$_subscribedOnly)
3232
+					{
2754 3233
 						#echo $folderName."->".$type."<br>";
2755 3234
 						#_debug_array($foldersNameSpace[$type]['subscribed']);
2756 3235
 						$folderObject->subscribed = in_array($folderName, (array)$foldersNameSpace[$type]['subscribed']);
2757 3236
 					}
2758 3237
 
2759
-					if($_getCounters == true) {
3238
+					if($_getCounters == true)
3239
+					{
2760 3240
 						//error_log(__METHOD__.' ('.__LINE__.') '.' getCounter forFolder:'.$folderName);
2761 3241
 						$folderObject->counter = $this->getMailBoxCounters($folderName);
2762 3242
 					}
2763
-					if(strtoupper($folderName) == 'INBOX') {
3243
+					if(strtoupper($folderName) == 'INBOX')
3244
+					{
2764 3245
 						$folderName = 'INBOX';
2765 3246
 						$folderObject->folderName	= 'INBOX';
2766 3247
 						$folderObject->shortFolderName	= 'INBOX';
@@ -2768,24 +3249,34 @@  discard block
 block discarded – undo
2768 3249
 						$folderObject->shortDisplayName = lang('INBOX');
2769 3250
 						$folderObject->subscribed	= true;
2770 3251
 					// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
2771
-					} elseif (in_array($shortName,self::$autoFolders)) {
3252
+					}
3253
+					elseif (in_array($shortName,self::$autoFolders))
3254
+					{
2772 3255
 						$tmpfolderparts = explode($delimiter,$folderObject->folderName);
2773 3256
 						array_pop($tmpfolderparts);
2774 3257
 						$folderObject->displayName = implode($delimiter,$tmpfolderparts).$delimiter.lang($shortName);
2775 3258
 						$folderObject->shortDisplayName = lang($shortName);
2776 3259
 						unset($tmpfolderparts);
2777
-					} else {
3260
+					}
3261
+					else
3262
+					{
2778 3263
 						$folderObject->displayName = $folderObject->folderName;
2779 3264
 						$folderObject->shortDisplayName = $shortName;
2780 3265
 					}
2781 3266
 					//$folderName = $folderName;
2782
-					if (in_array($shortName,self::$autoFolders)&&self::searchValueInFolderObjects($shortName,$autoFolderObjects)===false) {
3267
+					if (in_array($shortName,self::$autoFolders)&&self::searchValueInFolderObjects($shortName,$autoFolderObjects)===false)
3268
+					{
2783 3269
 						$autoFolderObjects[$folderName] = $folderObject;
2784
-					} else {
3270
+					}
3271
+					else
3272
+					{
2785 3273
 						$folders[$folderName] = $folderObject;
2786 3274
 					}
2787 3275
 					//error_log(__METHOD__.' ('.__LINE__.') '.':'.$folderObject->folderName);
2788
-					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders ();
3276
+					if (!isset(self::$specialUseFolders))
3277
+					{
3278
+						$this->getSpecialUseFolders ();
3279
+					}
2789 3280
 					if (isset(self::$specialUseFolders[$folderName]))
2790 3281
 					{
2791 3282
 						$autofolder_exists[$folderName] = self::$specialUseFolders[$folderName];
@@ -2793,7 +3284,8 @@  discard block
 block discarded – undo
2793 3284
 				}
2794 3285
 			}
2795 3286
 		}
2796
-		if (is_array($autoFolderObjects) && !empty($autoFolderObjects)) {
3287
+		if (is_array($autoFolderObjects) && !empty($autoFolderObjects))
3288
+		{
2797 3289
 			uasort($autoFolderObjects,array($this,"sortByAutoFolderPos"));
2798 3290
 		}
2799 3291
 		// check if some standard folders are missing and need to be created
@@ -2802,7 +3294,10 @@  discard block
 block discarded – undo
2802 3294
 			// if new folders have been created, re-read folders ignoring the cache
2803 3295
 			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false);	// false = do NOT use cache
2804 3296
 		}
2805
-		if (is_array($folders)) uasort($folders,array($this,"sortByDisplayName"));
3297
+		if (is_array($folders))
3298
+		{
3299
+			uasort($folders,array($this,"sortByDisplayName"));
3300
+		}
2806 3301
 		//$folders2return = array_merge($autoFolderObjects,$folders);
2807 3302
 		//_debug_array($folders2return); #exit;
2808 3303
 		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject,(array)$autoFolderObjects,(array)$folders);
@@ -2814,7 +3309,10 @@  discard block
 block discarded – undo
2814 3309
 			Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),$folders2return,$expiration=60*60*1);
2815 3310
 		}
2816 3311
 		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderBasicInfo,$expiration=60*60*1);
2817
-		if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') ');
3312
+		if (self::$debugTimes)
3313
+		{
3314
+			self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') ');
3315
+		}
2818 3316
 		return $folders2return[$this->icServer->ImapServerId];
2819 3317
 	}
2820 3318
 
@@ -2842,31 +3340,44 @@  discard block
 block discarded – undo
2842 3340
 
2843 3341
 		$folders = $nameSpace =  array();
2844 3342
 		$nameSpaceTmp = $this->_getNameSpaces();
2845
-		foreach($nameSpaceTmp as $k => $singleNameSpace) {
3343
+		foreach($nameSpaceTmp as $k => $singleNameSpace)
3344
+		{
2846 3345
 			$nameSpace[$singleNameSpace['type']]=$singleNameSpace;
2847 3346
 		}
2848 3347
 		unset($nameSpaceTmp);
2849 3348
 
2850 3349
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2851 3350
 		// Get special use folders
2852
-		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders (); // Set self::$specialUseFolders
3351
+		if (!isset(self::$specialUseFolders))
3352
+		{
3353
+			$this->getSpecialUseFolders ();
3354
+		}
3355
+		// Set self::$specialUseFolders
2853 3356
 		// topLevelQueries generally ignore the $_search param. Except for Config::examineNamespace
2854
-		if ($_onlyTopLevel) // top level leaves
3357
+		if ($_onlyTopLevel)
3358
+		{
3359
+			// top level leaves
2855 3360
 		{
2856 3361
 			// Get top mailboxes of icServer
2857 3362
 			$topFolders = $this->icServer->getMailboxes("", 2, true);
3363
+		}
2858 3364
 			// Trigger examination of namespace to retrieve
2859 3365
 			// folders located in other and shared; needed only for some servers
2860
-			if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
3366
+			if (is_null(self::$mailConfig))
3367
+			{
3368
+				self::$mailConfig = Config::read('mail');
3369
+			}
2861 3370
 			if (self::$mailConfig['examineNamespace'])
2862 3371
 			{
2863 3372
 				$prefixes=array();
2864 3373
 				if (is_array($nameSpace))
2865 3374
 				{
2866
-					foreach($nameSpace as $k => $singleNameSpace) {
3375
+					foreach($nameSpace as $k => $singleNameSpace)
3376
+					{
2867 3377
 						$type = $singleNameSpace['type'];
2868 3378
 
2869
-						if(is_array($singleNameSpace) && $singleNameSpace['prefix']){
3379
+						if(is_array($singleNameSpace) && $singleNameSpace['prefix'])
3380
+						{
2870 3381
 							$prefixes[$type] = $singleNameSpace['prefix'];
2871 3382
 							//regard extra care for nameSpacequeries when configured AND respect $_search
2872 3383
 							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search==0?0:2, true);
@@ -2942,7 +3453,10 @@  discard block
 block discarded – undo
2942 3453
 							$nFolders [$path] = $folder;
2943 3454
 						}
2944 3455
 					}
2945
-					if (is_array($aFolders)) uasort ($aFolders, array($this,'sortByAutofolder'));
3456
+					if (is_array($aFolders))
3457
+					{
3458
+						uasort ($aFolders, array($this,'sortByAutofolder'));
3459
+					}
2946 3460
 					//ksort($aFolders);
2947 3461
 
2948 3462
 					// Sort none auto folders base on mailbox name
@@ -2952,12 +3466,17 @@  discard block
 block discarded – undo
2952 3466
 				}
2953 3467
 				else
2954 3468
 				{
2955
-					if (is_array($subFolders)) ksort($subFolders);
3469
+					if (is_array($subFolders))
3470
+					{
3471
+						ksort($subFolders);
3472
+					}
2956 3473
 				}
2957 3474
 				$folders = array_merge($folders,(array)$mainFolder, (array)$subFolders);
2958 3475
 			}
2959 3476
 		}
2960
-		elseif ($_nodePath) // single node
3477
+		elseif ($_nodePath)
3478
+		{
3479
+			// single node
2961 3480
 		{
2962 3481
 			switch ($_search)
2963 3482
 			{
@@ -2965,6 +3484,7 @@  discard block
 block discarded – undo
2965 3484
 				case 0:
2966 3485
 				case 2:
2967 3486
 					$path = $_nodePath.''.$delimiter;
3487
+		}
2968 3488
 					break;
2969 3489
 				// Node itself
2970 3490
 				// shouldn't contain next level delimiter
@@ -2983,11 +3503,14 @@  discard block
 block discarded – undo
2983 3503
 
2984 3504
 			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
2985 3505
 		}
2986
-		elseif(!$_nodePath) // all
3506
+		elseif(!$_nodePath)
3507
+		{
3508
+			// all
2987 3509
 		{
2988 3510
 			if ($_subscribedOnly)
2989 3511
 			{
2990 3512
 				$folders = $this->icServer->listSubscribedMailboxes('', 0, true);
3513
+		}
2991 3514
 			}
2992 3515
 			else
2993 3516
 			{
@@ -2999,7 +3522,10 @@  discard block
 block discarded – undo
2999 3522
 		{
3000 3523
 			// SORTING FOLDERS
3001 3524
 			//self::$debugTimes=true;
3002
-			if (self::$debugTimes) $starttime = microtime (true);
3525
+			if (self::$debugTimes)
3526
+			{
3527
+				$starttime = microtime (true);
3528
+			}
3003 3529
 			// Merge of all auto folders and specialusefolders
3004 3530
 			$autoFoldersTmp = array_unique((array_merge(self::$autoFolders, array_values(self::$specialUseFolders))));
3005 3531
 			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
@@ -3009,73 +3535,103 @@  discard block
 block discarded – undo
3009 3535
 			$isGoogleMail=false;
3010 3536
 			foreach($autoFoldersTmp as $afk=>$aF)
3011 3537
 			{
3012
-				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF]=$this->getFolderByType($aF,false);
3538
+				if (!isset($mySpecialUseFolders[$aF]) && $aF)
3539
+				{
3540
+					$mySpecialUseFolders[$aF]=$this->getFolderByType($aF,false);
3541
+				}
3013 3542
 				//error_log($afk.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3014 3543
 			}
3015 3544
 			//error_log(array2string($mySpecialUseFolders));
3016
-			foreach ($tmpFolders as $k => $f) {
3545
+			foreach ($tmpFolders as $k => $f)
3546
+			{
3017 3547
 				$sorted=false;
3018
-				if (strtoupper(substr($k,0,5))=='INBOX') {
3019
-					if (strtoupper($k)=='INBOX') {
3548
+				if (strtoupper(substr($k,0,5))=='INBOX')
3549
+				{
3550
+					if (strtoupper($k)=='INBOX')
3551
+					{
3020 3552
 						//error_log(__METHOD__.__LINE__.':'.strtoupper(substr($k,0,5)).':'.$k);
3021 3553
 						$inboxFolderObject[$k]=$f;
3022 3554
 						unset($folders[$k]);
3023 3555
 						$sorted=true;
3024
-					} else {
3556
+					}
3557
+					else
3558
+					{
3025 3559
 						$isAutoFolder=false;
3026 3560
 						foreach($autoFoldersTmp as $afk=>$aF)
3027 3561
 						{
3028 3562
 							//error_log(__METHOD__.__LINE__.$k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3029 3563
 							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3030 3564
 								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3031
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3565
+								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false))
3566
+							{
3567
+								// k is parent of an autofolder
3032 3568
 							{
3033 3569
 								//error_log(__METHOD__.__LINE__.$k.'->'.$mySpecialUseFolders[$aF]);
3034 3570
 								$isAutoFolder=true;
3571
+							}
3035 3572
 								$autoFolderObjects[$k]=$f;
3036 3573
 								break;
3037 3574
 							}
3038 3575
 						}
3039
-						if ($isAutoFolder==false) $inboxSubFolderObjects[$k]=$f;
3576
+						if ($isAutoFolder==false)
3577
+						{
3578
+							$inboxSubFolderObjects[$k]=$f;
3579
+						}
3040 3580
 						unset($folders[$k]);
3041 3581
 						$sorted=true;
3042 3582
 					}
3043
-				} elseif (strtoupper(substr($k,0,13))=='[GOOGLE MAIL]') {
3583
+				}
3584
+				elseif (strtoupper(substr($k,0,13))=='[GOOGLE MAIL]')
3585
+				{
3044 3586
 					$isGoogleMail=true;
3045
-					if (strtoupper($k)=='[GOOGLE MAIL]') {
3587
+					if (strtoupper($k)=='[GOOGLE MAIL]')
3588
+					{
3046 3589
 						$googleMailFolderObject[$k]=$f;
3047 3590
 						unset($folders[$k]);
3048 3591
 						$sorted=true;
3049
-					} else {
3592
+					}
3593
+					else
3594
+					{
3050 3595
 						$isAutoFolder=false;
3051 3596
 						foreach($autoFoldersTmp as $afk=>$aF)
3052 3597
 						{
3053 3598
 							//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3054 3599
 							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3055 3600
 								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3056
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3601
+								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false))
3602
+							{
3603
+								// k is parent of an autofolder
3057 3604
 							{
3058 3605
 								//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3059 3606
 								$isAutoFolder=true;
3607
+							}
3060 3608
 								$googleAutoFolderObjects[$k]=$f;
3061 3609
 								break;
3062 3610
 							}
3063 3611
 						}
3064
-						if ($isAutoFolder==false) $googleSubFolderObjects[$k]=$f;
3612
+						if ($isAutoFolder==false)
3613
+						{
3614
+							$googleSubFolderObjects[$k]=$f;
3615
+						}
3065 3616
 						unset($folders[$k]);
3066 3617
 						$sorted=true;
3067 3618
 					}
3068
-				} else {
3619
+				}
3620
+				else
3621
+				{
3069 3622
 					$isAutoFolder=false;
3070 3623
 					foreach($autoFoldersTmp as $afk=>$aF)
3071 3624
 					{
3072 3625
 						//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3073 3626
 						if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3074 3627
 								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3075
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3628
+								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false))
3629
+						{
3630
+							// k is parent of an autofolder
3076 3631
 						{
3077 3632
 							//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3078 3633
 							$isAutoFolder=true;
3634
+						}
3079 3635
 							$autoFolderObjects[$k]=$f;
3080 3636
 							unset($folders[$k]);
3081 3637
 							$sorted=true;
@@ -3091,7 +3647,8 @@  discard block
 block discarded – undo
3091 3647
 						if ($nameSpace[$type]['prefix_present']&&$nameSpace[$type]['prefix'])
3092 3648
 						{
3093 3649
 							if (substr($k,0,strlen($nameSpace[$type]['prefix']))==$nameSpace[$type]['prefix']||
3094
-								substr($k,0,strlen($nameSpace[$type]['prefix'])-strlen($nameSpace[$type]['delimiter']))==substr($nameSpace[$type]['prefix'],0,strlen($nameSpace[$type]['delimiter'])*-1)) {
3650
+								substr($k,0,strlen($nameSpace[$type]['prefix'])-strlen($nameSpace[$type]['delimiter']))==substr($nameSpace[$type]['prefix'],0,strlen($nameSpace[$type]['delimiter'])*-1))
3651
+							{
3095 3652
 								//error_log(__METHOD__.__LINE__.':'.substr($k,0,strlen($nameSpace[$type]['prefix'])).':'.$k);
3096 3653
 								$typeFolderObject[$type][$k]=$f;
3097 3654
 								unset($folders[$k]);
@@ -3118,9 +3675,12 @@  discard block
 block discarded – undo
3118 3675
 				}
3119 3676
 			}
3120 3677
 			//error_log(__METHOD__.__LINE__.array2string($autoFolderObjects));
3121
-			if (!$isGoogleMail) {
3678
+			if (!$isGoogleMail)
3679
+			{
3122 3680
 				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$inboxSubFolderObjects,(array)$folders,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3123
-			} else {
3681
+			}
3682
+			else
3683
+			{
3124 3684
 				// avoid calling sortByAutoFolder as it is not regarding subfolders
3125 3685
 				$gAutoFolderObjectsTmp = $googleAutoFolderObjects;
3126 3686
 				unset($googleAutoFolderObjects);
@@ -3137,7 +3697,10 @@  discard block
 block discarded – undo
3137 3697
 				}
3138 3698
 				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$folders,(array)$googleMailFolderObject,$googleAutoFolderObjects,$googleSubFolderObjects,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3139 3699
 			}
3140
-			if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') Sorting:');
3700
+			if (self::$debugTimes)
3701
+			{
3702
+				self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') Sorting:');
3703
+			}
3141 3704
 			//self::$debugTimes=false;
3142 3705
 		}
3143 3706
 		// Get counter information and add them to each fetched folders array
@@ -3187,7 +3750,13 @@  discard block
 block discarded – undo
3187 3750
 		$rv = false;
3188 3751
 		foreach ($haystack as $k => $v)
3189 3752
 		{
3190
-			foreach($v as &$sv) {if (trim($sv)==trim($needle)) return $k;}
3753
+			foreach($v as &$sv)
3754
+			{
3755
+if (trim($sv)==trim($needle))
3756
+			{
3757
+				return $k;
3758
+			}
3759
+			}
3191 3760
 		}
3192 3761
 		return $rv;
3193 3762
 	}
@@ -3214,7 +3783,10 @@  discard block
 block discarded – undo
3214 3783
 	 */
3215 3784
 	static function pathToFolderData ($_path, $_hDelimiter)
3216 3785
 	{
3217
-		if (!strpos($_path, self::DELIMITER)) $_path = self::DELIMITER.$_path;
3786
+		if (!strpos($_path, self::DELIMITER))
3787
+		{
3788
+			$_path = self::DELIMITER.$_path;
3789
+		}
3218 3790
 		list(,$path) = explode(self::DELIMITER, $_path);
3219 3791
 		$path_chain = $parts = explode($_hDelimiter, $path);
3220 3792
 		$name = array_pop($parts);
@@ -3243,7 +3815,10 @@  discard block
 block discarded – undo
3243 3815
 		$b = self::pathToFolderData($_b['MAILBOX'], $_b['delimiter']);
3244 3816
 		$pos1 = array_search(trim($a['name']),self::$autoFolders);
3245 3817
 		$pos2 = array_search(trim($b['name']),self::$autoFolders);
3246
-		if ($pos1 == $pos2) return 0;
3818
+		if ($pos1 == $pos2)
3819
+		{
3820
+			return 0;
3821
+		}
3247 3822
 		return ($pos1 < $pos2) ? -1 : 1;
3248 3823
 	}
3249 3824
 
@@ -3274,7 +3849,10 @@  discard block
 block discarded – undo
3274 3849
 		// 0, 1 und -1
3275 3850
 		$pos1 = array_search(trim($a->shortFolderName),self::$autoFolders);
3276 3851
 		$pos2 = array_search(trim($b->shortFolderName),self::$autoFolders);
3277
-		if ($pos1 == $pos2) return 0;
3852
+		if ($pos1 == $pos2)
3853
+		{
3854
+			return 0;
3855
+		}
3278 3856
 		return ($pos1 < $pos2) ? -1 : 1;
3279 3857
 	}
3280 3858
 
@@ -3295,11 +3873,18 @@  discard block
 block discarded – undo
3295 3873
 		}
3296 3874
 		catch (\Exception $e)
3297 3875
 		{
3298
-			if (self::$debug) error_log(__METHOD__." returned FolderStatus for Folder $folderName:".$e->getMessage());
3876
+			if (self::$debug)
3877
+			{
3878
+				error_log(__METHOD__." returned FolderStatus for Folder $folderName:".$e->getMessage());
3879
+			}
3299 3880
 			return false;
3300 3881
 		}
3301
-		if(is_array($folderStatus)) {
3302
-			if ($_returnObject===false) return $folderStatus;
3882
+		if(is_array($folderStatus))
3883
+		{
3884
+			if ($_returnObject===false)
3885
+			{
3886
+				return $folderStatus;
3887
+			}
3303 3888
 			$status =  new \stdClass;
3304 3889
 			$status->messages   = $folderStatus['MESSAGES'];
3305 3890
 			$status->unseen     = $folderStatus['UNSEEN'];
@@ -3326,7 +3911,8 @@  discard block
 block discarded – undo
3326 3911
 	{
3327 3912
 		#echo __METHOD__." retrieve SubFolders for $_mailbox$delimiter <br>";
3328 3913
 		$maxreclevel=25;
3329
-		if ($reclevel > $maxreclevel) {
3914
+		if ($reclevel > $maxreclevel)
3915
+		{
3330 3916
 			error_log( __METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3331 3917
 			return array();
3332 3918
 		}
@@ -3340,7 +3926,8 @@  discard block
 block discarded – undo
3340 3926
 //error_log(__METHOD__.' ('.__LINE__.') '.' Delimiter:'.array2string($delimiter));
3341 3927
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
3342 3928
 		// Example: Array([INBOX/GaGa] => Array([MAILBOX] => INBOX/GaGa[ATTRIBUTES] => Array([0] => \\unmarked)[delimiter] => /))
3343
-		if (is_array($mbx[$mbxkeys[0]]["ATTRIBUTES"]) && (in_array('\HasChildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Haschildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\haschildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]))) {
3929
+		if (is_array($mbx[$mbxkeys[0]]["ATTRIBUTES"]) && (in_array('\HasChildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Haschildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\haschildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"])))
3930
+		{
3344 3931
 			// if there are children fetch them
3345 3932
 			//echo $mbx[$mbxkeys[0]]['MAILBOX']."<br>";
3346 3933
 
@@ -3348,7 +3935,8 @@  discard block
 block discarded – undo
3348 3935
 			//$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'],2,false);
3349 3936
 			//_debug_array($buff);
3350 3937
 			$allMailboxes = array();
3351
-			foreach ($buff as $mbxname) {
3938
+			foreach ($buff as $mbxname)
3939
+			{
3352 3940
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbxname));
3353 3941
 				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$mbxname['MAILBOX']);
3354 3942
 				#echo "About to recur in level $reclevel:".$mbxname."<br>";
@@ -3357,9 +3945,14 @@  discard block
 block discarded – undo
3357 3945
 					$allMailboxes = array_merge($allMailboxes, self::getMailBoxesRecursive($mbxname, $delimiter, $prefix, $reclevel));
3358 3946
 				}
3359 3947
 			}
3360
-			if (!(in_array('\NoSelect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Noselect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\noselect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]))) $allMailboxes[] = $mbx[$mbxkeys[0]]['MAILBOX'];
3948
+			if (!(in_array('\NoSelect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Noselect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\noselect',$mbx[$mbxkeys[0]]["ATTRIBUTES"])))
3949
+			{
3950
+				$allMailboxes[] = $mbx[$mbxkeys[0]]['MAILBOX'];
3951
+			}
3361 3952
 			return $allMailboxes;
3362
-		} else {
3953
+		}
3954
+		else
3955
+		{
3363 3956
 			return array($_mailbox);
3364 3957
 		}
3365 3958
 	}
@@ -3383,14 +3976,21 @@  discard block
 block discarded – undo
3383 3976
 			'Outbox'   => array('profileKey'=>'acc_folder_outbox','autoFolderName'=>'Outbox'),
3384 3977
 			'Archive'   => array('profileKey'=>'acc_folder_archive','autoFolderName'=>'Archive'),
3385 3978
 		);
3386
-		if ($_type == 'Templates') $_type = 'Template';	// for some reason self::$autofolders uses 'Templates'!
3979
+		if ($_type == 'Templates')
3980
+		{
3981
+			$_type = 'Template';
3982
+		}
3983
+		// for some reason self::$autofolders uses 'Templates'!
3387 3984
 		$created = false;
3388 3985
 		if (!isset($types[$_type]))
3389 3986
 		{
3390 3987
 			error_log(__METHOD__.' ('.__LINE__.') '.' '.$_type.' not supported for '.__METHOD__);
3391 3988
 			return false;
3392 3989
 		}
3393
-		if (is_null(self::$specialUseFolders) || empty(self::$specialUseFolders)) self::$specialUseFolders = $this->getSpecialUseFolders();
3990
+		if (is_null(self::$specialUseFolders) || empty(self::$specialUseFolders))
3991
+		{
3992
+			self::$specialUseFolders = $this->getSpecialUseFolders();
3993
+		}
3394 3994
 
3395 3995
 		//highest precedence
3396 3996
 		try
@@ -3400,25 +4000,39 @@  discard block
 block discarded – undo
3400 4000
 		catch (\Exception $e)
3401 4001
 		{
3402 4002
 			// we know that outbox is not supported, but we use this here, as we autocreate expected SpecialUseFolders in this function
3403
-			if ($_type != 'Outbox') error_log(__METHOD__.' ('.__LINE__.') '.' Failed to retrieve Folder'.$_folderName." for ".array2string($types[$_type]).":".$e->getMessage());
4003
+			if ($_type != 'Outbox')
4004
+			{
4005
+				error_log(__METHOD__.' ('.__LINE__.') '.' Failed to retrieve Folder'.$_folderName." for ".array2string($types[$_type]).":".$e->getMessage());
4006
+			}
3404 4007
 			$_folderName = false;
3405 4008
 		}
3406 4009
 		// do not try to autocreate configured Archive-Folder. Return false if configured folder does not exist
3407
-		if ($_type == 'Archive') {
3408
-			if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
4010
+		if ($_type == 'Archive')
4011
+		{
4012
+			if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true))
4013
+			{
3409 4014
 				return false;
3410
-			} else {
4015
+			}
4016
+			else
4017
+			{
3411 4018
 				return $_folderName;
3412 4019
 			}
3413 4020
 
3414 4021
 		}
3415 4022
 		// does the folder exist??? (is configured/preset, but non-existent)
3416
-		if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
4023
+		if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true))
4024
+		{
3417 4025
 			try
3418 4026
 			{
3419 4027
 				$error = null;
3420
-				if (($_folderName = $this->createFolder('', $_folderName, $error))) $created = true;
3421
-				if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
4028
+				if (($_folderName = $this->createFolder('', $_folderName, $error)))
4029
+				{
4030
+					$created = true;
4031
+				}
4032
+				if ($error)
4033
+				{
4034
+					error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
4035
+				}
3422 4036
 			}
3423 4037
 			catch(Exception $e)
3424 4038
 			{
@@ -3427,9 +4041,16 @@  discard block
 block discarded – undo
3427 4041
 			}
3428 4042
 		}
3429 4043
 		// not sure yet if false is the correct behavior on none
3430
-		if ($_folderName =='none') return 'none' ; //false;
4044
+		if ($_folderName =='none')
4045
+		{
4046
+			return 'none' ;
4047
+		}
4048
+		//false;
3431 4049
 		//no (valid) folder found yet; try specialUseFolders
3432
-		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type,self::$specialUseFolders))) $_folderName = $f;
4050
+		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type,self::$specialUseFolders)))
4051
+		{
4052
+			$_folderName = $f;
4053
+		}
3433 4054
 		//no specialUseFolder; try some Defaults
3434 4055
 		if (empty($_folderName) && isset($types[$_type]))
3435 4056
 		{
@@ -3455,7 +4076,10 @@  discard block
 block discarded – undo
3455 4076
 					$error = null;
3456 4077
 					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'],$error);
3457 4078
 					$_folderName = $prefix.$types[$_type]['autoFolderName'];
3458
-					if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
4079
+					if ($error)
4080
+					{
4081
+						error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
4082
+					}
3459 4083
 				}
3460 4084
 				catch(Exception $e)
3461 4085
 				{
@@ -3558,25 +4182,35 @@  discard block
 block discarded – undo
3558 4182
 	function isSentFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3559 4183
 	{
3560 4184
 		$sentFolder = $this->getSentFolder($_checkexistance);
3561
-		if(empty($sentFolder)) {
4185
+		if(empty($sentFolder))
4186
+		{
3562 4187
 			return false;
3563 4188
 		}
3564 4189
 		// does the folder exist???
3565
-		if ($_checkexistance && !$this->folderExists($_folderName)) {
4190
+		if ($_checkexistance && !$this->folderExists($_folderName))
4191
+		{
3566 4192
 			return false;
3567 4193
 		}
3568 4194
 
3569 4195
 		if ($_exactMatch)
3570 4196
 		{
3571
-			if(false !== stripos($_folderName, $sentFolder)&& strlen($_folderName)==strlen($sentFolder)) {
4197
+			if(false !== stripos($_folderName, $sentFolder)&& strlen($_folderName)==strlen($sentFolder))
4198
+			{
3572 4199
 				return true;
3573
-			} else {
4200
+			}
4201
+			else
4202
+			{
3574 4203
 				return false;
3575 4204
 			}
3576
-		} else {
3577
-			if(false !== stripos($_folderName, $sentFolder)) {
4205
+		}
4206
+		else
4207
+		{
4208
+			if(false !== stripos($_folderName, $sentFolder))
4209
+			{
3578 4210
 				return true;
3579
-			} else {
4211
+			}
4212
+			else
4213
+			{
3580 4214
 				return false;
3581 4215
 			}
3582 4216
 		}
@@ -3591,23 +4225,33 @@  discard block
 block discarded – undo
3591 4225
 	 */
3592 4226
 	function isOutbox($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3593 4227
 	{
3594
-		if (stripos($_folderName, 'Outbox')===false) {
4228
+		if (stripos($_folderName, 'Outbox')===false)
4229
+		{
3595 4230
 			return false;
3596 4231
 		}
3597 4232
 		// does the folder exist???
3598
-		if ($_checkexistance && $GLOBALS['egw_info']['user']['apps']['activesync'] && !$this->folderExists($_folderName)) {
4233
+		if ($_checkexistance && $GLOBALS['egw_info']['user']['apps']['activesync'] && !$this->folderExists($_folderName))
4234
+		{
3599 4235
 			$outboxFolder = $this->getOutboxFolder($_checkexistance);
3600 4236
 			if ($_exactMatch)
3601 4237
 			{
3602
-				if(false !== stripos($_folderName, $outboxFolder)&& strlen($_folderName)==strlen($outboxFolder)) {
4238
+				if(false !== stripos($_folderName, $outboxFolder)&& strlen($_folderName)==strlen($outboxFolder))
4239
+				{
3603 4240
 					return true;
3604
-				} else {
4241
+				}
4242
+				else
4243
+				{
3605 4244
 					return false;
3606 4245
 				}
3607
-			} else {
3608
-				if(false !== stripos($_folderName, $outboxFolder)) {
4246
+			}
4247
+			else
4248
+			{
4249
+				if(false !== stripos($_folderName, $outboxFolder))
4250
+				{
3609 4251
 					return true;
3610
-				} else {
4252
+				}
4253
+				else
4254
+				{
3611 4255
 					return false;
3612 4256
 				}
3613 4257
 			}
@@ -3625,25 +4269,38 @@  discard block
 block discarded – undo
3625 4269
 	function isDraftFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3626 4270
 	{
3627 4271
 		$draftFolder = $this->getDraftFolder($_checkexistance);
3628
-		if(empty($draftFolder)) {
4272
+		if(empty($draftFolder))
4273
+		{
3629 4274
 			return false;
3630 4275
 		}
3631 4276
 		// does the folder exist???
3632
-		if ($_checkexistance && !$this->folderExists($_folderName)) {
4277
+		if ($_checkexistance && !$this->folderExists($_folderName))
4278
+		{
3633 4279
 			return false;
3634 4280
 		}
3635
-		if (is_a($_folderName,"Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
4281
+		if (is_a($_folderName,"Horde_Imap_Client_Mailbox"))
4282
+		{
4283
+			$_folderName = $_folderName->utf8;
4284
+		}
3636 4285
 		if ($_exactMatch)
3637 4286
 		{
3638
-			if(false !== stripos($_folderName, $draftFolder)&& strlen($_folderName)==strlen($draftFolder)) {
4287
+			if(false !== stripos($_folderName, $draftFolder)&& strlen($_folderName)==strlen($draftFolder))
4288
+			{
4289
+				return true;
4290
+			}
4291
+			else
4292
+			{
4293
+				return false;
4294
+			}
4295
+		}
4296
+		else
4297
+		{
4298
+			if(false !== stripos($_folderName, $draftFolder))
4299
+			{
3639 4300
 				return true;
3640
-			} else {
3641
-				return false;
3642 4301
 			}
3643
-		} else {
3644
-			if(false !== stripos($_folderName, $draftFolder)) {
3645
-				return true;
3646
-			} else {
4302
+			else
4303
+			{
3647 4304
 				return false;
3648 4305
 			}
3649 4306
 		}
@@ -3659,25 +4316,35 @@  discard block
 block discarded – undo
3659 4316
 	function isTrashFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3660 4317
 	{
3661 4318
 		$trashFolder = $this->getTrashFolder($_checkexistance);
3662
-		if(empty($trashFolder)) {
4319
+		if(empty($trashFolder))
4320
+		{
3663 4321
 			return false;
3664 4322
 		}
3665 4323
 		// does the folder exist???
3666
-		if ($_checkexistance && !$this->folderExists($_folderName)) {
4324
+		if ($_checkexistance && !$this->folderExists($_folderName))
4325
+		{
3667 4326
 			return false;
3668 4327
 		}
3669 4328
 
3670 4329
 		if ($_exactMatch)
3671 4330
 		{
3672
-			if(false !== stripos($_folderName, $trashFolder)&& strlen($_folderName)==strlen($trashFolder)) {
4331
+			if(false !== stripos($_folderName, $trashFolder)&& strlen($_folderName)==strlen($trashFolder))
4332
+			{
3673 4333
 				return true;
3674
-			} else {
4334
+			}
4335
+			else
4336
+			{
3675 4337
 				return false;
3676 4338
 			}
3677
-		} else {
3678
-			if(false !== stripos($_folderName, $trashFolder)) {
4339
+		}
4340
+		else
4341
+		{
4342
+			if(false !== stripos($_folderName, $trashFolder))
4343
+			{
3679 4344
 				return true;
3680
-			} else {
4345
+			}
4346
+			else
4347
+			{
3681 4348
 				return false;
3682 4349
 			}
3683 4350
 		}
@@ -3693,24 +4360,34 @@  discard block
 block discarded – undo
3693 4360
 	function isTemplateFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3694 4361
 	{
3695 4362
 		$templateFolder = $this->getTemplateFolder($_checkexistance);
3696
-		if(empty($templateFolder)) {
4363
+		if(empty($templateFolder))
4364
+		{
3697 4365
 			return false;
3698 4366
 		}
3699 4367
 		// does the folder exist???
3700
-		if ($_checkexistance && !$this->folderExists($_folderName)) {
4368
+		if ($_checkexistance && !$this->folderExists($_folderName))
4369
+		{
3701 4370
 			return false;
3702 4371
 		}
3703 4372
 		if ($_exactMatch)
3704 4373
 		{
3705
-			if(false !== stripos($_folderName, $templateFolder)&& strlen($_folderName)==strlen($templateFolder)) {
4374
+			if(false !== stripos($_folderName, $templateFolder)&& strlen($_folderName)==strlen($templateFolder))
4375
+			{
3706 4376
 				return true;
3707
-			} else {
4377
+			}
4378
+			else
4379
+			{
3708 4380
 				return false;
3709 4381
 			}
3710
-		} else {
3711
-			if(false !== stripos($_folderName, $templateFolder)) {
4382
+		}
4383
+		else
4384
+		{
4385
+			if(false !== stripos($_folderName, $templateFolder))
4386
+			{
3712 4387
 				return true;
3713
-			} else {
4388
+			}
4389
+			else
4390
+			{
3714 4391
 				return false;
3715 4392
 			}
3716 4393
 		}
@@ -3729,15 +4406,27 @@  discard block
 block discarded – undo
3729 4406
 		if (empty($_folder))
3730 4407
 		{
3731 4408
 			// this error is more or less without significance, unless we force the check
3732
-			if ($_forceCheck===true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
4409
+			if ($_forceCheck===true)
4410
+			{
4411
+				error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
4412
+			}
3733 4413
 			return false;
3734 4414
 		}
3735 4415
 		// when check is not enforced , we assume a folder represented as Horde_Imap_Client_Mailbox as existing folder
3736
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")&&$_forceCheck===false) return true;
3737
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")) $_folder =  $_folder->utf8;
4416
+		if (is_a($_folder,"Horde_Imap_Client_Mailbox")&&$_forceCheck===false)
4417
+		{
4418
+			return true;
4419
+		}
4420
+		if (is_a($_folder,"Horde_Imap_Client_Mailbox"))
4421
+		{
4422
+			$_folder =  $_folder->utf8;
4423
+		}
3738 4424
 		// reduce traffic within the Instance per User; Expire every 5 hours
3739 4425
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Called with Folder:'.$_folder.function_backtrace());
3740
-		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),$expiration=60*60*5);
4426
+		if (is_null($folderInfo))
4427
+		{
4428
+			$folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),$expiration=60*60*5);
4429
+		}
3741 4430
 		//error_log(__METHOD__.' ('.__LINE__.') '.'Cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID.($forceCheck?'(forcedCheck)':'').':'.array2string($folderInfo));
3742 4431
 		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck===false)
3743 4432
 		{
@@ -3755,7 +4444,8 @@  discard block
 block discarded – undo
3755 4444
 
3756 4445
 		// does the folder exist???
3757 4446
 		//error_log(__METHOD__."->Connected?".$this->icServer->_connected.", ".$_folder.", ".($forceCheck?' forceCheck activated':'dont check on server'));
3758
-		if ( $forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
4447
+		if ( $forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder]))
4448
+		{
3759 4449
 			//error_log(__METHOD__."->NotConnected and forceCheck with profile:".$this->profileID);
3760 4450
 			//return false;
3761 4451
 			//try to connect
@@ -3796,9 +4486,12 @@  discard block
 block discarded – undo
3796 4486
 
3797 4487
 		$this->icServer->openMailbox($folderName);
3798 4488
 
3799
-		if(strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
4489
+		if(strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash")
4490
+		{
3800 4491
 			$this->deleteMessages('all',$folderName,'remove_immediately');
3801
-		} else {
4492
+		}
4493
+		else
4494
+		{
3802 4495
 			$this->icServer->expunge($folderName);
3803 4496
 		}
3804 4497
 	}
@@ -3817,10 +4510,16 @@  discard block
 block discarded – undo
3817 4510
 	{
3818 4511
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.array2string($_folder).', '.$_forceDeleteMethod);
3819 4512
 		$oldMailbox = '';
3820
-		if (is_null($_folder) || empty($_folder)) $_folder = $this->sessionData['mailbox'];
4513
+		if (is_null($_folder) || empty($_folder))
4514
+		{
4515
+			$_folder = $this->sessionData['mailbox'];
4516
+		}
3821 4517
 		if (empty($_messageUID))
3822 4518
 		{
3823
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
4519
+			if (self::$debug)
4520
+			{
4521
+				error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
4522
+			}
3824 4523
 			return false;
3825 4524
 		}
3826 4525
 		elseif ($_messageUID==='all')
@@ -3830,32 +4529,48 @@  discard block
 block discarded – undo
3830 4529
 		else
3831 4530
 		{
3832 4531
 			$uidsToDelete = new Horde_Imap_Client_Ids();
3833
-			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4532
+			if (!(is_object($_messageUID) || is_array($_messageUID)))
4533
+			{
4534
+				$_messageUID = (array)$_messageUID;
4535
+			}
3834 4536
 			$uidsToDelete->add($_messageUID);
3835 4537
 		}
3836 4538
 		$deleteOptions = $_forceDeleteMethod; // use forceDeleteMethod if not "no", or unknown method
3837
-		if ($_forceDeleteMethod === 'no' || !in_array($_forceDeleteMethod,array('move_to_trash',"mark_as_deleted","remove_immediately"))) $deleteOptions  = ($this->mailPreferences['deleteOptions']?$this->mailPreferences['deleteOptions']:"mark_as_deleted");
4539
+		if ($_forceDeleteMethod === 'no' || !in_array($_forceDeleteMethod,array('move_to_trash',"mark_as_deleted","remove_immediately")))
4540
+		{
4541
+			$deleteOptions  = ($this->mailPreferences['deleteOptions']?$this->mailPreferences['deleteOptions']:"mark_as_deleted");
4542
+		}
3838 4543
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3839 4544
 		$trashFolder    = $this->getTrashFolder();
3840 4545
 		$draftFolder	= $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3841 4546
 		$templateFolder = $this->getTemplateFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['templateFolder'];
3842 4547
 		if((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") ||
3843
-		   (strtolower($_folder) == strtolower($draftFolder))) {
4548
+		   (strtolower($_folder) == strtolower($draftFolder)))
4549
+		{
3844 4550
 			$deleteOptions = "remove_immediately";
3845 4551
 		}
3846
-		if($this->icServer->getCurrentMailbox() != $_folder) {
4552
+		if($this->icServer->getCurrentMailbox() != $_folder)
4553
+		{
3847 4554
 			$oldMailbox = $this->icServer->getCurrentMailbox();
3848 4555
 			$this->icServer->openMailbox($_folder);
3849 4556
 		}
3850 4557
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3851 4558
 		$updateCache = false;
3852
-		switch($deleteOptions) {
4559
+		switch($deleteOptions)
4560
+		{
3853 4561
 			case "move_to_trash":
3854 4562
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3855 4563
 				$updateCache = true;
3856
-				if(!empty($trashFolder)) {
3857
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.implode(' : ', $_messageUID));
3858
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ". $this->sessionData['mailbox']);
4564
+				if(!empty($trashFolder))
4565
+				{
4566
+					if (self::$debug)
4567
+					{
4568
+						error_log(__METHOD__.' ('.__LINE__.') '.implode(' : ', $_messageUID));
4569
+					}
4570
+					if (self::$debug)
4571
+					{
4572
+						error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ". $this->sessionData['mailbox']);
4573
+					}
3859 4574
 					// copy messages
3860 4575
 					try
3861 4576
 					{
@@ -3871,7 +4586,10 @@  discard block
 block discarded – undo
3871 4586
 			case "mark_as_deleted":
3872 4587
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3873 4588
 				// mark messages as deleted
3874
-				if (is_null($_messageUID)) $_messageUID='all';
4589
+				if (is_null($_messageUID))
4590
+				{
4591
+					$_messageUID='all';
4592
+				}
3875 4593
 				foreach((array)$_messageUID as $key =>$uid)
3876 4594
 				{
3877 4595
 					//flag messages, that are flagged for deletion as seen too
@@ -3879,7 +4597,10 @@  discard block
 block discarded – undo
3879 4597
 					$flags = $this->getFlags($uid);
3880 4598
 					$this->flagMessages('delete', $uid, $_folder);
3881 4599
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
3882
-					if (strpos( array2string($flags),'Deleted')!==false) $undelete[] = $uid;
4600
+					if (strpos( array2string($flags),'Deleted')!==false)
4601
+					{
4602
+						$undelete[] = $uid;
4603
+					}
3883 4604
 					unset($flags);
3884 4605
 				}
3885 4606
 				foreach((array)$undelete as $key =>$uid)
@@ -3891,7 +4612,10 @@  discard block
 block discarded – undo
3891 4612
 			case "remove_immediately":
3892 4613
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3893 4614
 				$updateCache = true;
3894
-				if (is_null($_messageUID)) $_messageUID='all';
4615
+				if (is_null($_messageUID))
4616
+				{
4617
+					$_messageUID='all';
4618
+				}
3895 4619
 				if (is_object($_messageUID))
3896 4620
 				{
3897 4621
 					$this->flagMessages('delete', $_messageUID, $_folder);
@@ -3908,7 +4632,8 @@  discard block
 block discarded – undo
3908 4632
 				$this->icServer->expunge($_folder);
3909 4633
 				break;
3910 4634
 		}
3911
-		if($oldMailbox != '') {
4635
+		if($oldMailbox != '')
4636
+		{
3912 4637
 			$this->icServer->openMailbox($oldMailbox);
3913 4638
 		}
3914 4639
 
@@ -3922,11 +4647,15 @@  discard block
 block discarded – undo
3922 4647
 	 *
3923 4648
 	 * @return null/array flags
3924 4649
 	 */
3925
-	function getFlags ($_messageUID) {
4650
+	function getFlags ($_messageUID)
4651
+	{
3926 4652
 		try
3927 4653
 		{
3928 4654
 			$uidsToFetch = new Horde_Imap_Client_Ids();
3929
-			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4655
+			if (!(is_object($_messageUID) || is_array($_messageUID)))
4656
+			{
4657
+				$_messageUID = (array)$_messageUID;
4658
+			}
3930 4659
 			$uidsToFetch->add($_messageUID);
3931 4660
 			$_folderName = $this->icServer->getCurrentMailbox();
3932 4661
 			$fquery = new Horde_Imap_Client_Fetch_Query();
@@ -3934,8 +4663,10 @@  discard block
 block discarded – undo
3934 4663
 			$headersNew = $this->icServer->fetch($_folderName, $fquery, array(
3935 4664
 				'ids' => $uidsToFetch,
3936 4665
 			));
3937
-			if (is_object($headersNew)) {
3938
-				foreach($headersNew->ids() as $id) {
4666
+			if (is_object($headersNew))
4667
+			{
4668
+				foreach($headersNew->ids() as $id)
4669
+				{
3939 4670
 					$_headerObject = $headersNew->get($id);
3940 4671
 					$flags = $_headerObject->getFlags();
3941 4672
 				}
@@ -3960,10 +4691,16 @@  discard block
 block discarded – undo
3960 4691
 	 */
3961 4692
 	function getNotifyFlags ($_messageUID, $flags=null)
3962 4693
 	{
3963
-		if (self::$debug) error_log(__METHOD__.$_messageUID.' Flags:'.array2string($flags));
4694
+		if (self::$debug)
4695
+		{
4696
+			error_log(__METHOD__.$_messageUID.' Flags:'.array2string($flags));
4697
+		}
3964 4698
 		try
3965 4699
 		{
3966
-			if($flags===null) $flags =  $this->getFlags($_messageUID);
4700
+			if($flags===null)
4701
+			{
4702
+				$flags =  $this->getFlags($_messageUID);
4703
+			}
3967 4704
 		}
3968 4705
 		catch (\Exception $e)
3969 4706
 		{
@@ -3971,10 +4708,14 @@  discard block
 block discarded – undo
3971 4708
 		}
3972 4709
 
3973 4710
 		if ( stripos( array2string($flags),'MDNSent')!==false)
3974
-			return true;
4711
+		{
4712
+					return true;
4713
+		}
3975 4714
 
3976 4715
 		if ( stripos( array2string($flags),'MDNnotSent')!==false)
3977
-			return false;
4716
+		{
4717
+					return false;
4718
+		}
3978 4719
 
3979 4720
 		return null;
3980 4721
 	}
@@ -3995,7 +4736,10 @@  discard block
 block discarded – undo
3995 4736
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",$_folder /".$this->sessionData['mailbox']);
3996 4737
 		if (empty($_messageUID))
3997 4738
 		{
3998
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
4739
+			if (self::$debug)
4740
+			{
4741
+				error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
4742
+			}
3999 4743
 			return false;
4000 4744
 		}
4001 4745
 		$this->icServer->openMailbox(($_folder?$_folder:$this->sessionData['mailbox']));
@@ -4003,7 +4747,10 @@  discard block
 block discarded – undo
4003 4747
 		if (is_array($_messageUID)&& count($_messageUID)>50)
4004 4748
 		{
4005 4749
 			$count = $this->getMailBoxCounters($folder,true);
4006
-			if ($count->messages == count($_messageUID)) $_messageUID='all';
4750
+			if ($count->messages == count($_messageUID))
4751
+			{
4752
+				$_messageUID='all';
4753
+			}
4007 4754
 		}
4008 4755
 
4009 4756
 		if ($_messageUID==='all')
@@ -4012,7 +4759,10 @@  discard block
 block discarded – undo
4012 4759
 		}
4013 4760
 		else
4014 4761
 		{
4015
-			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4762
+			if (!(is_object($_messageUID) || is_array($_messageUID)))
4763
+			{
4764
+				$_messageUID = (array)$_messageUID;
4765
+			}
4016 4766
 			$messageUIDs = array_chunk($_messageUID,50,true);
4017 4767
 		}
4018 4768
 		try
@@ -4028,7 +4778,8 @@  discard block
 block discarded – undo
4028 4778
 					$uidsToModify = new Horde_Imap_Client_Ids();
4029 4779
 					$uidsToModify->add($uids);
4030 4780
 				}
4031
-				switch($_flag) {
4781
+				switch($_flag)
4782
+				{
4032 4783
 					case "delete":
4033 4784
 						$ret = $this->icServer->store($folder, array('add'=>array('\\Deleted'), 'ids'=> $uidsToModify));
4034 4785
 						break;
@@ -4114,7 +4865,10 @@  discard block
 block discarded – undo
4114 4865
 		{
4115 4866
 			error_log(__METHOD__.__LINE__.' Error, could not flag messages in folder '.$folder.' Reason:'.$e->getMessage());
4116 4867
 		}
4117
-		if ($folder instanceof Horde_Imap_Client_Mailbox) $_folder = $folder->utf8;
4868
+		if ($folder instanceof Horde_Imap_Client_Mailbox)
4869
+		{
4870
+			$_folder = $folder->utf8;
4871
+		}
4118 4872
 		//error_log(__METHOD__.__LINE__.'#'.$this->icServer->ImapServerId.'#'.array2string($_folder).'#');
4119 4873
 		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder)?$_folder: $this->sessionData['mailbox'])]['uidValidity'] = 0;
4120 4874
 
@@ -4143,7 +4897,10 @@  discard block
 block discarded – undo
4143 4897
 		//$deleteOptions  = $GLOBALS['egw_info']["user"]["preferences"]["mail"]["deleteOptions"];
4144 4898
 		if (empty($_messageUID))
4145 4899
 		{
4146
-			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',',$_messageUID));
4900
+			if (self::$debug)
4901
+			{
4902
+				error_log(__METHOD__." no Message(s): ".implode(',',$_messageUID));
4903
+			}
4147 4904
 			return false;
4148 4905
 		}
4149 4906
 		elseif ($_messageUID==='all')
@@ -4155,7 +4912,10 @@  discard block
 block discarded – undo
4155 4912
 		{
4156 4913
 			//error_log(__METHOD__." Message(s): ".implode(',',$_messageUID));
4157 4914
 			$uidsToMove = new Horde_Imap_Client_Ids();
4158
-			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4915
+			if (!(is_object($_messageUID) || is_array($_messageUID)))
4916
+			{
4917
+				$_messageUID = (array)$_messageUID;
4918
+			}
4159 4919
 			$uidsToMove->add($_messageUID);
4160 4920
 		}
4161 4921
 		$sourceFolder = (!empty($currentFolder)?$currentFolder: $this->sessionData['mailbox']);
@@ -4177,12 +4937,14 @@  discard block
 block discarded – undo
4177 4937
 
4178 4938
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' mailheaders:'.array2string($headersNew));
4179 4939
 
4180
-			if (is_object($headersNew)) {
4940
+			if (is_object($headersNew))
4941
+			{
4181 4942
 				$c=0;
4182 4943
 				$retUid = new Horde_Imap_Client_Ids();
4183 4944
 				// we copy chunks of 5 to avoid too much memory and/or server stress
4184 4945
 				// some servers seem not to allow/support the appendig of multiple messages. so we are down to one
4185
-				foreach($headersNew as &$_headerObject) {
4946
+				foreach($headersNew as &$_headerObject)
4947
+				{
4186 4948
 					$c++;
4187 4949
 					$flags = $_headerObject->getFlags(); //unseen status seems to be lost when retrieving the full message
4188 4950
 					$date = $_headerObject->getImapDate();
@@ -4266,7 +5028,11 @@  discard block
 block discarded – undo
4266 5028
 	{
4267 5029
 		try {
4268 5030
 			$date = new DateTime($_date);	// parse date & time including timezone (throws exception, if not parsable)
4269
-			if ($convert2usertime) $date->setUser();	// convert to user-time
5031
+			if ($convert2usertime)
5032
+			{
5033
+				$date->setUser();
5034
+			}
5035
+			// convert to user-time
4270 5036
 			$date2return = $date->format($format);
4271 5037
 		}
4272 5038
 		catch(\Exception $e)
@@ -4298,9 +5064,15 @@  discard block
 block discarded – undo
4298 5064
 	static function htmlentities($_string, $_charset=false)
4299 5065
 	{
4300 5066
 		//setting the charset (if not given)
4301
-		if ($_charset===false) $_charset = self::$displayCharset;
5067
+		if ($_charset===false)
5068
+		{
5069
+			$_charset = self::$displayCharset;
5070
+		}
4302 5071
 		$string = @htmlentities($_string, ENT_QUOTES, $_charset, false);
4303
-		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string,Translation::detect_encoding($_string),$_charset),ENT_QUOTES | ENT_IGNORE,$_charset, false);
5072
+		if (empty($string) && !empty($_string))
5073
+		{
5074
+			$string = @htmlentities(Translation::convert($_string,Translation::detect_encoding($_string),$_charset),ENT_QUOTES | ENT_IGNORE,$_charset, false);
5075
+		}
4304 5076
 		return $string;
4305 5077
 	}
4306 5078
 
@@ -4320,18 +5092,41 @@  discard block
 block discarded – undo
4320 5092
 		$_html = str_replace(array('&amp;amp;','<DIV><BR></DIV>',"<DIV>&nbsp;</DIV>",'<div>&nbsp;</div>','</td></font>','<br><td>','<tr></tr>','<o:p></o:p>','<o:p>','</o:p>'),
4321 5093
 							 array('&amp;',    '<BR>',           '<BR>',             '<BR>',             '</font></td>','<td>',    '',         '',           '',  ''),$_html);
4322 5094
 		//$_html = str_replace(array('&amp;amp;'),array('&amp;'),$_html);
4323
-		if (stripos($_html,'style')!==false) Mail\Html::replaceTagsCompletley($_html,'style'); // clean out empty or pagewide style definitions / left over tags
4324
-		if (stripos($_html,'head')!==false) Mail\Html::replaceTagsCompletley($_html,'head'); // Strip out stuff in head
5095
+		if (stripos($_html,'style')!==false)
5096
+		{
5097
+			Mail\Html::replaceTagsCompletley($_html,'style');
5098
+		}
5099
+		// clean out empty or pagewide style definitions / left over tags
5100
+		if (stripos($_html,'head')!==false)
5101
+		{
5102
+			Mail\Html::replaceTagsCompletley($_html,'head');
5103
+		}
5104
+		// Strip out stuff in head
4325 5105
 		//if (stripos($_html,'![if')!==false && stripos($_html,'<![endif]>')!==false) Mail\Html::replaceTagsCompletley($_html,'!\[if','<!\[endif\]>',false); // Strip out stuff in ifs
4326 5106
 		//if (stripos($_html,'!--[if')!==false && stripos($_html,'<![endif]-->')!==false) Mail\Html::replaceTagsCompletley($_html,'!--\[if','<!\[endif\]-->',false); // Strip out stuff in ifs
4327 5107
 		//error_log(__METHOD__.' ('.__LINE__.') '.$_html);
4328 5108
 
4329
-		if (get_magic_quotes_gpc() === 1) $_html = stripslashes($_html);
5109
+		if (get_magic_quotes_gpc() === 1)
5110
+		{
5111
+			$_html = stripslashes($_html);
5112
+		}
4330 5113
 		// Strip out doctype in head, as htmlLawed cannot handle it TODO: Consider extracting it and adding it afterwards
4331
-		if (stripos($_html,'!doctype')!==false) Mail\Html::replaceTagsCompletley($_html,'!doctype');
4332
-		if (stripos($_html,'?xml:namespace')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml:namespace','/>',false);
4333
-		if (stripos($_html,'?xml version')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml version','\?>',false);
4334
-		if (strpos($_html,'!CURSOR')!==false) Mail\Html::replaceTagsCompletley($_html,'!CURSOR');
5114
+		if (stripos($_html,'!doctype')!==false)
5115
+		{
5116
+			Mail\Html::replaceTagsCompletley($_html,'!doctype');
5117
+		}
5118
+		if (stripos($_html,'?xml:namespace')!==false)
5119
+		{
5120
+			Mail\Html::replaceTagsCompletley($_html,'\?xml:namespace','/>',false);
5121
+		}
5122
+		if (stripos($_html,'?xml version')!==false)
5123
+		{
5124
+			Mail\Html::replaceTagsCompletley($_html,'\?xml version','\?>',false);
5125
+		}
5126
+		if (strpos($_html,'!CURSOR')!==false)
5127
+		{
5128
+			Mail\Html::replaceTagsCompletley($_html,'!CURSOR');
5129
+		}
4335 5130
 		// htmLawed filter only the 'body'
4336 5131
 		//preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $_html, $matches);
4337 5132
 		//if ($matches[2])
@@ -4370,8 +5165,10 @@  discard block
 block discarded – undo
4370 5165
 		//$charSet = 'iso-8859-1';//self::$displayCharset; //'iso-8859-1'; // self::displayCharset seems to be asmarter fallback than iso-8859-1
4371 5166
 		$CharsetFound=false;
4372 5167
 		//echo "#".$_mimePartObject->encoding.'#<br>';
4373
-		if(is_array($_mimePartObject->parameters)) {
4374
-			if(isset($_mimePartObject->parameters['CHARSET'])) {
5168
+		if(is_array($_mimePartObject->parameters))
5169
+		{
5170
+			if(isset($_mimePartObject->parameters['CHARSET']))
5171
+			{
4375 5172
 				$charSet = $_mimePartObject->parameters['CHARSET'];
4376 5173
 				$CharsetFound=true;
4377 5174
 			}
@@ -4392,7 +5189,10 @@  discard block
 block discarded – undo
4392 5189
 	function decodeMimePart($_mimeMessage, $_encoding, $_charset = '')
4393 5190
 	{
4394 5191
 		// decode the part
4395
-		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage,true));
5192
+		if (self::$debug)
5193
+		{
5194
+			error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage,true));
5195
+		}
4396 5196
 		switch (strtoupper($_encoding))
4397 5197
 		{
4398 5198
 			case 'BASE64':
@@ -4433,13 +5233,19 @@  discard block
 block discarded – undo
4433 5233
 		// sometimes there are 3 parts, when there is an ics/ical attached/included-> we want to show that
4434 5234
 		// as attachment AND as abstracted ical information (we use our notification style here).
4435 5235
 		$partText = $partCalendar = $partHTML = null;
4436
-		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__,"LINE"=>__LINE__,"STRUCTURE"=>$_structure));
5236
+		if (self::$debug)
5237
+		{
5238
+			_debug_array(array("METHOD"=>__METHOD__,"LINE"=>__LINE__,"STRUCTURE"=>$_structure));
5239
+		}
4437 5240
 		//error_log(__METHOD__.' ('.__LINE__.') ');
4438 5241
 		$ignore_first_part = true;
4439 5242
 		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4440 5243
 		{
4441 5244
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type"." ignoreFirstPart:".$ignore_first_part);
4442
-			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
5245
+			if (self::$debug)
5246
+			{
5247
+				echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
5248
+			}
4443 5249
 
4444 5250
 			if ($ignore_first_part)
4445 5251
 			{
@@ -4455,15 +5261,24 @@  discard block
 block discarded – undo
4455 5261
 					switch($mimePart->getSubType())
4456 5262
 					{
4457 5263
 						case 'plain':
4458
-							if ($mimePart->getBytes() > 0) $partText = $mimePart;
5264
+							if ($mimePart->getBytes() > 0)
5265
+							{
5266
+								$partText = $mimePart;
5267
+							}
4459 5268
 							break;
4460 5269
 
4461 5270
 						case 'html':
4462
-							if ($mimePart->getBytes() > 0)  $partHTML = $mimePart;
5271
+							if ($mimePart->getBytes() > 0)
5272
+							{
5273
+								$partHTML = $mimePart;
5274
+							}
4463 5275
 							break;
4464 5276
 
4465 5277
 						case 'calendar':
4466
-							if ($mimePart->getBytes() > 0)  $partCalendar = $mimePart;
5278
+							if ($mimePart->getBytes() > 0)
5279
+							{
5280
+								$partCalendar = $mimePart;
5281
+							}
4467 5282
 							break;
4468 5283
 					}
4469 5284
 					break;
@@ -4476,7 +5291,10 @@  discard block
 block discarded – undo
4476 5291
 							if (count($mimePart->getParts()) > 1)
4477 5292
 							{
4478 5293
 								// in a multipart alternative we treat the multipart/related as html part
4479
-								if (self::$debug) error_log(__METHOD__." process MULTIPART/".$mimePart->getSubType()." with array as subparts");
5294
+								if (self::$debug)
5295
+								{
5296
+									error_log(__METHOD__." process MULTIPART/".$mimePart->getSubType()." with array as subparts");
5297
+								}
4480 5298
 								$partHTML = $mimePart;
4481 5299
 								break 3; // GET OUT OF LOOP, will be processed according to type
4482 5300
 							}
@@ -4557,9 +5375,15 @@  discard block
 block discarded – undo
4557 5375
 	 */
4558 5376
 	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts=array())
4559 5377
 	{
4560
-		if (self::$debug) echo __METHOD__."$_uid, $_htmlMode<br>";
5378
+		if (self::$debug)
5379
+		{
5380
+			echo __METHOD__."$_uid, $_htmlMode<br>";
5381
+		}
4561 5382
 		$bodyPart = array();
4562
-		if (self::$debug) _debug_array($_structure);
5383
+		if (self::$debug)
5384
+		{
5385
+			_debug_array($_structure);
5386
+		}
4563 5387
 
4564 5388
 		$ignore_first_part = true;
4565 5389
 		//$skipParts = array();
@@ -4567,7 +5391,10 @@  discard block
 block discarded – undo
4567 5391
 		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4568 5392
 		{
4569 5393
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type");
4570
-			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
5394
+			if (self::$debug)
5395
+			{
5396
+				echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
5397
+			}
4571 5398
 			if ($ignore_first_part)
4572 5399
 			{
4573 5400
 				$ignore_first_part = false;
@@ -4585,7 +5412,10 @@  discard block
 block discarded – undo
4585 5412
 			switch($part->getPrimaryType())
4586 5413
 			{
4587 5414
 				case 'multipart':
4588
-					if ($part->getDisposition() == 'attachment') continue;
5415
+					if ($part->getDisposition() == 'attachment')
5416
+					{
5417
+						continue;
5418
+					}
4589 5419
 					switch($part->getSubType())
4590 5420
 					{
4591 5421
 						case 'alternative':
@@ -4650,7 +5480,9 @@  discard block
 block discarded – undo
4650 5480
 					if($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4651 5481
 					{
4652 5482
 						$skipParts[$mime_id.'.0'] = $mime_type;
4653
-						foreach($part->contentTypeMap() as $sub_id => $sub_type){ $skipParts[$sub_id] = $sub_type;}
5483
+						foreach($part->contentTypeMap() as $sub_id => $sub_type)
5484
+						{
5485
+$skipParts[$sub_id] = $sub_type;}
4654 5486
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$_uid.' Part:'.$mime_id.':'.array2string($skipParts));
4655 5487
 						//break 2;
4656 5488
 					}
@@ -4693,7 +5525,10 @@  discard block
 block discarded – undo
4693 5525
 	 */
4694 5526
 	function getBodyPart($_uid, $_partID=null, $_folder=null, $_preserveSeen=false, $_stream=false, &$_encoding=null, $_tryDecodingServerside=true)
4695 5527
 	{
4696
-		if (self::$debug) error_log( __METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
5528
+		if (self::$debug)
5529
+		{
5530
+			error_log( __METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
5531
+		}
4697 5532
 
4698 5533
 		if (empty($_folder))
4699 5534
 		{
@@ -4702,7 +5537,10 @@  discard block
 block discarded – undo
4702 5537
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_folder).'/'.$this->icServer->getCurrentMailbox().'/'. $this->sessionData['mailbox']);
4703 5538
 		// querying contents of body part
4704 5539
 		$uidsToFetch = new Horde_Imap_Client_Ids();
4705
-		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5540
+		if (!(is_object($_uid) || is_array($_uid)))
5541
+		{
5542
+			$_uid = (array)$_uid;
5543
+		}
4706 5544
 		$uidsToFetch->add($_uid);
4707 5545
 
4708 5546
 		$fquery = new Horde_Imap_Client_Fetch_Query();
@@ -4710,9 +5548,12 @@  discard block
 block discarded – undo
4710 5548
 			'peek' => $_preserveSeen,
4711 5549
 			'decode' => true,	// try decode on server, does NOT neccessary work
4712 5550
 		);
4713
-		if ($_tryDecodingServerside===false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
5551
+		if ($_tryDecodingServerside===false)
5552
+		{
5553
+			// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4714 5554
 		{
4715 5555
 			$_tryDecodingServerside=false;
5556
+		}
4716 5557
 			$fetchParams = array(
4717 5558
 				'peek' => $_preserveSeen,
4718 5559
 			);
@@ -4754,7 +5595,10 @@  discard block
 block discarded – undo
4754 5595
 	{
4755 5596
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_uid.':'.array2string($_structure).' '.function_backtrace());
4756 5597
 		$bodyPart = array();
4757
-		if (self::$debug) _debug_array(array($_structure,function_backtrace()));
5598
+		if (self::$debug)
5599
+		{
5600
+			_debug_array(array($_structure,function_backtrace()));
5601
+		}
4758 5602
 
4759 5603
 		if($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4760 5604
 		{
@@ -4805,8 +5649,12 @@  discard block
 block discarded – undo
4805 5649
 	 */
4806 5650
 	function getMessageBody($_uid, $_htmlOptions='', $_partID=null, Horde_Mime_Part $_structure=null, $_preserveSeen = false, $_folder = '', &$calendar_part=null)
4807 5651
 	{
4808
-		if (self::$debug) echo __METHOD__."$_uid, $_htmlOptions, $_partID<br>";
4809
-		if($_htmlOptions != '') {
5652
+		if (self::$debug)
5653
+		{
5654
+			echo __METHOD__."$_uid, $_htmlOptions, $_partID<br>";
5655
+		}
5656
+		if($_htmlOptions != '')
5657
+		{
4810 5658
 			$this->htmlOptions = $_htmlOptions;
4811 5659
 		}
4812 5660
 		if (empty($_folder))
@@ -4895,7 +5743,9 @@  discard block
 block discarded – undo
4895 5743
 						default:
4896 5744
 							$bodyPart = array($this->getTextPart($_uid, $_structure, $this->htmlOptions, $_preserveSeen));
4897 5745
 					}
4898
-				} else {
5746
+				}
5747
+				else
5748
+				{
4899 5749
 					// what if the structure->disposition is attachment ,...
4900 5750
 				}
4901 5751
 				return self::normalizeBodyParts($bodyPart);
@@ -4906,13 +5756,18 @@  discard block
 block discarded – undo
4906 5756
 				{
4907 5757
 					case 'rfc822':
4908 5758
 						$newStructure = $_structure->getParts();
4909
-						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]);}
5759
+						if (self::$debug)
5760
+						{
5761
+echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]);}
4910 5762
 						return self::normalizeBodyParts($this->getMessageBody($_uid, $_htmlOptions, $newStructure[0]->getMimeId(), $newStructure[0], $_preserveSeen, $_folder));
4911 5763
 				}
4912 5764
 				break;
4913 5765
 
4914 5766
 			default:
4915
-				if (self::$debug) _debug_array($_structure);
5767
+				if (self::$debug)
5768
+				{
5769
+					_debug_array($_structure);
5770
+				}
4916 5771
 				return array(
4917 5772
 					array(
4918 5773
 						'body'		=> lang('The mimeparser can not parse this message.').$_structure->getType(),
@@ -4936,9 +5791,12 @@  discard block
 block discarded – undo
4936 5791
 		{
4937 5792
 			foreach($_bodyParts as $singleBodyPart)
4938 5793
 			{
4939
-				if (!isset($singleBodyPart['body'])) {
5794
+				if (!isset($singleBodyPart['body']))
5795
+				{
4940 5796
 					$buff = self::normalizeBodyParts($singleBodyPart);
4941
-					foreach ((array)$buff as $val) { $body2return[] = $val;}
5797
+					foreach ((array)$buff as $val)
5798
+					{
5799
+$body2return[] = $val;}
4942 5800
 					continue;
4943 5801
 				}
4944 5802
 				$body2return[] = $singleBodyPart;
@@ -4964,13 +5822,20 @@  discard block
 block discarded – undo
4964 5822
 		$message='';
4965 5823
 		for($i=0; $i<count($bodyParts); $i++)
4966 5824
 		{
4967
-			if (!isset($bodyParts[$i]['body'])) {
5825
+			if (!isset($bodyParts[$i]['body']))
5826
+			{
4968 5827
 				$bodyParts[$i]['body'] = self::getdisplayableBody($mailClass, $bodyParts[$i], $preserveHTML, $useTidy);
4969 5828
 				$message .= empty($bodyParts[$i]['body'])?'':$bodyParts[$i]['body'];
4970 5829
 				continue;
4971 5830
 			}
4972
-			if (isset($bodyParts[$i]['error'])) continue;
4973
-			if (empty($bodyParts[$i]['body'])) continue;
5831
+			if (isset($bodyParts[$i]['error']))
5832
+			{
5833
+				continue;
5834
+			}
5835
+			if (empty($bodyParts[$i]['body']))
5836
+			{
5837
+				continue;
5838
+			}
4974 5839
 			// some characterreplacements, as they fail to translate
4975 5840
 			$sar = array(
4976 5841
 				'@(\x84|\x93|\x94)@',
@@ -4997,13 +5862,17 @@  discard block
 block discarded – undo
4997 5862
 				$bodyParts[$i]['body'] = preg_replace($sar,$rar,$bodyParts[$i]['body']);
4998 5863
 			}
4999 5864
 
5000
-			if ($bodyParts[$i]['charSet']===false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5865
+			if ($bodyParts[$i]['charSet']===false)
5866
+			{
5867
+				$bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5868
+			}
5001 5869
 			// add line breaks to $bodyParts
5002 5870
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
5003 5871
 			$newBody  = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
5004 5872
 			//error_log(__METHOD__.' ('.__LINE__.') '.' MimeType:'.$bodyParts[$i]['mimeType'].'->'.$newBody);
5005 5873
 			$mailClass->activeMimeType = 'text/plain';
5006
-			if ($bodyParts[$i]['mimeType'] == 'text/html') {
5874
+			if ($bodyParts[$i]['mimeType'] == 'text/html')
5875
+			{
5007 5876
 				$mailClass->activeMimeType = $bodyParts[$i]['mimeType'];
5008 5877
 				if (!$preserveHTML)
5009 5878
 				{
@@ -5049,15 +5918,28 @@  discard block
 block discarded – undo
5049 5918
 						// as we switched off HTMLaweds tidy functionality
5050 5919
 						$newBody = str_replace(array('&amp;amp;','<DIV><BR></DIV>',"<DIV>&nbsp;</DIV>",'<div>&nbsp;</div>'),array('&amp;','<BR>','<BR>','<BR>'),$newBody);
5051 5920
 						$newBody = $htmLawed->run($newBody,self::$htmLawed_config);
5052
-						if ($hasOther && $preserveHTML) $newBody = $matches[1]. $newBody. $matches[3];
5921
+						if ($hasOther && $preserveHTML)
5922
+						{
5923
+							$newBody = $matches[1]. $newBody. $matches[3];
5924
+						}
5053 5925
 						$alreadyHtmlLawed=true;
5054 5926
 					}
5055 5927
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after purify:'.$newBody);
5056
-					if ($preserveHTML==false) $newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,true,true);
5928
+					if ($preserveHTML==false)
5929
+					{
5930
+						$newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,true,true);
5931
+					}
5057 5932
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after convertHTMLToText:'.$newBody);
5058
-					if ($preserveHTML==false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
5933
+					if ($preserveHTML==false)
5934
+					{
5935
+						$newBody = nl2br($newBody);
5936
+					}
5937
+					// we need this, as htmLawed removes \r\n
5059 5938
 					/*if (!$alreadyHtmlLawed) */ $mailClass->getCleanHTML($newBody); // remove stuff we regard as unwanted
5060
-					if ($preserveHTML==false) $newBody = str_replace("<br />","\r\n",$newBody);
5939
+					if ($preserveHTML==false)
5940
+					{
5941
+						$newBody = str_replace("<br />","\r\n",$newBody);
5942
+					}
5061 5943
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after getClean:'.$newBody);
5062 5944
 				}
5063 5945
 				$message .= $newBody;
@@ -5094,12 +5976,12 @@  discard block
 block discarded – undo
5094 5976
 				  substr($line,0,strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
5095 5977
 				 )
5096 5978
 				)
5097
-			   )
5098
-			{
5979
+			   ) {
5099 5980
 				$s=explode(" ", $line);
5100 5981
 				$line = "";
5101 5982
 				$linecnt = 0;
5102
-				foreach ($s as &$v) {
5983
+				foreach ($s as &$v)
5984
+				{
5103 5985
 					$cnt = strlen($v);
5104 5986
 					// only break long words within the wordboundaries,
5105 5987
 					// but it may destroy links, so we check for href and dont do it if we find one
@@ -5109,14 +5991,20 @@  discard block
 block discarded – undo
5109 5991
 						$v=wordwrap($v, $allowedLength, $cut, true);
5110 5992
 					}
5111 5993
 					// the rest should be broken at the start of the new word that exceeds the limit
5112
-					if ($linecnt+$cnt > $allowedLength) {
5994
+					if ($linecnt+$cnt > $allowedLength)
5995
+					{
5113 5996
 						$v=$cut.$v;
5114 5997
 						#$linecnt = 0;
5115 5998
 						$linecnt =strlen($v)-strlen($cut);
5116
-					} else {
5999
+					}
6000
+					else
6001
+					{
5117 6002
 						$linecnt += $cnt;
5118 6003
 					}
5119
-					if (strlen($v)) $line .= (strlen($line) ? " " : "").$v;
6004
+					if (strlen($v))
6005
+					{
6006
+						$line .= (strlen($line) ? " " : "").$v;
6007
+					}
5120 6008
 				}
5121 6009
 			}
5122 6010
 			$newStr .= $line . "\n";
@@ -5137,11 +6025,18 @@  discard block
 block discarded – undo
5137 6025
 	function getMessageEnvelope($_uid, $_partID = '',$decode=false, $_folder='', $_useHeaderInsteadOfEnvelope=false)
5138 6026
 	{
5139 6027
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder".function_backtrace());
5140
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6028
+		if (empty($_folder))
6029
+		{
6030
+			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6031
+		}
5141 6032
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder");
5142
-		if((empty($_partID)||$_partID=='null')&&$_useHeaderInsteadOfEnvelope===false) {
6033
+		if((empty($_partID)||$_partID=='null')&&$_useHeaderInsteadOfEnvelope===false)
6034
+		{
5143 6035
 			$uidsToFetch = new Horde_Imap_Client_Ids();
5144
-			if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
6036
+			if (!(is_object($_uid) || is_array($_uid)))
6037
+			{
6038
+				$_uid = (array)$_uid;
6039
+			}
5145 6040
 			$uidsToFetch->add($_uid);
5146 6041
 
5147 6042
 			$fquery = new Horde_Imap_Client_Fetch_Query();
@@ -5151,8 +6046,10 @@  discard block
 block discarded – undo
5151 6046
 			$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5152 6047
 				'ids' => $uidsToFetch,
5153 6048
 			));
5154
-			if (is_object($headersNew)) {
5155
-				foreach($headersNew as &$_headerObject) {
6049
+			if (is_object($headersNew))
6050
+			{
6051
+				foreach($headersNew as &$_headerObject)
6052
+				{
5156 6053
 					$env = $_headerObject->getEnvelope();
5157 6054
 					//_debug_array($envFields->singleFields());
5158 6055
 					$singleFields = $envFields->singleFields();
@@ -5169,7 +6066,10 @@  discard block
 block discarded – undo
5169 6066
 								//error_log(__METHOD__.' ('.__LINE__.') '.$v.'->'.array2string($env->$v->addresses));
5170 6067
 								$envelope[$v]=$env->$v->addresses;
5171 6068
 								$address = array();
5172
-								if (!is_array($envelope[$v])) break;
6069
+								if (!is_array($envelope[$v]))
6070
+								{
6071
+									break;
6072
+								}
5173 6073
 								foreach ($envelope[$v] as $k => $ad)
5174 6074
 								{
5175 6075
 									if (stripos($ad,'@')===false)
@@ -5206,7 +6106,9 @@  discard block
 block discarded – undo
5206 6106
 				}
5207 6107
 			}
5208 6108
 			return $envelope;
5209
-		} else {
6109
+		}
6110
+		else
6111
+		{
5210 6112
 
5211 6113
 			$headers = $this->getMessageHeader($_uid, $_partID, true,true,$_folder);
5212 6114
 
@@ -5217,19 +6119,43 @@  discard block
 block discarded – undo
5217 6119
 				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']):$headers['SUBJECT']),
5218 6120
 				'MESSAGE_ID'	=> $headers['MESSAGE-ID']
5219 6121
 			);
5220
-			if (isset($headers['IN-REPLY-TO'])) $newData['IN-REPLY-TO'] = $headers['IN-REPLY-TO'];
5221
-			if (isset($headers['REFERENCES'])) $newData['REFERENCES'] = $headers['REFERENCES'];
5222
-			if (isset($headers['THREAD-TOPIC'])) $newData['THREAD-TOPIC'] = $headers['THREAD-TOPIC'];
5223
-			if (isset($headers['THREAD-INDEX'])) $newData['THREAD-INDEX'] = $headers['THREAD-INDEX'];
5224
-			if (isset($headers['LIST-ID'])) $newData['LIST-ID'] = $headers['LIST-ID'];
5225
-			if (isset($headers['SIZE'])) $newData['SIZE'] = $headers['SIZE'];
6122
+			if (isset($headers['IN-REPLY-TO']))
6123
+			{
6124
+				$newData['IN-REPLY-TO'] = $headers['IN-REPLY-TO'];
6125
+			}
6126
+			if (isset($headers['REFERENCES']))
6127
+			{
6128
+				$newData['REFERENCES'] = $headers['REFERENCES'];
6129
+			}
6130
+			if (isset($headers['THREAD-TOPIC']))
6131
+			{
6132
+				$newData['THREAD-TOPIC'] = $headers['THREAD-TOPIC'];
6133
+			}
6134
+			if (isset($headers['THREAD-INDEX']))
6135
+			{
6136
+				$newData['THREAD-INDEX'] = $headers['THREAD-INDEX'];
6137
+			}
6138
+			if (isset($headers['LIST-ID']))
6139
+			{
6140
+				$newData['LIST-ID'] = $headers['LIST-ID'];
6141
+			}
6142
+			if (isset($headers['SIZE']))
6143
+			{
6144
+				$newData['SIZE'] = $headers['SIZE'];
6145
+			}
5226 6146
 			//_debug_array($newData);
5227 6147
 			$recepientList = array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO');
5228
-			foreach($recepientList as $recepientType) {
5229
-				if(isset($headers[$recepientType])) {
5230
-					if ($decode) $headers[$recepientType] =  self::decode_header($headers[$recepientType],true);
6148
+			foreach($recepientList as $recepientType)
6149
+			{
6150
+				if(isset($headers[$recepientType]))
6151
+				{
6152
+					if ($decode)
6153
+					{
6154
+						$headers[$recepientType] =  self::decode_header($headers[$recepientType],true);
6155
+					}
5231 6156
 					//error_log(__METHOD__.__LINE__." ".$recepientType."->".array2string($headers[$recepientType]));
5232
-					foreach(self::parseAddressList($headers[$recepientType]) as $singleAddress) {
6157
+					foreach(self::parseAddressList($headers[$recepientType]) as $singleAddress)
6158
+					{
5233 6159
 						$addressData = array(
5234 6160
 							'PERSONAL_NAME'		=> $singleAddress->personal ? $singleAddress->personal : 'NIL',
5235 6161
 							'AT_DOMAIN_LIST'	=> $singleAddress->adl ? $singleAddress->adl : 'NIL',
@@ -5237,17 +6163,25 @@  discard block
 block discarded – undo
5237 6163
 							'HOST_NAME'		=> $singleAddress->host ? $singleAddress->host : 'NIL',
5238 6164
 							'EMAIL'			=> $singleAddress->host ? $singleAddress->mailbox.'@'.$singleAddress->host : $singleAddress->mailbox,
5239 6165
 						);
5240
-						if($addressData['PERSONAL_NAME'] != 'NIL') {
6166
+						if($addressData['PERSONAL_NAME'] != 'NIL')
6167
+						{
5241 6168
 							$addressData['RFC822_EMAIL'] = imap_rfc822_write_address($singleAddress->mailbox, $singleAddress->host, $singleAddress->personal);
5242
-						} else {
6169
+						}
6170
+						else
6171
+						{
5243 6172
 							$addressData['RFC822_EMAIL'] = 'NIL';
5244 6173
 						}
5245 6174
 						$newData[$recepientType][] = ($addressData['RFC822_EMAIL']!='NIL'?$addressData['RFC822_EMAIL']:$addressData['EMAIL']);//$addressData;
5246 6175
 					}
5247
-				} else {
5248
-					if($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
6176
+				}
6177
+				else
6178
+				{
6179
+					if($recepientType == 'SENDER' || $recepientType == 'REPLY-TO')
6180
+					{
5249 6181
 						$newData[$recepientType] = $newData['FROM'];
5250
-					} else {
6182
+					}
6183
+					else
6184
+					{
5251 6185
 						$newData[$recepientType] = array();
5252 6186
 					}
5253 6187
 				}
@@ -5270,9 +6204,15 @@  discard block
 block discarded – undo
5270 6204
 	function getMessageHeader($_uid, $_partID = '',$decode=false, $preserveUnSeen=false, $_folder='')
5271 6205
 	{
5272 6206
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$_uid.', '.$_partID.', '.$decode.', '.$preserveUnSeen.', '.$_folder);
5273
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6207
+		if (empty($_folder))
6208
+		{
6209
+			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6210
+		}
5274 6211
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5275
-		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
6212
+		if (!(is_object($_uid) || is_array($_uid)))
6213
+		{
6214
+			$_uid = (array)$_uid;
6215
+		}
5276 6216
 		$uidsToFetch->add($_uid);
5277 6217
 
5278 6218
 		$fquery = new Horde_Imap_Client_Fetch_Query();
@@ -5290,7 +6230,8 @@  discard block
 block discarded – undo
5290 6230
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5291 6231
 			'ids' => $uidsToFetch,
5292 6232
 		));
5293
-		if (is_object($headersNew)) {
6233
+		if (is_object($headersNew))
6234
+		{
5294 6235
 			foreach($headersNew as $_fetchObject)
5295 6236
 			{
5296 6237
 				$headers = $_fetchObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
@@ -5312,11 +6253,17 @@  discard block
 block discarded – undo
5312 6253
 			}
5313 6254
 			if ($decode === 'object')
5314 6255
 			{
5315
-				if (is_object($headers)) $headers->setUserAgent('EGroupware API '.$GLOBALS['egw_info']['server']['versions']['phpgwapi']);
6256
+				if (is_object($headers))
6257
+				{
6258
+					$headers->setUserAgent('EGroupware API '.$GLOBALS['egw_info']['server']['versions']['phpgwapi']);
6259
+				}
5316 6260
 				return $headers;
5317 6261
 			}
5318 6262
 			$retValue = is_object($headers) ? $headers->toArray():array();
5319
-			if ($size) $retValue['size'] = $size;
6263
+			if ($size)
6264
+			{
6265
+				$retValue['size'] = $size;
6266
+			}
5320 6267
 		}
5321 6268
 		$retValue = array_change_key_case($retValue,CASE_UPPER);
5322 6269
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue));
@@ -5348,10 +6295,16 @@  discard block
 block discarded – undo
5348 6295
 	function getMessageRawHeader($_uid, $_partID = '', $_folder = '')
5349 6296
 	{
5350 6297
 		static $rawHeaders;
5351
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6298
+		if (empty($_folder))
6299
+		{
6300
+			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6301
+		}
5352 6302
 		//error_log(__METHOD__.' ('.__LINE__.') '." Try Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5353 6303
 
5354
-		if (is_null($rawHeaders)||!is_array($rawHeaders)) $rawHeaders = Cache::getCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
6304
+		if (is_null($rawHeaders)||!is_array($rawHeaders))
6305
+		{
6306
+			$rawHeaders = Cache::getCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
6307
+		}
5355 6308
 		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5356 6309
 		{
5357 6310
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Header $_uid, $_partID in Folder $_folder");
@@ -5359,7 +6312,10 @@  discard block
 block discarded – undo
5359 6312
 		}
5360 6313
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5361 6314
 		$uid = $_uid;
5362
-		if (!(is_object($_uid) || is_array($_uid))) $uid = (array)$_uid;
6315
+		if (!(is_object($_uid) || is_array($_uid)))
6316
+		{
6317
+			$uid = (array)$_uid;
6318
+		}
5363 6319
 		$uidsToFetch->add($uid);
5364 6320
 
5365 6321
 		$fquery = new Horde_Imap_Client_Fetch_Query();
@@ -5375,8 +6331,10 @@  discard block
 block discarded – undo
5375 6331
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5376 6332
 			'ids' => $uidsToFetch,
5377 6333
 		));
5378
-		if (is_object($headersNew)) {
5379
-			foreach($headersNew as &$_headerObject) {
6334
+		if (is_object($headersNew))
6335
+		{
6336
+			foreach($headersNew as &$_headerObject)
6337
+			{
5380 6338
 				$retValue = $_headerObject->getHeaderText();
5381 6339
 				if ($_partID != '')
5382 6340
 				{
@@ -5404,22 +6362,33 @@  discard block
 block discarded – undo
5404 6362
 	static function &getStyles($_bodyParts)
5405 6363
 	{
5406 6364
 		$style = '';
5407
-		if (empty($_bodyParts)) return "";
5408
-		foreach((array)$_bodyParts as $singleBodyPart) {
5409
-			if (!isset($singleBodyPart['body'])) {
6365
+		if (empty($_bodyParts))
6366
+		{
6367
+			return "";
6368
+		}
6369
+		foreach((array)$_bodyParts as $singleBodyPart)
6370
+		{
6371
+			if (!isset($singleBodyPart['body']))
6372
+			{
5410 6373
 				$singleBodyPart['body'] = self::getStyles($singleBodyPart);
5411 6374
 				$style .= $singleBodyPart['body'];
5412 6375
 				continue;
5413 6376
 			}
5414 6377
 
5415
-			if ($singleBodyPart['charSet']===false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
6378
+			if ($singleBodyPart['charSet']===false)
6379
+			{
6380
+				$singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
6381
+			}
5416 6382
 			$singleBodyPart['body'] = Translation::convert(
5417 6383
 				$singleBodyPart['body'],
5418 6384
 				strtolower($singleBodyPart['charSet'])
5419 6385
 			);
5420 6386
 			$ct = 0;
5421 6387
 			$newStyle=array();
5422
-			if (stripos($singleBodyPart['body'],'<style')!==false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
6388
+			if (stripos($singleBodyPart['body'],'<style')!==false)
6389
+			{
6390
+				$ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
6391
+			}
5423 6392
 			if ($ct>0)
5424 6393
 			{
5425 6394
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$ct.'#'.array2string($newStyle));
@@ -5451,7 +6420,11 @@  discard block
 block discarded – undo
5451 6420
 		// CSS Security
5452 6421
 		// http://code.google.com/p/browsersec/wiki/Part1#Cascading_stylesheets
5453 6422
 		$css = preg_replace('/(javascript|expression|-moz-binding)/i','',$style);
5454
-		if (stripos($css,'script')!==false) Mail\Html::replaceTagsCompletley($css,'script'); // Strip out script that may be included
6423
+		if (stripos($css,'script')!==false)
6424
+		{
6425
+			Mail\Html::replaceTagsCompletley($css,'script');
6426
+		}
6427
+		// Strip out script that may be included
5455 6428
 		// we need this, as styledefinitions are enclosed with curly brackets; and template stuff tries to replace everything between curly brackets that is having no horizontal whitespace
5456 6429
 		// as the comments as <!-- styledefinition --> in stylesheet are outdated, and ck-editor does not understand it, we remove it
5457 6430
 		$css = str_replace(array(':','<!--','-->'),array(': ','',''),$css);
@@ -5473,8 +6446,14 @@  discard block
 block discarded – undo
5473 6446
 	{
5474 6447
 		//TODO: caching einbauen static!
5475 6448
 		static $rawBody;
5476
-		if (is_null($rawBody)) $rawBody = array();
5477
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6449
+		if (is_null($rawBody))
6450
+		{
6451
+			$rawBody = array();
6452
+		}
6453
+		if (empty($_folder))
6454
+		{
6455
+			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6456
+		}
5478 6457
 		if (!$_stream && isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5479 6458
 		{
5480 6459
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Body $_uid, $_partID in Folder $_folder");
@@ -5483,7 +6462,10 @@  discard block
 block discarded – undo
5483 6462
 
5484 6463
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5485 6464
 		$uid = $_uid;
5486
-		if (!(is_object($_uid) || is_array($_uid))) $uid = (array)$_uid;
6465
+		if (!(is_object($_uid) || is_array($_uid)))
6466
+		{
6467
+			$uid = (array)$_uid;
6468
+		}
5487 6469
 		$uidsToFetch->add($uid);
5488 6470
 
5489 6471
 		$fquery = new Horde_Imap_Client_Fetch_Query();
@@ -5496,8 +6478,10 @@  discard block
 block discarded – undo
5496 6478
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5497 6479
 			'ids' => $uidsToFetch,
5498 6480
 		));
5499
-		if (is_object($headersNew)) {
5500
-			foreach($headersNew as &$_headerObject) {
6481
+		if (is_object($headersNew))
6482
+		{
6483
+			foreach($headersNew as &$_headerObject)
6484
+			{
5501 6485
 				$body = $_headerObject->getFullMsg($_stream);
5502 6486
 				if ($_partID != '')
5503 6487
 				{
@@ -5533,14 +6517,20 @@  discard block
 block discarded – undo
5533 6517
 	 */
5534 6518
 	function getStructure($_uid, $_partID=null, $_folder=null, $_preserveSeen=false)
5535 6519
 	{
5536
-		if (self::$debug) error_log( __METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
6520
+		if (self::$debug)
6521
+		{
6522
+			error_log( __METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
6523
+		}
5537 6524
 
5538 6525
 		if (empty($_folder))
5539 6526
 		{
5540 6527
 			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5541 6528
 		}
5542 6529
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5543
-		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
6530
+		if (!(is_object($_uid) || is_array($_uid)))
6531
+		{
6532
+			$_uid = (array)$_uid;
6533
+		}
5544 6534
 		$uidsToFetch->add($_uid);
5545 6535
 		try
5546 6536
 		{
@@ -5549,7 +6539,10 @@  discard block
 block discarded – undo
5549 6539
 	//		$fquery->envelope();
5550 6540
 	//		$fquery->size();
5551 6541
 			$_fquery->structure();
5552
-			if ($_partID) $_fquery->bodyPart($_partID, array('peek' => $_preserveSeen));
6542
+			if ($_partID)
6543
+			{
6544
+				$_fquery->bodyPart($_partID, array('peek' => $_preserveSeen));
6545
+			}
5553 6546
 
5554 6547
 			$mail = $this->icServer->fetch($_folder, $_fquery, array(
5555 6548
 				'ids' => $uidsToFetch,
@@ -5580,16 +6573,28 @@  discard block
 block discarded – undo
5580 6573
 	 */
5581 6574
 	function getMessageAttachments($_uid, $_partID=null, Horde_Mime_Part $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=false, $resolveTNEF=true, $_folder='')
5582 6575
 	{
5583
-		if (self::$debug) error_log( __METHOD__.":$_uid, $_partID");
5584
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6576
+		if (self::$debug)
6577
+		{
6578
+			error_log( __METHOD__.":$_uid, $_partID");
6579
+		}
6580
+		if (empty($_folder))
6581
+		{
6582
+			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6583
+		}
5585 6584
 		$attachments = array();
5586 6585
 		if (!isset($_structure))
5587 6586
 		{
5588 6587
 			$_structure = $this->getStructure($_uid, $_partID,$_folder,true);
5589 6588
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.print_r($_structure->contentTypeMap(),true));
5590 6589
 		}
5591
-		if (!$_structure || !$_structure->contentTypeMap()) return array();
5592
-		if (!empty($_partID)) $_structure = $_structure->getPart($_partID);
6590
+		if (!$_structure || !$_structure->contentTypeMap())
6591
+		{
6592
+			return array();
6593
+		}
6594
+		if (!empty($_partID))
6595
+		{
6596
+			$_structure = $_structure->getPart($_partID);
6597
+		}
5593 6598
 		$skipParts = array();
5594 6599
 		$tnefParts = array();
5595 6600
 		$skip = 0;
@@ -5618,7 +6623,13 @@  discard block
 block discarded – undo
5618 6623
 			if ($mime_type=='message/rfc822' && $_partID!=$mime_id)
5619 6624
 			{
5620 6625
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
5621
-				foreach($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
6626
+				foreach($part->contentTypeMap() as $sub_id => $sub_type)
6627
+				{
6628
+if ($sub_id != $mime_id)
6629
+				{
6630
+					$skipParts[$sub_id] = $sub_type;
6631
+				}
6632
+				}
5622 6633
 			}
5623 6634
 			if (empty($partDisposition) && $partPrimaryType != 'multipart' && $partPrimaryType != 'text')
5624 6635
 			{
@@ -5629,7 +6640,10 @@  discard block
 block discarded – undo
5629 6640
 				$partDisposition='attachment';
5630 6641
 			}
5631 6642
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($skipParts));
5632
-			if (array_key_exists($mime_id,$skipParts)) continue;
6643
+			if (array_key_exists($mime_id,$skipParts))
6644
+			{
6645
+				continue;
6646
+			}
5633 6647
 
5634 6648
 			if ($partDisposition == 'attachment' ||
5635 6649
 				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId()=='') ||
@@ -5640,23 +6654,41 @@  discard block
 block discarded – undo
5640 6654
 			{
5641 6655
 				// if type is message/rfc822 and _partID is given, and MimeID equals partID
5642 6656
 				// we attempt to fetch "ourselves"
5643
-				if ($_partID==$part->getMimeId() && $part->getPrimaryType()=='message') continue;
6657
+				if ($_partID==$part->getMimeId() && $part->getPrimaryType()=='message')
6658
+				{
6659
+					continue;
6660
+				}
5644 6661
 				$attachment = $part->getAllDispositionParameters();
5645 6662
 				$attachment['disposition'] = $part->getDisposition();
5646 6663
 				$attachment['mimeType'] = $mime_type;
5647 6664
 				$attachment['uid'] = $_uid;
5648 6665
 				$attachment['partID'] = $mime_id;
5649
-				if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
6666
+				if (!isset($attachment['name'])||empty($attachment['name']))
6667
+				{
6668
+					$attachment['name'] = $part->getName();
6669
+				}
5650 6670
 				if ($fetchTextCalendar)
5651 6671
 				{
5652 6672
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part->getAllContentTypeParameters()));
5653 6673
 					$method = $part->getContentTypeParameter('method');
5654
-					if ($method) $attachment['method'] = $method;
5655
-					if (!isset($attachment['name'])) $attachment['name'] = 'event.ics';
6674
+					if ($method)
6675
+					{
6676
+						$attachment['method'] = $method;
6677
+					}
6678
+					if (!isset($attachment['name']))
6679
+					{
6680
+						$attachment['name'] = 'event.ics';
6681
+					}
5656 6682
 				}
5657 6683
 				$attachment['size'] = $part->getBytes();
5658
-				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5659
-				if (empty($attachment['name'])) $attachment['name'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($mime_type);
6684
+				if (($cid = $part->getContentId()))
6685
+				{
6686
+					$attachment['cid'] = $cid;
6687
+				}
6688
+				if (empty($attachment['name']))
6689
+				{
6690
+					$attachment['name'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($mime_type);
6691
+				}
5660 6692
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($attachment));
5661 6693
 				//typical winmail.dat attachment is
5662 6694
 				//Array([size] => 1462762[filename] => winmail.dat[mimeType] => application/ms-tnef[uid] => 100[partID] => 2[name] => winmail.dat)
@@ -5692,14 +6724,26 @@  discard block
 block discarded – undo
5692 6724
 						$attachment['uid'] = $tnp['uid'];
5693 6725
 						$attachment['partID'] = $tnp['partID'];
5694 6726
 						$attachment['is_winmail'] = $tnp['uid'].'@'.$tnp['partID'].'@'.$mime_id;
5695
-						if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
6727
+						if (!isset($attachment['name'])||empty($attachment['name']))
6728
+						{
6729
+							$attachment['name'] = $part->getName();
6730
+						}
5696 6731
 						$attachment['size'] = $part->getBytes();
5697
-						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5698
-						if (empty($attachment['name'])) $attachment['name'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
6732
+						if (($cid = $part->getContentId()))
6733
+						{
6734
+							$attachment['cid'] = $cid;
6735
+						}
6736
+						if (empty($attachment['name']))
6737
+						{
6738
+							$attachment['name'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
6739
+						}
5699 6740
 						$attachments[] = $attachment;
5700 6741
 					}
5701 6742
 				}
5702
-				if ($tnefResolved===false) $attachments[]=$tnp;
6743
+				if ($tnefResolved===false)
6744
+				{
6745
+					$attachments[]=$tnp;
6746
+				}
5703 6747
 			}
5704 6748
 		}
5705 6749
 		//error_log(__METHOD__.__LINE__.array2string($attachments));
@@ -5803,8 +6847,14 @@  discard block
 block discarded – undo
5803 6847
 
5804 6848
 				$attachment = $part->getAllDispositionParameters();
5805 6849
 				$attachment['mimeType'] = $part->getType();
5806
-				if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5807
-				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
6850
+				if (!isset($attachment['filename'])||empty($attachment['filename']))
6851
+				{
6852
+					$attachment['filename'] = $part->getName();
6853
+				}
6854
+				if (($cid = $part->getContentId()))
6855
+				{
6856
+					$attachment['cid'] = $cid;
6857
+				}
5808 6858
 				if (empty($attachment['filename']))
5809 6859
 				{
5810 6860
 					$attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?
@@ -5816,7 +6866,10 @@  discard block
 block discarded – undo
5816 6866
 				$attachments[$_uid.'@'.$_partID.'@'.$mime_id] = $attachment;
5817 6867
 			}
5818 6868
 		}
5819
-		if (!is_array($attachments)) return false;
6869
+		if (!is_array($attachments))
6870
+		{
6871
+			return false;
6872
+		}
5820 6873
 		return $attachments;
5821 6874
 	}
5822 6875
 
@@ -5835,10 +6888,16 @@  discard block
 block discarded – undo
5835 6888
 	function getAttachment($_uid, $_partID, $_winmail_nr=0, $_returnPart=true, $_stream=false, $_folder=null)
5836 6889
 	{
5837 6890
 		//error_log(__METHOD__.__LINE__."Uid:$_uid, PartId:$_partID, WinMailNr:$_winmail_nr, ReturnPart:$_returnPart, Stream:$_stream, Folder:$_folder".function_backtrace());
5838
-		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6891
+		if (!isset($_folder))
6892
+		{
6893
+			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
6894
+		}
5839 6895
 
5840 6896
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5841
-		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
6897
+		if (!(is_object($_uid) || is_array($_uid)))
6898
+		{
6899
+			$_uid = (array)$_uid;
6900
+		}
5842 6901
 		$uidsToFetch->add($_uid);
5843 6902
 
5844 6903
 		$fquery = new Horde_Imap_Client_Fetch_Query();
@@ -5847,8 +6906,10 @@  discard block
 block discarded – undo
5847 6906
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5848 6907
 			'ids' => $uidsToFetch,
5849 6908
 		));
5850
-		if (is_object($headersNew)) {
5851
-			foreach($headersNew as $id=>$_headerObject) {
6909
+		if (is_object($headersNew))
6910
+		{
6911
+			foreach($headersNew as $id=>$_headerObject)
6912
+			{
5852 6913
 				$body = $_headerObject->getFullMsg();
5853 6914
 				if ($_partID != '')
5854 6915
 				{
@@ -5862,7 +6923,10 @@  discard block
 block discarded – undo
5862 6923
 					}
5863 6924
 					// if $partDisposition is empty, we assume attachment, and hope that the function
5864 6925
 					// itself is only triggered to fetch attachments
5865
-					if (empty($partDisposition)) $partDisposition='attachment';
6926
+					if (empty($partDisposition))
6927
+					{
6928
+						$partDisposition='attachment';
6929
+					}
5866 6930
 					if ($part && ($partDisposition=='attachment' || $partDisposition=='inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
5867 6931
 					{
5868 6932
 						//$headerObject=$part->getAllDispositionParameters();//not used anywhere around here
@@ -5871,13 +6935,19 @@  discard block
 block discarded – undo
5871 6935
 						$charset = $part->getContentTypeParameter('charset');
5872 6936
 						//$structure_bytes = $part->getBytes(); $structure_partID=$part->getMimeId(); error_log(__METHOD__.__LINE__." fetchPartContents(".array2string($_uid).", $structure_partID, $_stream, $_preserveSeen,$structure_mime)" );
5873 6937
 						$this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen=true,$structure_mime);
5874
-						if ($_returnPart) return $part;
6938
+						if ($_returnPart)
6939
+						{
6940
+							return $part;
6941
+						}
5875 6942
 					}
5876 6943
 				}
5877 6944
 			}
5878 6945
 		}
5879 6946
 		$ext = MimeMagic::mime2ext($structure_mime);
5880
-		if ($ext && stripos($filename,'.')===false && stripos($filename,$ext)===false) $filename = trim($filename).'.'.$ext;
6947
+		if ($ext && stripos($filename,'.')===false && stripos($filename,$ext)===false)
6948
+		{
6949
+			$filename = trim($filename).'.'.$ext;
6950
+		}
5881 6951
 		if (!$part)
5882 6952
 		{
5883 6953
 			throw new Exception\WrongParameter("Error: Could not fetch attachment for Uid=".array2string($_uid).", PartId=$_partID, WinMailNr=$_winmail_nr, folder=$_folder");
@@ -5893,7 +6963,10 @@  discard block
 block discarded – undo
5893 6963
 		);
5894 6964
 
5895 6965
 		// try guessing the mimetype, if we get the application/octet-stream
5896
-		if (strtolower($attachmentData['type']) == 'application/octet-stream') $attachmentData['type'] = MimeMagic::filename2mime($attachmentData['filename']);
6966
+		if (strtolower($attachmentData['type']) == 'application/octet-stream')
6967
+		{
6968
+			$attachmentData['type'] = MimeMagic::filename2mime($attachmentData['filename']);
6969
+		}
5897 6970
 		# if the attachment holds a winmail number and is a winmail.dat then we have to handle that.
5898 6971
 		if ( $filename == 'winmail.dat' && $_winmail_nr)
5899 6972
 		{
@@ -5916,9 +6989,18 @@  discard block
 block discarded – undo
5916 6989
 					if ($_winmail_nr == $wantedPart.'@'.$mime_id)
5917 6990
 					{
5918 6991
 						//error_log(__METHOD__.__LINE__.'#'.$structure_mime.'#'.$filename.'#'.array2string($attachment));
5919
-						if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5920
-						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5921
-						if (empty($attachment['filename'])) $attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
6992
+						if (!isset($attachment['filename'])||empty($attachment['filename']))
6993
+						{
6994
+							$attachment['filename'] = $part->getName();
6995
+						}
6996
+						if (($cid = $part->getContentId()))
6997
+						{
6998
+							$attachment['cid'] = $cid;
6999
+						}
7000
+						if (empty($attachment['filename']))
7001
+						{
7002
+							$attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
7003
+						}
5922 7004
 						$wmattach = $attachment;
5923 7005
 						$wmattach['attachment'] = $part->getContents(array('stream'=>$_stream));
5924 7006
 
@@ -5928,7 +7010,10 @@  discard block
 block discarded – undo
5928 7010
 			if ($tnefResolved)
5929 7011
 			{
5930 7012
 				$ext = MimeMagic::mime2ext($wmattach['mimeType']);
5931
-				if ($ext && stripos($wmattach['filename'],'.')===false && stripos($wmattach['filename'],$ext)===false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
7013
+				if ($ext && stripos($wmattach['filename'],'.')===false && stripos($wmattach['filename'],$ext)===false)
7014
+				{
7015
+					$wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
7016
+				}
5932 7017
 				$attachmentData = array(
5933 7018
 					'type'       => $wmattach['mimeType'],
5934 7019
 					'filename'   => $wmattach['filename'],
@@ -5958,7 +7043,10 @@  discard block
 block discarded – undo
5958 7043
 		static $uid=null, $part=null, $structure=null;
5959 7044
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_cid, $_part");
5960 7045
 
5961
-		if(empty($_cid)) return false;
7046
+		if(empty($_cid))
7047
+		{
7048
+			return false;
7049
+		}
5962 7050
 
5963 7051
 		if ($_uid != $uid || $_part != $part)
5964 7052
 		{
@@ -5983,13 +7071,19 @@  discard block
 block discarded – undo
5983 7071
 					$attachment = $part;
5984 7072
 				}
5985 7073
 				// everything else we only consider after we checked all
5986
-				if (!isset($attachment)) $attachment = $part;
7074
+				if (!isset($attachment))
7075
+				{
7076
+					$attachment = $part;
7077
+				}
5987 7078
 				// do we want content fetched, can be done later, if not needed
5988 7079
 				if (isset($_stream))
5989 7080
 				{
5990 7081
 					$this->fetchPartContents($_uid, $attachment, $_stream);
5991 7082
 				}
5992
-				if (isset($attachment)) break;
7083
+				if (isset($attachment))
7084
+				{
7085
+					break;
7086
+				}
5993 7087
 			}
5994 7088
 		}
5995 7089
 		// set name as filename, if not set
@@ -6020,10 +7114,17 @@  discard block
 block discarded – undo
6020 7114
 	 */
6021 7115
 	public function fetchPartContents($_uid, Horde_Mime_Part $part=null, $_stream=false, $_preserveSeen=false, $_mimetype=null)
6022 7116
 	{
6023
-		if (is_null($part)) return null;//new Horde_Mime_Part;
7117
+		if (is_null($part))
7118
+		{
7119
+			return null;
7120
+		}
7121
+		//new Horde_Mime_Part;
6024 7122
 		$encoding = null;
6025 7123
 		$fetchAsBinary = true;
6026
-		if ($_mimetype && strtolower($_mimetype)=='message/rfc822') $fetchAsBinary = false;
7124
+		if ($_mimetype && strtolower($_mimetype)=='message/rfc822')
7125
+		{
7126
+			$fetchAsBinary = false;
7127
+		}
6027 7128
 		// we need to set content on structure to decode transfer encoding
6028 7129
 		$part->setContents(
6029 7130
 			$this->getBodyPart($_uid, $part->getMimeId(), null, $_preserveSeen, $_stream, $encoding, $fetchAsBinary),
@@ -6060,7 +7161,10 @@  discard block
 block discarded – undo
6060 7161
 		// the recent flag is the default enforced here ; as we assume the _flags is always set,
6061 7162
 		// we default it to hordes default (Recent) (, other wise we should not pass the parameter
6062 7163
 		// for flags at all)
6063
-		if (empty($_flags)) $_flags = '\\Recent';
7164
+		if (empty($_flags))
7165
+		{
7166
+			$_flags = '\\Recent';
7167
+		}
6064 7168
 		//if (!is_array($_flags) && stripos($_flags,',')!==false) $_flags=explode(',',$_flags);
6065 7169
 		//if (!is_array($_flags)) $_flags = (array) $_flags;
6066 7170
 		try
@@ -6077,18 +7181,27 @@  discard block
 block discarded – undo
6077 7181
 		}
6078 7182
 		catch (\Exception $e)
6079 7183
 		{
6080
-			if (self::$debug) error_log("Could not append Message: ".$e->getMessage());
7184
+			if (self::$debug)
7185
+			{
7186
+				error_log("Could not append Message: ".$e->getMessage());
7187
+			}
6081 7188
 			throw new Exception\WrongUserinput(lang("Could not append Message:").' '.$e->getMessage().': '.$e->details);
6082 7189
 			//return false;
6083 7190
 		}
6084 7191
 		//error_log(__METHOD__.' ('.__LINE__.') '.' appended UID:'.$messageid);
6085 7192
 		//$messageid = true; // for debug reasons only
6086
-		if ($messageid === true || empty($messageid)) // try to figure out the message uid
7193
+		if ($messageid === true || empty($messageid))
7194
+		{
7195
+			// try to figure out the message uid
6087 7196
 		{
6088 7197
 			$list = $this->getHeaders($_folderName, $_startMessage=1, 1, 'INTERNALDATE', true, array(),null, false);
7198
+		}
6089 7199
 			if ($list)
6090 7200
 			{
6091
-				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' MessageUid:'.$messageid.' but found:'.array2string($list));
7201
+				if (self::$debug)
7202
+				{
7203
+					error_log(__METHOD__.' ('.__LINE__.') '.' MessageUid:'.$messageid.' but found:'.array2string($list));
7204
+				}
6092 7205
 				$messageid = $list['header'][0]['uid'];
6093 7206
 			}
6094 7207
 		}
@@ -6129,7 +7242,10 @@  discard block
 block discarded – undo
6129 7242
 	{
6130 7243
 			//echo __METHOD__." called for $uid,$partid <br>";
6131 7244
 			$headers = $mailClass->getMessageHeader($uid,$partid,true,false,$mailbox);
6132
-			if (empty($headers)) return false;
7245
+			if (empty($headers))
7246
+			{
7247
+				return false;
7248
+			}
6133 7249
 			// dont force retrieval of the textpart, let mailClass preferences decide
6134 7250
 			$bodyParts = $mailClass->getMessageBody($uid,($preserveHTML?'always_display':'only_if_no_text'),$partid,null,false,$mailbox);
6135 7251
 			// if we do not want HTML but there is no TextRepresentation with the message itself, try converting
@@ -6147,15 +7263,30 @@  discard block
 block discarded – undo
6147 7263
 			//error_log(array2string($bodyParts));
6148 7264
 			$attachments = $includeAttachments?$mailClass->getMessageAttachments($uid,$partid,null,true,false,true,$mailbox):array();
6149 7265
 
6150
-			if ($mailClass->isSentFolder($mailbox)) $mailaddress = $headers['TO'];
6151
-			elseif (isset($headers['FROM'])) $mailaddress = $headers['FROM'];
6152
-			elseif (isset($headers['SENDER'])) $mailaddress = $headers['SENDER'];
6153
-			if (isset($headers['CC'])) $mailaddress .= ','.$headers['CC'];
7266
+			if ($mailClass->isSentFolder($mailbox))
7267
+			{
7268
+				$mailaddress = $headers['TO'];
7269
+			}
7270
+			elseif (isset($headers['FROM']))
7271
+			{
7272
+				$mailaddress = $headers['FROM'];
7273
+			}
7274
+			elseif (isset($headers['SENDER']))
7275
+			{
7276
+				$mailaddress = $headers['SENDER'];
7277
+			}
7278
+			if (isset($headers['CC']))
7279
+			{
7280
+				$mailaddress .= ','.$headers['CC'];
7281
+			}
6154 7282
 			//_debug_array(array($headers,$mailaddress));
6155 7283
 			$subject = $headers['SUBJECT'];
6156 7284
 
6157 7285
 			$message = self::getdisplayableBody($mailClass, $bodyParts, $preserveHTML);
6158
-			if ($preserveHTML && $mailClass->activeMimeType == 'text/plain') $message = '<pre>'.$message.'</pre>';
7286
+			if ($preserveHTML && $mailClass->activeMimeType == 'text/plain')
7287
+			{
7288
+				$message = '<pre>'.$message.'</pre>';
7289
+			}
6159 7290
 			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '',$preserveHTML) : '');
6160 7291
 			$message = $headdata.$message;
6161 7292
 			//echo __METHOD__.'<br>';
@@ -6206,7 +7337,8 @@  discard block
 block discarded – undo
6206 7337
 							$attachments[$num]['attachment'] = $c->getContents();
6207 7338
 						}
6208 7339
 						// no attempt to convert, if we dont know about the charset
6209
-						if (isset($attachments[$num]['charset'])&&!empty($attachments[$num]['charset'])) {
7340
+						if (isset($attachments[$num]['charset'])&&!empty($attachments[$num]['charset']))
7341
+						{
6210 7342
 							// we do not try guessing the charset, if it is not set
6211 7343
 							//if ($attachments[$num]['charset']===false) $attachments[$num]['charset'] = Translation::detect_encoding($attachments[$num]['attachment']);
6212 7344
 							Translation::convert($attachments[$num]['attachment'],$attachments[$num]['charset']);
@@ -6227,7 +7359,10 @@  discard block
 block discarded – undo
6227 7359
 						unset($attachments[$num]['attachment']);
6228 7360
 					}
6229 7361
 				}
6230
-				if (is_array($attachedMessages)) $attachments = array_merge($attachments,$attachedMessages);
7362
+				if (is_array($attachedMessages))
7363
+				{
7364
+					$attachments = array_merge($attachments,$attachedMessages);
7365
+				}
6231 7366
 			}
6232 7367
 			return array(
6233 7368
 					'mailaddress'=>$mailaddress,
@@ -6249,10 +7384,17 @@  discard block
 block discarded – undo
6249 7384
 	{
6250 7385
 		$c = 0;
6251 7386
 		// use the standardIdentity
6252
-		foreach($_identities as $key => $acc) {
6253
-			if ($c==0) $identity = $acc;
7387
+		foreach($_identities as $key => $acc)
7388
+		{
7389
+			if ($c==0)
7390
+			{
7391
+				$identity = $acc;
7392
+			}
6254 7393
 			//error_log(__METHOD__.__LINE__." $key == $_profile_id ");
6255
-			if ($key==$_profile_id) $identity = $acc;
7394
+			if ($key==$_profile_id)
7395
+			{
7396
+				$identity = $acc;
7397
+			}
6256 7398
 			$c++;
6257 7399
 		}
6258 7400
 		return $identity;
@@ -6268,20 +7410,53 @@  discard block
 block discarded – undo
6268 7410
 	{
6269 7411
 		$headdata = null;
6270 7412
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($header).function_backtrace());
6271
-		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML?"<br />":"\n");
6272
-		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML?"<br />":"\n");
6273
-		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML?"<br />":"\n");
6274
-		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML?"<br />":"\n");
6275
-		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML?"<br />":"\n");
6276
-		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML?"<br />":"\n");
6277
-		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML?"<br />":"\n");
6278
-		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML?"<br />":"\n");
6279
-		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] !='normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML?"<br />":"\n");
7413
+		if ($header['SUBJECT'])
7414
+		{
7415
+			$headdata = lang('subject').': '.$header['SUBJECT'].($createHTML?"<br />":"\n");
7416
+		}
7417
+		if ($header['FROM'])
7418
+		{
7419
+			$headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML?"<br />":"\n");
7420
+		}
7421
+		if ($header['SENDER'])
7422
+		{
7423
+			$headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML?"<br />":"\n");
7424
+		}
7425
+		if ($header['TO'])
7426
+		{
7427
+			$headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML?"<br />":"\n");
7428
+		}
7429
+		if ($header['CC'])
7430
+		{
7431
+			$headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML?"<br />":"\n");
7432
+		}
7433
+		if ($header['BCC'])
7434
+		{
7435
+			$headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML?"<br />":"\n");
7436
+		}
7437
+		if ($header['DATE'])
7438
+		{
7439
+			$headdata .= lang('date').': '.$header['DATE'].($createHTML?"<br />":"\n");
7440
+		}
7441
+		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal')
7442
+		{
7443
+			$headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML?"<br />":"\n");
7444
+		}
7445
+		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] !='normal')
7446
+		{
7447
+			$headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML?"<br />":"\n");
7448
+		}
6280 7449
 		//if ($mailcontent['headers']['ORGANIZATION']) $headdata .= lang('organization').': '.$mailcontent['headers']['ORGANIZATION']."\
6281 7450
 		if (!empty($headdata))
6282 7451
 		{
6283
-			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML?"<br />":"\n").$headdata;
6284
-			if (empty($headline)) $headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'').$headdata;
7452
+			if (!empty($headline) && $headline != 'SUPPRESS')
7453
+			{
7454
+				$headdata = "---------------------------- $headline ----------------------------".($createHTML?"<br />":"\n").$headdata;
7455
+			}
7456
+			if (empty($headline))
7457
+			{
7458
+				$headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'').$headdata;
7459
+			}
6285 7460
 			$headdata .= ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6286 7461
 		}
6287 7462
 		else
@@ -6315,12 +7490,15 @@  discard block
 block discarded – undo
6315 7490
 		$returnAddr ='';
6316 7491
 		if (is_array($rfcAddressArray))
6317 7492
 		{
6318
-			foreach((array)$rfcAddressArray as $addressData) {
7493
+			foreach((array)$rfcAddressArray as $addressData)
7494
+			{
6319 7495
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($addressData));
6320
-				if($addressData['MAILBOX_NAME'] == 'NIL') {
7496
+				if($addressData['MAILBOX_NAME'] == 'NIL')
7497
+				{
6321 7498
 					continue;
6322 7499
 				}
6323
-				if(strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
7500
+				if(strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients')
7501
+				{
6324 7502
 					continue;
6325 7503
 				}
6326 7504
 				if ($addressData['RFC822_EMAIL'])
@@ -6334,7 +7512,10 @@  discard block
 block discarded – undo
6334 7512
 				}
6335 7513
 				$addressObject = $addressObjectA[0];
6336 7514
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($addressObject));
6337
-				if (!$addressObject->valid) continue;
7515
+				if (!$addressObject->valid)
7516
+				{
7517
+					continue;
7518
+				}
6338 7519
 				//$mb =(string)$addressObject->mailbox;
6339 7520
 				//$h = (string)$addressObject->host;
6340 7521
 				//$p = (string)$addressObject->personal;
@@ -6351,7 +7532,10 @@  discard block
 block discarded – undo
6351 7532
 			// do not mess with strings, return them untouched /* ToDo: validate string as Address */
6352 7533
 			$rfcAddressArray = self::decode_header($rfcAddressArray,true);
6353 7534
 			$rfcAddressArray = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$rfcAddressArray);
6354
-			if (is_string($rfcAddressArray)) return $rfcAddressArray;
7535
+			if (is_string($rfcAddressArray))
7536
+			{
7537
+				return $rfcAddressArray;
7538
+			}
6355 7539
 		}
6356 7540
 		return $returnAddr;
6357 7541
 	}
@@ -6368,10 +7552,19 @@  discard block
 block discarded – undo
6368 7552
 	{
6369 7553
 		$mergeobj = new Contacts\Merge();
6370 7554
 
6371
-		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ?'text/plain':'text/html');
7555
+		if (empty($mimetype))
7556
+		{
7557
+			$mimetype = (strlen(strip_tags($content)) == strlen($content) ?'text/plain':'text/html');
7558
+		}
6372 7559
 		$rv = $mergeobj->merge_string($content,$ids,$err='',$mimetype, array(), self::$displayCharset);
6373
-		if (empty($rv) && !empty($content) && !empty($err)) $rv = $content;
6374
-		if (!empty($err) && !empty($content) && !empty($ids)) error_log(__METHOD__.' ('.__LINE__.') '.' Merge failed for Ids:'.array2string($ids).' ContentType:'.$mimetype.' Content:'.$content.' Reason:'.array2string($err));
7560
+		if (empty($rv) && !empty($content) && !empty($err))
7561
+		{
7562
+			$rv = $content;
7563
+		}
7564
+		if (!empty($err) && !empty($content) && !empty($ids))
7565
+		{
7566
+			error_log(__METHOD__.' ('.__LINE__.') '.' Merge failed for Ids:'.array2string($ids).' ContentType:'.$mimetype.' Content:'.$content.' Reason:'.array2string($err));
7567
+		}
6375 7568
 		return $rv;
6376 7569
 	}
6377 7570
 
@@ -6408,13 +7601,15 @@  discard block
 block discarded – undo
6408 7601
 			settype($bytes, 'integer');
6409 7602
 			$bytes /= 10;
6410 7603
 		}
6411
-		else
6412
-			settype($bytes, 'integer');
7604
+		else {
7605
+					settype($bytes, 'integer');
7606
+		}
6413 7607
 
6414 7608
 		return $bytes . ' ' . $type ;
6415 7609
 	}
6416 7610
 
6417
-	static function detect_qp(&$sting) {
7611
+	static function detect_qp(&$sting)
7612
+	{
6418 7613
 		$needle = '/(=[0-9][A-F])|(=[A-F][0-9])|(=[A-F][A-F])|(=[0-9][0-9])/';
6419 7614
 		return preg_match("$needle",$string);
6420 7615
 	}
@@ -6431,9 +7626,15 @@  discard block
 block discarded – undo
6431 7626
 	 */
6432 7627
 	static function logRunTimes($_starttime,$_endtime=null,$_message='',$_methodNline='')
6433 7628
 	{
6434
-		if (is_null($_endtime)) $_endtime = microtime(true);
7629
+		if (is_null($_endtime))
7630
+		{
7631
+			$_endtime = microtime(true);
7632
+		}
6435 7633
 		$usagetime = microtime(true) - $_starttime;
6436
-		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime,5).'(s) '.($_message?'Details:'.$_message:''));
7634
+		if (self::$debugTimes)
7635
+		{
7636
+			error_log($_methodNline.' took:'.number_format($usagetime,5).'(s) '.($_message?'Details:'.$_message:''));
7637
+		}
6437 7638
 	}
6438 7639
 
6439 7640
 	/**
@@ -6448,7 +7649,10 @@  discard block
 block discarded – undo
6448 7649
 	 */
6449 7650
 	static function checkFileBasics(&$_formData, $IDtoAddToFileName='', $reqMimeType='message/rfc822')
6450 7651
 	{
6451
-		if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
7652
+		if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'egw-data')
7653
+		{
7654
+			return $_formData['file'];
7655
+		}
6452 7656
 
6453 7657
 		//error_log(__METHOD__.__FILE__.array2string($_formData).' Id:'.$IDtoAddToFileName.' ReqMimeType:'.$reqMimeType);
6454 7658
 		$importfailed = $tmpFileName = false;
@@ -6497,8 +7701,15 @@  discard block
 block discarded – undo
6497 7701
 			{
6498 7702
 				$buff = explode('.',$_formData['name']);
6499 7703
 				$suffix = '';
6500
-				if (is_array($buff)) $suffix = array_pop($buff); // take the last extension to check with ext2mime
6501
-				if (!empty($suffix)) $sfxMimeType = MimeMagic::ext2mime($suffix);
7704
+				if (is_array($buff))
7705
+				{
7706
+					$suffix = array_pop($buff);
7707
+				}
7708
+				// take the last extension to check with ext2mime
7709
+				if (!empty($suffix))
7710
+				{
7711
+					$sfxMimeType = MimeMagic::ext2mime($suffix);
7712
+				}
6502 7713
 				if (!empty($suffix) && !empty($sfxMimeType) &&
6503 7714
 					(strlen(trim($_formData['type']))==0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6504 7715
 				{
@@ -6546,7 +7757,9 @@  discard block
 block discarded – undo
6546 7757
 			{
6547 7758
 				rename($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName);
6548 7759
 			}
6549
-		} else {
7760
+		}
7761
+		else
7762
+		{
6550 7763
 			//error_log("Import of message ".$_formData['file']." failes to meet basic restrictions");
6551 7764
 			$importfailed = true;
6552 7765
 			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.",$_formData['name']);
@@ -6592,21 +7805,32 @@  discard block
 block discarded – undo
6592 7805
 				if (substr($url, 0, 5) !== 'data:')
6593 7806
 				{
6594 7807
 					$filename = basename($url);
6595
-					if (($directory = dirname($url)) == '.') $directory = '';
7808
+					if (($directory = dirname($url)) == '.')
7809
+					{
7810
+						$directory = '';
7811
+					}
6596 7812
 					$ext = pathinfo($filename, PATHINFO_EXTENSION);
6597 7813
 					$mimeType  = MimeMagic::ext2mime($ext);
6598
-					if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
7814
+					if ( strlen($directory) > 1 && substr($directory,-1) != '/')
7815
+					{
7816
+$directory .= '/'; }
6599 7817
 					$myUrl = $directory.$filename;
6600
-					if ($myUrl[0]=='/') // local path -> we only allow path's that are available via http/https (or vfs)
7818
+					if ($myUrl[0]=='/')
7819
+					{
7820
+						// local path -> we only allow path's that are available via http/https (or vfs)
6601 7821
 					{
6602 7822
 						$basedir = ($_SERVER['HTTPS']?'https://':'http://'.$_SERVER['HTTP_HOST']);
6603 7823
 					}
7824
+					}
6604 7825
 					// use vfs instead of url containing webdav.php
6605 7826
 					// ToDo: we should test if the webdav url is of our own scope, as we cannot handle foreign
6606 7827
 					// webdav.php urls as vfs
6607
-					if (strpos($myUrl,'/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
7828
+					if (strpos($myUrl,'/webdav.php') !== false)
7829
+					{
7830
+						// we have a webdav link, so we build a vfs/sqlfs link of it.
6608 7831
 					{
6609 7832
 						Vfs::load_wrapper('vfs');
7833
+					}
6610 7834
 						list(,$myUrl) = explode('/webdav.php',$myUrl,2);
6611 7835
 						$basedir = 'vfs://default';
6612 7836
 						$needTempFile = false;
@@ -6635,8 +7859,13 @@  discard block
 block discarded – undo
6635 7859
 						}
6636 7860
 					}
6637 7861
 
6638
-					if ( strlen($basedir) > 1 && substr($basedir,-1) != '/' && $myUrl[0]!='/') { $basedir .= '/'; }
6639
-					if ($needTempFile && !$attachment && substr($myUrl,0,4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
7862
+					if ( strlen($basedir) > 1 && substr($basedir,-1) != '/' && $myUrl[0]!='/')
7863
+					{
7864
+$basedir .= '/'; }
7865
+					if ($needTempFile && !$attachment && substr($myUrl,0,4) !== "http")
7866
+					{
7867
+						$data = file_get_contents($basedir.urldecode($myUrl));
7868
+					}
6640 7869
 				}
6641 7870
 				if (substr($url,0,strlen('data:'))=='data:')
6642 7871
 				{
@@ -6737,7 +7966,10 @@  discard block
 block discarded – undo
6737 7966
 				$_folder = $this->getSentFolder();
6738 7967
 			}
6739 7968
 			$delimiter = $this->getHierarchyDelimiter();
6740
-			if($_folder=='INBOX'.$delimiter) $_folder='INBOX';
7969
+			if($_folder=='INBOX'.$delimiter)
7970
+			{
7971
+				$_folder='INBOX';
7972
+			}
6741 7973
 			if ($importfailed === false)
6742 7974
 			{
6743 7975
 				$Subject = $mailObject->getHeader('Subject');
@@ -6766,7 +7998,9 @@  discard block
 block discarded – undo
6766 7998
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Id To Merge:'.$val);
6767 7999
 					if (/*$GLOBALS['egw_info']['flags']['currentapp'] == 'addressbook' &&*/
6768 8000
 						count($SendAndMergeTocontacts) > 1 && $val &&
6769
-						(is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val))) // do the merge
8001
+						(is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val)))
8002
+					{
8003
+						// do the merge
6770 8004
 					{
6771 8005
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6772 8006
 
@@ -6775,6 +8009,7 @@  discard block
 block discarded – undo
6775 8009
 						{
6776 8010
 							//error_log('ID ' . $val . ' ' .$type . ': ' . $mailObject->getHeader(Mailer::$type2header[$type]) . ' -> ' .$bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset));
6777 8011
 							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset);
8012
+					}
6778 8013
 							$mailObject->addAddress($merged,'',$type);
6779 8014
 							if($type == 'to')
6780 8015
 							{
@@ -6806,9 +8041,15 @@  discard block
 block discarded – undo
6806 8041
 						$mailObject->clearCustomHeaders();
6807 8042
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6808 8043
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6809
-						if($text_body) $text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8044
+						if($text_body)
8045
+						{
8046
+							$text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8047
+						}
6810 8048
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6811
-						if($html_body) $html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8049
+						if($html_body)
8050
+						{
8051
+							$html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8052
+						}
6812 8053
 
6813 8054
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6814 8055
 						// set a higher timeout for big messages
@@ -6823,9 +8064,12 @@  discard block
 block discarded – undo
6823 8064
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($errorInfo));
6824 8065
 						}
6825 8066
 					}
6826
-					elseif (!$k)	// 1. entry, further entries will fail for apps other then addressbook
8067
+					elseif (!$k)
8068
+					{
8069
+						// 1. entry, further entries will fail for apps other then addressbook
6827 8070
 					{
6828 8071
 						$openAsDraft = true;
8072
+					}
6829 8073
 						$mailObject->removeHeader('Message-ID');
6830 8074
 						$mailObject->removeHeader('Date');
6831 8075
 						$mailObject->clearCustomHeaders();
@@ -6840,9 +8084,12 @@  discard block
 block discarded – undo
6840 8084
 
6841 8085
 						// No addresses from placeholders?  Treat it as just a contact ID
6842 8086
 						if (count($mailObject->getAddresses('to',true)) == 0 &&
6843
-							is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val)) // do the merge
8087
+							is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val))
8088
+						{
8089
+							// do the merge
6844 8090
 						{
6845 8091
 							$contact = $bo_merge->contacts->read($val);
8092
+						}
6846 8093
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($contact));
6847 8094
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
6848 8095
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
@@ -6853,9 +8100,15 @@  discard block
 block discarded – undo
6853 8100
 						}
6854 8101
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6855 8102
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6856
-						if (!empty($Body)) $text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8103
+						if (!empty($Body))
8104
+						{
8105
+							$text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8106
+						}
6857 8107
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6858
-						if (!empty($AltBody)) $html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8108
+						if (!empty($AltBody))
8109
+						{
8110
+							$html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
8111
+						}
6859 8112
 						$_folder = $this->getDraftFolder();
6860 8113
 					}
6861 8114
 					if ($sendOK || $openAsDraft)
@@ -6863,11 +8116,15 @@  discard block
 block discarded – undo
6863 8116
 						if ($this->folderExists($_folder,true))
6864 8117
 						{
6865 8118
 						    if($this->isSentFolder($_folder))
6866
-							{
8119
+						    {
6867 8120
 						        $flags = '\\Seen';
6868
-						    } elseif($this->isDraftFolder($_folder)) {
8121
+						    }
8122
+						    elseif($this->isDraftFolder($_folder))
8123
+						    {
6869 8124
 						        $flags = '\\Draft';
6870
-						    } else {
8125
+						    }
8126
+						    else
8127
+						    {
6871 8128
 						        $flags = '';
6872 8129
 						    }
6873 8130
 							$savefailed = false;
@@ -6901,7 +8158,10 @@  discard block
 block discarded – undo
6901 8158
 						}
6902 8159
 						else
6903 8160
 						{
6904
-							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
8161
+							if (!$openComposeWindow)
8162
+							{
8163
+								$processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
8164
+							}
6905 8165
 						}
6906 8166
 					}
6907 8167
 					if (!is_null($sendOK) && $sendOK===false && is_null($openComposeWindow))
@@ -6949,7 +8209,10 @@  discard block
 block discarded – undo
6949 8209
 				$tmpFileName = $GLOBALS['egw_info']['server']['temp_dir'].'/'.basename($tmpFileName);
6950 8210
 				break;
6951 8211
 		}
6952
-		if (!isset($message)) $message = fopen($tmpFileName, 'r');
8212
+		if (!isset($message))
8213
+		{
8214
+			$message = fopen($tmpFileName, 'r');
8215
+		}
6953 8216
 
6954 8217
 		if (!$message)
6955 8218
 		{
@@ -6987,7 +8250,10 @@  discard block
 block discarded – undo
6987 8250
 				(fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 8192));
6988 8251
 
6989 8252
 			$length = strpos($start, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
6990
-			if ($length===false) $length = strlen($start);
8253
+			if ($length===false)
8254
+			{
8255
+				$length = strlen($start);
8256
+			}
6991 8257
 			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0,$length));
6992 8258
 
6993 8259
 			foreach($headers->toArray(array('nowrap' => true)) as $header => $value)
@@ -7016,7 +8282,10 @@  discard block
 block discarded – undo
7016 8282
 		}
7017 8283
 		else
7018 8284
 		{
7019
-			if (($type = gettype($message)) == 'object') $type = get_class ($message);
8285
+			if (($type = gettype($message)) == 'object')
8286
+			{
8287
+				$type = get_class ($message);
8288
+			}
7020 8289
 			throw new Exception\WrongParameter('Wrong parameter type for message: '.$type);
7021 8290
 		}
7022 8291
 	}
@@ -7040,7 +8309,9 @@  discard block
 block discarded – undo
7040 8309
 			$matches = array();
7041 8310
 			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/",$addresses,$matches);
7042 8311
 			//error_log(__METHOD__.__LINE__.array2string($matches));
7043
-			foreach ($matches[0] as &$match) {$match = trim($match,', ');}
8312
+			foreach ($matches[0] as &$match)
8313
+			{
8314
+$match = trim($match,', ');}
7044 8315
 			$addresses = implode(',',$matches[0]);
7045 8316
 			//error_log(__METHOD__.__LINE__.array2string($addresses));
7046 8317
 			$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
@@ -7071,7 +8342,10 @@  discard block
 block discarded – undo
7071 8342
 			}
7072 8343
 			else
7073 8344
 			{
7074
-				if ($previousFailed && $remember) $adr->personal = $remember. ' ' . $adr->personal;
8345
+				if ($previousFailed && $remember)
8346
+				{
8347
+					$adr->personal = $remember. ' ' . $adr->personal;
8348
+				}
7075 8349
 				$remember = '';
7076 8350
 				$previousFailed=false;
7077 8351
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
@@ -7093,7 +8367,10 @@  discard block
 block discarded – undo
7093 8367
 	{
7094 8368
 		$acc = Mail\Account::read($this->profileID);
7095 8369
 		$identity = Mail\Account::read_identity($acc['ident_id'], true, null, $acc);
7096
-		if (self::$debug) error_log(__METHOD__.__LINE__.array2string($identity));
8370
+		if (self::$debug)
8371
+		{
8372
+			error_log(__METHOD__.__LINE__.array2string($identity));
8373
+		}
7097 8374
 		$headers = $this->getMessageHeader($uid, '', 'object', true, $_folder);
7098 8375
 
7099 8376
 		$mdn = new Horde_Mime_Mdn($headers);
Please login to merge, or discard this patch.
Spacing   +1150 added lines, -1151 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	 *
122 122
 	 * @array
123 123
 	 */
124
-	static $tidy_config = array('clean'=>false,'output-html'=>true,'join-classes'=>true,'join-styles'=>true,'show-body-only'=>"auto",'word-2000'=>true,'wrap'=>0);
124
+	static $tidy_config = array('clean'=>false, 'output-html'=>true, 'join-classes'=>true, 'join-styles'=>true, 'show-body-only'=>"auto", 'word-2000'=>true, 'wrap'=>0);
125 125
 
126 126
 	/**
127 127
 	 * static used to configure htmLawed, for use with emails
@@ -132,9 +132,9 @@  discard block
 block discarded – undo
132 132
 		'make_tag_strict' => 3, // 3 is a new own config value, to indicate that transformation is to be performed, but don't transform font as size transformation of numeric sizes to keywords alters the intended result too much
133 133
 		'keep_bad'=>2, //remove tags but keep element content (4 and 6 keep element content only if text (pcdata) is valid in parent element as per specs, this may lead to textloss if balance is switched on)
134 134
 		// we switch the balance off because of some broken html mails contents get removed like (td in table), and let browser deal with it
135
-		'balance'=>0,//turn off tag-balancing (config['balance']=>0). That will not introduce any security risk; only standards-compliant tag nesting check/filtering will be turned off (basic tag-balance will remain; i.e., there won't be any unclosed tag, etc., after filtering)
135
+		'balance'=>0, //turn off tag-balancing (config['balance']=>0). That will not introduce any security risk; only standards-compliant tag nesting check/filtering will be turned off (basic tag-balance will remain; i.e., there won't be any unclosed tag, etc., after filtering)
136 136
 		'direct_list_nest' => 1,
137
-		'allow_for_inline' => array('table','div','li','p'),//block elements allowed for nesting when only inline is allowed; Example span does not allow block elements as table; table is the only element tested so far
137
+		'allow_for_inline' => array('table', 'div', 'li', 'p'), //block elements allowed for nesting when only inline is allowed; Example span does not allow block elements as table; table is the only element tested so far
138 138
 		// tidy eats away even some wanted whitespace, so we switch it off;
139 139
 		// we used it for its compacting and beautifying capabilities, which resulted in better html for further processing
140 140
 		'tidy'=>0,
@@ -149,13 +149,13 @@  discard block
 block discarded – undo
149 149
 	 *
150 150
 	 * @array
151 151
 	 */
152
-	static $aclShortCuts = array('' => array('label'=>'none','title'=>'The user has no rights whatsoever.'),
153
-		'lrs'		=> array('label'=>'readable','title'=>'Allows a user to read the contents of the mailbox.'),
154
-		'lprs'		=> array('label'=>'post','title'=>'Allows a user to read the mailbox and post to it through the delivery system by sending mail to the submission address of the mailbox.'),
155
-		'ilprs'		=> array('label'=>'append','title'=>'Allows a user to read the mailbox and append messages to it, either via IMAP or through the delivery system.'),
156
-		'cdilprsw'	=> array('label'=>'write','title'=>'Allows a user to read the maibox, post to it, append messages to it, and delete messages or the mailbox itself. The only right not given is the right to change the ACL of the mailbox.'),
157
-		'acdilprsw'	=> array('label'=>'all','title'=>'The user has all possible rights on the mailbox. This is usually granted to users only on the mailboxes they own.'),
158
-		'custom'	=> array('label'=>'custom','title'=>'User defined combination of rights for the ACL'),
152
+	static $aclShortCuts = array('' => array('label'=>'none', 'title'=>'The user has no rights whatsoever.'),
153
+		'lrs'		=> array('label'=>'readable', 'title'=>'Allows a user to read the contents of the mailbox.'),
154
+		'lprs'		=> array('label'=>'post', 'title'=>'Allows a user to read the mailbox and post to it through the delivery system by sending mail to the submission address of the mailbox.'),
155
+		'ilprs'		=> array('label'=>'append', 'title'=>'Allows a user to read the mailbox and append messages to it, either via IMAP or through the delivery system.'),
156
+		'cdilprsw'	=> array('label'=>'write', 'title'=>'Allows a user to read the maibox, post to it, append messages to it, and delete messages or the mailbox itself. The only right not given is the right to change the ACL of the mailbox.'),
157
+		'acdilprsw'	=> array('label'=>'all', 'title'=>'The user has all possible rights on the mailbox. This is usually granted to users only on the mailboxes they own.'),
158
+		'custom'	=> array('label'=>'custom', 'title'=>'User defined combination of rights for the ACL'),
159 159
 	);
160 160
 
161 161
 	/**
@@ -197,13 +197,13 @@  discard block
 block discarded – undo
197 197
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
198 198
 	 * @return Mail
199 199
 	 */
200
-	public static function getInstance($_restoreSession=true, &$_profileID=0, $_validate=true, $_oldImapServerObject=false, $_reuseCache=null)
200
+	public static function getInstance($_restoreSession = true, &$_profileID = 0, $_validate = true, $_oldImapServerObject = false, $_reuseCache = null)
201 201
 	{
202 202
 		//$_restoreSession=false;
203 203
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
204 204
 		//error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID.'/'.Mail\Account::get_default_acc_id().' for user:'.$GLOBALS['egw_info']['user']['account_lid'].' called from:'.function_backtrace());
205 205
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_oldImapServerObject));
206
-		self::$profileDefunct = Cache::getCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),5*1);
206
+		self::$profileDefunct = Cache::getCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 5 * 1);
207 207
 		if (isset(self::$profileDefunct[$_profileID]) && strlen(self::$profileDefunct[$_profileID]))
208 208
 		{
209 209
 			throw new Exception(__METHOD__." failed to instanciate Mail for Profile #$_profileID Reason:".self::$profileDefunct[$_profileID]);
@@ -212,13 +212,13 @@  discard block
 block discarded – undo
212 212
 		{
213 213
 			if (!is_object(self::$instances[$_profileID]))
214 214
 			{
215
-				self::$instances[$_profileID] = new Mail('utf-8',false,$_profileID,false,$_reuseCache);
215
+				self::$instances[$_profileID] = new Mail('utf-8', false, $_profileID, false, $_reuseCache);
216 216
 			}
217 217
 			self::$instances[$_profileID]->icServer = $_oldImapServerObject;
218
-			self::$instances[$_profileID]->accountid= $_oldImapServerObject->ImapServerId;
219
-			self::$instances[$_profileID]->profileID= $_oldImapServerObject->ImapServerId;
218
+			self::$instances[$_profileID]->accountid = $_oldImapServerObject->ImapServerId;
219
+			self::$instances[$_profileID]->profileID = $_oldImapServerObject->ImapServerId;
220 220
 			self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
221
-			self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
221
+			self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
222 222
 			return self::$instances[$_profileID];
223 223
 		}
224 224
 		if ($_profileID == 0)
@@ -231,14 +231,14 @@  discard block
 block discarded – undo
231 231
 			{
232 232
 				$profileID = Mail\Account::get_default_acc_id();
233 233
 			}
234
-			if ($profileID!=$_profileID) $_restoreSession==false;
235
-			$_profileID=$profileID;
234
+			if ($profileID != $_profileID) $_restoreSession == false;
235
+			$_profileID = $profileID;
236 236
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' called with profileID==0 using '.$profileID.' instead->'.function_backtrace());
237 237
 		}
238 238
 		// no validation or restoreSession for old ImapServer Object, just fetch it and return it
239
-		if ($_oldImapServerObject===true)
239
+		if ($_oldImapServerObject === true)
240 240
 		{
241
-			return new Mail('utf-8',false,$_profileID,true,$_reuseCache);
241
+			return new Mail('utf-8', false, $_profileID, true, $_reuseCache);
242 242
 		}
243 243
 		if ($_profileID != 0 && $_validate)
244 244
 		{
@@ -258,9 +258,9 @@  discard block
 block discarded – undo
258 258
 			//Cache::setSession('mail','activeProfileID',$_profileID);
259 259
 		}
260 260
 		//error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID.' called from:'.function_backtrace());
261
-		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession===false))
261
+		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession === false))
262 262
 		{
263
-			self::$instances[$_profileID] = new Mail('utf-8',$_restoreSession,$_profileID,false,$_reuseCache);
263
+			self::$instances[$_profileID] = new Mail('utf-8', $_restoreSession, $_profileID, false, $_reuseCache);
264 264
 		}
265 265
 		else
266 266
 		{
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 				self::$instances[$_profileID]->ogServer = Mail\Account::read($_profileID)->smtpServer();
272 272
 				// TODO: merge mailprefs into userprefs, for easy treatment
273 273
 				self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
274
-				self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
274
+				self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
275 275
 			} catch (\Exception $e)
276 276
 			{
277 277
 				$newprofileID = Mail\Account::get_default_acc_id();
@@ -279,15 +279,15 @@  discard block
 block discarded – undo
279 279
 				error_log(__METHOD__.' ('.__LINE__.') '." Loading the Profile for ProfileID ".$_profileID.' failed for icServer; '.$e->getMessage().' Trigger new instance for Default-Profile '.$newprofileID.'. called from:'.function_backtrace());
280 280
 				if ($newprofileID)
281 281
 				{
282
-					self::$instances[$newprofileID] = new Mail('utf-8',false,$newprofileID,false,$_reuseCache);
282
+					self::$instances[$newprofileID] = new Mail('utf-8', false, $newprofileID, false, $_reuseCache);
283 283
 					$_profileID = $newprofileID;
284 284
 				}
285 285
 				else
286 286
 				{
287
-					throw new Exception(__METHOD__." failed to load the Profile for ProfileID for $_profileID with error:".$e->getMessage().($e->details?', '.$e->details:''));
287
+					throw new Exception(__METHOD__." failed to load the Profile for ProfileID for $_profileID with error:".$e->getMessage().($e->details ? ', '.$e->details : ''));
288 288
 				}
289 289
 			}
290
-			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate );
290
+			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate);
291 291
 		}
292 292
 		self::$instances[$_profileID]->profileID = $_profileID;
293 293
 		if (!isset(self::$instances[$_profileID]->idna2)) self::$instances[$_profileID]->idna2 = new Horde_Idna;
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 	 * @param boolean $_testConnection = 0
304 304
 	 * @return mixed $_profileID or false on failed ConnectionTest
305 305
 	 */
306
-	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID=0, $_testConnection=true)
306
+	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID = 0, $_testConnection = true)
307 307
 	{
308 308
 		if (isset($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']) && !empty($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']))
309 309
 		{
@@ -324,12 +324,12 @@  discard block
 block discarded – undo
324 324
 		}
325 325
 		if ($oldProfileID != $_profileID)
326 326
 		{
327
-			if ($oldProfileID && $_profileID==0) $_profileID = $oldProfileID;
328
-			$GLOBALS['egw']->preferences->add('mail','ActiveProfileID',$_profileID,'user');
327
+			if ($oldProfileID && $_profileID == 0) $_profileID = $oldProfileID;
328
+			$GLOBALS['egw']->preferences->add('mail', 'ActiveProfileID', $_profileID, 'user');
329 329
 			// save prefs
330 330
 			$GLOBALS['egw']->preferences->save_repository(true);
331 331
 			$GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $_profileID;
332
-			Cache::setSession('mail','activeProfileID',$_profileID);
332
+			Cache::setSession('mail', 'activeProfileID', $_profileID);
333 333
 		}
334 334
 		return $_profileID;
335 335
 	}
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 	 * @param int $_acc_id = 0
345 345
 	 * @return int validated acc_id -> either acc_id given, or first valid one
346 346
 	 */
347
-	public static function validateProfileID($_acc_id=0)
347
+	public static function validateProfileID($_acc_id = 0)
348 348
 	{
349 349
 		if ($_acc_id)
350 350
 		{
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 		}
364 364
 		// no account specified or specified account not found or not valid
365 365
 		// --> search existing account for first valid one and return that
366
-		foreach(Mail\Account::search($only_current_user=true, 'acc_imap_host') as $acc_id => $imap_host)
366
+		foreach (Mail\Account::search($only_current_user = true, 'acc_imap_host') as $acc_id => $imap_host)
367 367
 		{
368 368
 			if (!empty($imap_host) && ($account = Mail\Account::read($acc_id)) && $account->is_imap())
369 369
 			{
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 	 * @param boolean $_oldImapServerObject = false
386 386
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
387 387
 	 */
388
-	private function __construct($_displayCharset='utf-8',$_restoreSession=true, $_profileID=0, $_oldImapServerObject=false, $_reuseCache=null)
388
+	private function __construct($_displayCharset = 'utf-8', $_restoreSession = true, $_profileID = 0, $_oldImapServerObject = false, $_reuseCache = null)
389 389
 	{
390 390
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
391 391
 		if (!empty($_displayCharset)) self::$displayCharset = $_displayCharset;
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 			$firstMessage = $this->sessionData['previewMessage'];
406 406
 			$this->sessionData = array();
407 407
 		}
408
-		if (!$_reuseCache) $this->forcePrefReload($_profileID,!$_reuseCache);
408
+		if (!$_reuseCache) $this->forcePrefReload($_profileID, !$_reuseCache);
409 409
 		try
410 410
 		{
411 411
 			$this->profileID = self::validateProfileID($_profileID);
@@ -419,11 +419,11 @@  discard block
 block discarded – undo
419 419
 			throw new Exception(__METHOD__." failed to instanciate Mail for $_profileID / ".$this->profileID." with error:".$e->getMessage());
420 420
 		}
421 421
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($acc->imapServer()));
422
-		$this->icServer = ($_oldImapServerObject?$acc->oldImapServer():$acc->imapServer());
422
+		$this->icServer = ($_oldImapServerObject ? $acc->oldImapServer() : $acc->imapServer());
423 423
 		$this->ogServer = $acc->smtpServer();
424 424
 		// TODO: merge mailprefs into userprefs, for easy treatment
425 425
 		$this->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
426
-		$this->htmlOptions  = $this->mailPreferences['htmlOptions'];
426
+		$this->htmlOptions = $this->mailPreferences['htmlOptions'];
427 427
 		if (isset($this->icServer->ImapServerId) && !empty($this->icServer->ImapServerId))
428 428
 		{
429 429
 			$_profileID = $this->profileID = $GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $this->icServer->ImapServerId;
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 	public static function &forceEAProfileLoad($_profile_id)
442 442
 	{
443 443
 		self::unsetCachedObjects($_profile_id);
444
-		$mail = self::getInstance(false, $_profile_id,false);
444
+		$mail = self::getInstance(false, $_profile_id, false);
445 445
 		//_debug_array( $_profile_id);
446 446
 		$mail->icServer = Mail\Account::read($_profile_id)->imapServer();
447 447
 		$mail->ogServer = Mail\Account::read($_profile_id)->smtpServer();
@@ -453,11 +453,11 @@  discard block
 block discarded – undo
453 453
 	 * @param int $_profile_id
454 454
 	 * @param boolean $_resetFolderObjects
455 455
 	 */
456
-	public static function forcePrefReload($_profile_id=null,$_resetFolderObjects=true)
456
+	public static function forcePrefReload($_profile_id = null, $_resetFolderObjects = true)
457 457
 	{
458 458
 		// unset the mail_preferences session object, to force the reload/rebuild
459
-		Cache::setSession('mail','mail_preferences',serialize(array()));
460
-		Cache::setSession('emailadmin','session_data',serialize(array()));
459
+		Cache::setSession('mail', 'mail_preferences', serialize(array()));
460
+		Cache::setSession('emailadmin', 'session_data', serialize(array()));
461 461
 		if ($_resetFolderObjects) self::resetFolderObjectCache($_profile_id);
462 462
 	}
463 463
 
@@ -466,8 +466,8 @@  discard block
 block discarded – undo
466 466
 	 */
467 467
 	function restoreSessionData()
468 468
 	{
469
-		$this->sessionData = array();//Cache::getCache(Cache::SESSION,'mail','session_data',$callback=null,$callback_params=array(),$expiration=60*60*1);
470
-		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
469
+		$this->sessionData = array(); //Cache::getCache(Cache::SESSION,'mail','session_data',$callback=null,$callback_params=array(),$expiration=60*60*1);
470
+		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
471 471
 		if (!empty(self::$activeFolderCache[$this->profileID])) $this->sessionData['mailbox'] = self::$activeFolderCache[$this->profileID];
472 472
 	}
473 473
 
@@ -477,10 +477,10 @@  discard block
 block discarded – undo
477 477
 	function saveSessionData()
478 478
 	{
479 479
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($this->sessionData)));
480
-		if (!empty($this->sessionData['mailbox'])) self::$activeFolderCache[$this->profileID]=$this->sessionData['mailbox'];
480
+		if (!empty($this->sessionData['mailbox'])) self::$activeFolderCache[$this->profileID] = $this->sessionData['mailbox'];
481 481
 		if (isset(self::$activeFolderCache) && is_array(self::$activeFolderCache))
482 482
 		{
483
-			Cache::setCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),self::$activeFolderCache, 60*60*10);
483
+			Cache::setCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), self::$activeFolderCache, 60 * 60 * 10);
484 484
 		}
485 485
 	}
486 486
 
@@ -496,40 +496,40 @@  discard block
 block discarded – undo
496 496
 	 * @param int $_profileID = null default profile of user as returned by getUserDefaultProfileID
497 497
 	 * @return void
498 498
 	 */
499
-	static function unsetCachedObjects($_profileID=null)
499
+	static function unsetCachedObjects($_profileID = null)
500 500
 	{
501 501
 		if (is_null($_profileID)) $_profileID = Mail\Account::get_default_acc_id();
502 502
 		if (is_array($_profileID) && $_profileID['account_id']) $account_id = $_profileID['account_id'];
503 503
 		//error_log(__METHOD__.__LINE__.' called with ProfileID:'.array2string($_profileID).' from '.function_backtrace());
504
-		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID,'tracker_')===false)))
504
+		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID, 'tracker_') === false)))
505 505
 		{
506 506
 			self::resetConnectionErrorCache($_profileID);
507
-			$rawHeadersCache = Cache::getCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
507
+			$rawHeadersCache = Cache::getCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
508 508
 			if (isset($rawHeadersCache[$_profileID]))
509 509
 			{
510 510
 				unset($rawHeadersCache[$_profileID]);
511
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$rawHeadersCache, $expiration=60*60*1);
511
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $rawHeadersCache, $expiration = 60 * 60 * 1);
512 512
 			}
513
-			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*5);
513
+			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 5);
514 514
 			if (isset($HierarchyDelimiterCache[$_profileID]))
515 515
 			{
516 516
 				unset($HierarchyDelimiterCache[$_profileID]);
517
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$HierarchyDelimiterCache, $expiration=60*60*24*5);
517
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $HierarchyDelimiterCache, $expiration = 60 * 60 * 24 * 5);
518 518
 			}
519 519
 			//reset folderObject cache, to trigger reload
520 520
 			self::resetFolderObjectCache($_profileID);
521 521
 			//reset counter of deleted messages per folder
522
-			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
522
+			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
523 523
 			if (isset($eMailListContainsDeletedMessages[$_profileID]))
524 524
 			{
525 525
 				unset($eMailListContainsDeletedMessages[$_profileID]);
526
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$eMailListContainsDeletedMessages, $expiration=60*60*1);
526
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $eMailListContainsDeletedMessages, $expiration = 60 * 60 * 1);
527 527
 			}
528
-			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*1);
528
+			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 1);
529 529
 			if (isset($vacationCached[$_profileID]))
530 530
 			{
531 531
 				unset($vacationCached[$_profileID]);
532
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),$vacationCached, $expiration=60*60*24*1);
532
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $vacationCached, $expiration = 60 * 60 * 24 * 1);
533 533
 			}
534 534
 
535 535
 			if (isset(self::$instances[$_profileID])) unset(self::$instances[$_profileID]);
@@ -537,17 +537,17 @@  discard block
 block discarded – undo
537 537
 		if (is_array($_profileID) && $_profileID['location'] == 'clear_cache')
538 538
 		{
539 539
 			// called via hook
540
-			foreach($GLOBALS['egw']->accounts->search(array('type' => 'accounts','order' => 'account_lid')) as $account)
540
+			foreach ($GLOBALS['egw']->accounts->search(array('type' => 'accounts', 'order' => 'account_lid')) as $account)
541 541
 			{
542 542
 				//error_log(__METHOD__.__LINE__.array2string($account));
543 543
 				$account_id = $account['account_id'];
544 544
 				$_profileID = null;
545
-				self::resetConnectionErrorCache($_profileID,$account_id);
546
-				self::resetFolderObjectCache($_profileID,$account_id);
547
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),array(), 60*60*1);
548
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),array(), 60*60*24*5);
549
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),array(), 60*60*1);
550
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),array(), 60*60*24*1);
545
+				self::resetConnectionErrorCache($_profileID, $account_id);
546
+				self::resetFolderObjectCache($_profileID, $account_id);
547
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), array(), 60 * 60 * 1);
548
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), array(), 60 * 60 * 24 * 5);
549
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), array(), 60 * 60 * 1);
550
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), array(), 60 * 60 * 24 * 1);
551 551
 			}
552 552
 		}
553 553
 	}
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 	 * @param int $_ImapServerId the profileID to look for
559 559
 	 * @param int $account_id the egw account to look for
560 560
 	 */
561
-	static function resetConnectionErrorCache($_ImapServerId=null,$account_id=null)
561
+	static function resetConnectionErrorCache($_ImapServerId = null, $account_id = null)
562 562
 	{
563 563
 		//error_log(__METHOD__.' ('.__LINE__.') '.' for Profile:'.array2string($_ImapServerId) .' for user:'.trim($account_id));
564 564
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
@@ -576,19 +576,19 @@  discard block
 block discarded – undo
576 576
 		}
577 577
 		else
578 578
 		{
579
-			$isConError = Cache::getCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id));
579
+			$isConError = Cache::getCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id));
580 580
 			if (isset($isConError[$_ImapServerId]))
581 581
 			{
582 582
 				unset($isConError[$_ImapServerId]);
583 583
 			}
584
-			$waitOnFailure = Cache::getCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),null,array(),60*60*2);
584
+			$waitOnFailure = Cache::getCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), null, array(), 60 * 60 * 2);
585 585
 			if (isset($waitOnFailure[$_ImapServerId]))
586 586
 			{
587 587
 				unset($waitOnFailure[$_ImapServerId]);
588 588
 			}
589 589
 		}
590
-		Cache::setCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id),$isConError,60*15);
591
-		Cache::setCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),$waitOnFailure,60*60*2);
590
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id), $isConError, 60 * 15);
591
+		Cache::setCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), $waitOnFailure, 60 * 60 * 2);
592 592
 	}
593 593
 
594 594
 	/**
@@ -597,13 +597,13 @@  discard block
 block discarded – undo
597 597
 	 * @param int $_ImapServerId the profileID to look for
598 598
 	 * @param int $account_id the egw account to look for
599 599
 	 */
600
-	static function resetFolderObjectCache($_ImapServerId=null,$account_id=null)
600
+	static function resetFolderObjectCache($_ImapServerId = null, $account_id = null)
601 601
 	{
602 602
 		//error_log(__METHOD__.' ('.__LINE__.') '.' called for Profile:'.array2string($_ImapServerId).'->'.function_backtrace());
603 603
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
604 604
 		// on [location] => verify_settings we coud either use [prefs] => Array([ActiveProfileID] => 9, .. as $_ImapServerId
605 605
 		// or treat it as not given. we try that path
606
-		if (is_null($_ImapServerId)||is_array($_ImapServerId))
606
+		if (is_null($_ImapServerId) || is_array($_ImapServerId))
607 607
 		{
608 608
 			$folders2return = array();
609 609
 			$folderInfo = array();
@@ -612,12 +612,12 @@  discard block
 block discarded – undo
612 612
 		}
613 613
 		else
614 614
 		{
615
-			$folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),null,array(),60*60*1);
615
+			$folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), null, array(), 60 * 60 * 1);
616 616
 			if (!empty($folders2return) && isset($folders2return[$_ImapServerId]))
617 617
 			{
618 618
 				unset($folders2return[$_ImapServerId]);
619 619
 			}
620
-			$folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),null,array(),60*60*5);
620
+			$folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), null, array(), 60 * 60 * 5);
621 621
 			if (!empty($folderInfo) && isset($folderInfo[$_ImapServerId]))
622 622
 			{
623 623
 				unset($folderInfo[$_ImapServerId]);
@@ -629,23 +629,23 @@  discard block
 block discarded – undo
629 629
 				unset($lastFolderUsedForMove[$_ImapServerId]);
630 630
 			}
631 631
 			*/
632
-			$folderBasicInfo = Cache::getCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),null,array(),60*60*1);
632
+			$folderBasicInfo = Cache::getCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), null, array(), 60 * 60 * 1);
633 633
 			if (!empty($folderBasicInfo) && isset($folderBasicInfo[$_ImapServerId]))
634 634
 			{
635 635
 				unset($folderBasicInfo[$_ImapServerId]);
636 636
 			}
637
-			$_specialUseFolders = Cache::getCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),null,array(),60*60*12);
637
+			$_specialUseFolders = Cache::getCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), null, array(), 60 * 60 * 12);
638 638
 			if (!empty($_specialUseFolders) && isset($_specialUseFolders[$_ImapServerId]))
639 639
 			{
640 640
 				unset($_specialUseFolders[$_ImapServerId]);
641
-				self::$specialUseFolders=null;
641
+				self::$specialUseFolders = null;
642 642
 			}
643 643
 		}
644
-		Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),$folders2return, 60*60*1);
645
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),$folderInfo,60*60*5);
644
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), $folders2return, 60 * 60 * 1);
645
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), $folderInfo, 60 * 60 * 5);
646 646
 		//Cache::setCache(Cache::INSTANCE,'email','lastFolderUsedForMove'.trim($account_id),$lastFolderUsedForMove,$expiration=60*60*1);
647
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),$folderBasicInfo,60*60*1);
648
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),$_specialUseFolders,60*60*12);
647
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), $folderBasicInfo, 60 * 60 * 1);
648
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), $_specialUseFolders, 60 * 60 * 12);
649 649
 	}
650 650
 
651 651
 	/**
@@ -666,15 +666,15 @@  discard block
 block discarded – undo
666 666
 	 * @param string $_profileID the ID of the mailaccount to check for identities, if null current mail-account is used
667 667
 	 * @return array - array(email=>realname)
668 668
 	 */
669
-	function getUserEMailAddresses($_profileID=null)
669
+	function getUserEMailAddresses($_profileID = null)
670 670
 	{
671
-		$acc = Mail\Account::read((!empty($_profileID)?$_profileID:$this->profileID));
671
+		$acc = Mail\Account::read((!empty($_profileID) ? $_profileID : $this->profileID));
672 672
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($acc));
673 673
 		$identities = Mail\Account::identities($acc);
674 674
 
675 675
 		$userEMailAdresses = array($acc['ident_email']=>$acc['ident_realname']);
676 676
 
677
-		foreach($identities as $ik => $ident) {
677
+		foreach ($identities as $ik => $ident) {
678 678
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
679 679
 			$identity = Mail\Account::read_identity($ik);
680 680
 			if (!empty($identity['ident_email']) && !isset($userEMailAdresses[$identity['ident_email']])) $userEMailAdresses[$identity['ident_email']] = $identity['ident_realname'];
@@ -689,19 +689,19 @@  discard block
 block discarded – undo
689 689
 	 * @param boolean $resolve_placeholders wether or not resolve possible placeholders in identities
690 690
 	 * @return array - array(email=>realname)
691 691
 	 */
692
-	static function getAllIdentities($_accountToSearch=null,$resolve_placeholders=false)
692
+	static function getAllIdentities($_accountToSearch = null, $resolve_placeholders = false)
693 693
 	{
694 694
 		$userEMailAdresses = array();
695
-		foreach(Mail\Account::search($only_current_user=($_accountToSearch?$_accountToSearch:true), $just_name=true) as $acc_id => $identity_name)
695
+		foreach (Mail\Account::search($only_current_user = ($_accountToSearch ? $_accountToSearch : true), $just_name = true) as $acc_id => $identity_name)
696 696
 		{
697
-			$acc = Mail\Account::read($acc_id,($_accountToSearch?$_accountToSearch:null));
698
-			if (!$resolve_placeholders) $userEMailAdresses[$acc['ident_id']] = array('acc_id'=>$acc_id,'ident_id'=>$acc['ident_id'],'ident_email'=>$acc['ident_email'],'ident_org'=>$acc['ident_org'],'ident_realname'=>$acc['ident_realname'],'ident_signature'=>$acc['ident_signature'],'ident_name'=>$acc['ident_name']);
697
+			$acc = Mail\Account::read($acc_id, ($_accountToSearch ? $_accountToSearch : null));
698
+			if (!$resolve_placeholders) $userEMailAdresses[$acc['ident_id']] = array('acc_id'=>$acc_id, 'ident_id'=>$acc['ident_id'], 'ident_email'=>$acc['ident_email'], 'ident_org'=>$acc['ident_org'], 'ident_realname'=>$acc['ident_realname'], 'ident_signature'=>$acc['ident_signature'], 'ident_name'=>$acc['ident_name']);
699 699
 
700
-			foreach(Mail\Account::identities($acc) as $ik => $ident) {
700
+			foreach (Mail\Account::identities($acc) as $ik => $ident) {
701 701
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
702
-				$identity = Mail\Account::read_identity($ik,$resolve_placeholders);
702
+				$identity = Mail\Account::read_identity($ik, $resolve_placeholders);
703 703
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
704
-				if (!isset($userEMailAdresses[$identity['ident_id']])) $userEMailAdresses[$identity['ident_id']] = array('acc_id'=>$acc_id,'ident_id'=>$identity['ident_id'],'ident_email'=>$identity['ident_email'],'ident_org'=>$identity['ident_org'],'ident_realname'=>$identity['ident_realname'],'ident_signature'=>$identity['ident_signature'],'ident_name'=>$identity['ident_name']);
704
+				if (!isset($userEMailAdresses[$identity['ident_id']])) $userEMailAdresses[$identity['ident_id']] = array('acc_id'=>$acc_id, 'ident_id'=>$identity['ident_id'], 'ident_email'=>$identity['ident_email'], 'ident_org'=>$identity['ident_org'], 'ident_realname'=>$identity['ident_realname'], 'ident_signature'=>$identity['ident_signature'], 'ident_name'=>$identity['ident_name']);
705 705
 			}
706 706
 		}
707 707
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($userEMailAdresses));
@@ -721,9 +721,9 @@  discard block
 block discarded – undo
721 721
 			$account = Mail\Account::read($account);
722 722
 		}
723 723
 		$userEMailAdresses = array();
724
-		foreach(Mail\Account::identities($account, true, 'params') as $ik => $ident) {
724
+		foreach (Mail\Account::identities($account, true, 'params') as $ik => $ident) {
725 725
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
726
-			$identity = Mail\Account::read_identity($ik,true,null,$account);
726
+			$identity = Mail\Account::read_identity($ik, true, null, $account);
727 727
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
728 728
 			// standardIdentity has ident_id==acc_id (as it is done within account->identities)
729 729
 			if (empty($identity['ident_id'])) $identity['ident_id'] = $identity['acc_id'];
@@ -750,9 +750,9 @@  discard block
 block discarded – undo
750 750
 	function getDefaultIdentity()
751 751
 	{
752 752
 		// retrieve the signature accociated with the identity
753
-		$id = $this->getIdentitiesWithAccounts($_accountData=array());
754
-		foreach(Mail\Account::identities($_accountData[$this->profileID] ?
755
-			$this->profileID : $_accountData[$id],false,'ident_id') as $accountData)
753
+		$id = $this->getIdentitiesWithAccounts($_accountData = array());
754
+		foreach (Mail\Account::identities($_accountData[$this->profileID] ?
755
+			$this->profileID : $_accountData[$id], false, 'ident_id') as $accountData)
756 756
 		{
757 757
 			return $accountData;
758 758
 		}
@@ -768,13 +768,13 @@  discard block
 block discarded – undo
768 768
 	{
769 769
 		// account select box
770 770
 		$selectedID = $this->profileID;
771
-		$allAccountData = Mail\Account::search($only_current_user=true, false, null);
771
+		$allAccountData = Mail\Account::search($only_current_user = true, false, null);
772 772
 		if ($allAccountData) {
773
-			$rememberFirst=$selectedFound=null;
773
+			$rememberFirst = $selectedFound = null;
774 774
 			foreach ($allAccountData as $tmpkey => $icServers)
775 775
 			{
776 776
 				if (is_null($rememberFirst)) $rememberFirst = $tmpkey;
777
-				if ($tmpkey == $selectedID) $selectedFound=true;
777
+				if ($tmpkey == $selectedID) $selectedFound = true;
778 778
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($icServers->acc_imap_host));
779 779
 				$host = $icServers->acc_imap_host;
780 780
 				if (empty($host)) continue;
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($identities[$icServers->acc_id]));
783 783
 			}
784 784
 		}
785
-		return ($selectedFound?$selectedID:$rememberFirst);
785
+		return ($selectedFound ? $selectedID : $rememberFirst);
786 786
 	}
787 787
 
788 788
 	/**
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
 	 * @var boolean $fullString full or false=NamePart only is returned
793 793
 	 * @return string - constructed of identity object data as defined in mailConfig
794 794
 	 */
795
-	static function generateIdentityString($identity, $fullString=true)
795
+	static function generateIdentityString($identity, $fullString = true)
796 796
 	{
797 797
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($identity));
798 798
 		//if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
@@ -803,16 +803,16 @@  discard block
 block discarded – undo
803 803
 		{
804 804
 			case 'email';
805 805
 				//$retData = str_replace('@',' ',$identity->emailAddress).($fullString===true?' <'.$identity->emailAddress.'>':'');
806
-				$retData = $identity['ident_email'].($fullString===true?' <'.$identity['ident_email'].'>':'');
806
+				$retData = $identity['ident_email'].($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
807 807
 				break;
808 808
 			case 'nameNemail';
809
-				$retData = (!empty($identity['ident_realname'])?$identity['ident_realname']:substr_replace($identity['ident_email'],'',strpos($identity['ident_email'],'@'))).($fullString===true?' <'.$identity['ident_email'].'>':'');
809
+				$retData = (!empty($identity['ident_realname']) ? $identity['ident_realname'] : substr_replace($identity['ident_email'], '', strpos($identity['ident_email'], '@'))).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
810 810
 				break;
811 811
 			case 'orgNemail';
812
-				$retData = (!empty($identity['ident_org'])?$identity['ident_org']:substr_replace($identity['ident_email'],'',0,strpos($identity['ident_email'],'@')+1)).($fullString===true?' <'.$identity['ident_email'].'>':'');
812
+				$retData = (!empty($identity['ident_org']) ? $identity['ident_org'] : substr_replace($identity['ident_email'], '', 0, strpos($identity['ident_email'], '@') + 1)).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
813 813
 				break;
814 814
 			default:
815
-				$retData = $identity['ident_realname'].(!empty($identity['ident_org'])?' '.$identity['ident_org']:'').($fullString===true?' <'.$identity['ident_email'].'>':'');
815
+				$retData = $identity['ident_realname'].(!empty($identity['ident_org']) ? ' '.$identity['ident_org'] : '').($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
816 816
 		}
817 817
 		return $retData;
818 818
 	}
@@ -837,7 +837,7 @@  discard block
 block discarded – undo
837 837
 	 */
838 838
 	function reopen($_foldername)
839 839
 	{
840
-		if (self::$debugTimes) $starttime = microtime (true);
840
+		if (self::$debugTimes) $starttime = microtime(true);
841 841
 
842 842
 		//error_log(__METHOD__.' ('.__LINE__.') '."('$_foldername') ".function_backtrace());
843 843
 		// TODO: trying to reduce traffic to the IMAP Server here, introduces problems with fetching the bodies of
@@ -852,7 +852,7 @@  discard block
 block discarded – undo
852 852
 			}
853 853
 			$folderOpened = $_foldername;
854 854
 		//}
855
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'Folder:'.$_foldername,__METHOD__.' ('.__LINE__.') ');
855
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'Folder:'.$_foldername, __METHOD__.' ('.__LINE__.') ');
856 856
 	}
857 857
 
858 858
 
@@ -863,15 +863,15 @@  discard block
 block discarded – undo
863 863
 	 * @throws Horde_Imap_Client_Exception on connection error or authentication failure
864 864
 	 * @throws InvalidArgumentException on missing credentials
865 865
 	 */
866
-	function openConnection($_icServerID=0)
866
+	function openConnection($_icServerID = 0)
867 867
 	{
868 868
 		//error_log( "-------------------------->open connection ".function_backtrace());
869 869
 		//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.array2string($this->icServer));
870
-		if (self::$debugTimes) $starttime = microtime (true);
871
-		$mailbox=null;
870
+		if (self::$debugTimes) $starttime = microtime(true);
871
+		$mailbox = null;
872 872
 		try
873 873
 		{
874
-			if(isset($this->sessionData['mailbox'])&&$this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
874
+			if (isset($this->sessionData['mailbox']) && $this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
875 875
 			if (empty($mailbox)) $mailbox = $this->icServer->getCurrentMailbox();
876 876
 /*
877 877
 			if (isset(Mail\Imap::$supports_keywords[$_icServerID]))
@@ -898,7 +898,7 @@  discard block
 block discarded – undo
898 898
 			error_log(__METHOD__.' ('.__LINE__.') '."->open connection for Server with profileID:".$_icServerID." trying to examine ($mailbox) failed!".$e->getMessage());
899 899
 			throw new Exception(__METHOD__." failed to ".__METHOD__." on Profile to $_icServerID while trying to examine $mailbox:".$e->getMessage());
900 900
 		}
901
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'ProfileID:'.$_icServerID,__METHOD__.' ('.__LINE__.') ');
901
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'ProfileID:'.$_icServerID, __METHOD__.' ('.__LINE__.') ');
902 902
 	}
903 903
 
904 904
 	/**
@@ -919,7 +919,7 @@  discard block
 block discarded – undo
919 919
 		try
920 920
 		{
921 921
 			$this->icServer->getCurrentMailbox();
922
-			if(!$this->icServer->hasCapability('QUOTA')) {
922
+			if (!$this->icServer->hasCapability('QUOTA')) {
923 923
 				$quota = false;
924 924
 				return false;
925 925
 			}
@@ -929,15 +929,15 @@  discard block
 block discarded – undo
929 929
 		{
930 930
 			//error_log(__METHOD__.array2string($e));
931 931
 			//error_log(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
932
-			if ($e->getCode()==102)
932
+			if ($e->getCode() == 102)
933 933
 			{
934
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
935
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
936
-				throw new Exception(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
934
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
935
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
936
+				throw new Exception(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : ''));
937 937
 			}
938 938
 		}
939 939
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($quota));
940
-		if(is_array($quota)) {
940
+		if (is_array($quota)) {
941 941
 			$quota = array(
942 942
 				'usage'	=> $quota['USED'],
943 943
 				'limit'	=> $quota['QMAX'],
@@ -955,10 +955,10 @@  discard block
 block discarded – undo
955 955
 	 *
956 956
 	 * @return int - timeout (either set or default 20/10)
957 957
 	 */
958
-	static function getTimeOut($_use='IMAP')
958
+	static function getTimeOut($_use = 'IMAP')
959 959
 	{
960 960
 		$timeout = $GLOBALS['egw_info']['user']['preferences']['mail']['connectionTimeout'];
961
-		if (empty($timeout)) $timeout = ($_use=='SIEVE'?10:20); // this is the default value
961
+		if (empty($timeout)) $timeout = ($_use == 'SIEVE' ? 10 : 20); // this is the default value
962 962
 		return $timeout;
963 963
 	}
964 964
 
@@ -979,18 +979,18 @@  discard block
 block discarded – undo
979 979
 		if (is_null($nameSpace)) $nameSpace = $this->icServer->getNameSpaceArray();
980 980
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($nameSpace));
981 981
 		if (is_array($nameSpace)) {
982
-			foreach($nameSpace as $type => $singleNameSpaceArray)
982
+			foreach ($nameSpace as $type => $singleNameSpaceArray)
983 983
 			{
984 984
 				foreach ($singleNameSpaceArray as $singleNameSpace)
985 985
 				{
986 986
 					$_foldersNameSpace = array();
987
-					if($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail')||$this->folderExists('INBOX')))
987
+					if ($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail') || $this->folderExists('INBOX')))
988 988
 					{
989 989
 						$_foldersNameSpace['prefix_present'] = 'forced';
990 990
 						// uw-imap server with mailbox prefix or dovecot maybe
991
-						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail')?'Mail':(!empty($singleNameSpace['name'])?$singleNameSpace['name']:''));
991
+						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail') ? 'Mail' : (!empty($singleNameSpace['name']) ? $singleNameSpace['name'] : ''));
992 992
 					}
993
-					elseif($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
993
+					elseif ($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
994 994
 					{
995 995
 						$_foldersNameSpace['prefix_present'] = 'forced';
996 996
 						// uw-imap server with mailbox prefix or dovecot maybe
@@ -999,9 +999,9 @@  discard block
 block discarded – undo
999 999
 						$_foldersNameSpace['prefix_present'] = !empty($singleNameSpace['name']);
1000 1000
 						$_foldersNameSpace['prefix'] = $singleNameSpace['name'];
1001 1001
 					}
1002
-					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter']?$singleNameSpace['delimiter']:$delimiter);
1002
+					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter'] ? $singleNameSpace['delimiter'] : $delimiter);
1003 1003
 					$_foldersNameSpace['type'] = $type;
1004
-					$foldersNameSpace[] =$_foldersNameSpace;
1004
+					$foldersNameSpace[] = $_foldersNameSpace;
1005 1005
 				}
1006 1006
 				//echo "############## $type->".print_r($foldersNameSpace[$type],true)." ###################<br>";
1007 1007
 			}
@@ -1019,10 +1019,10 @@  discard block
 block discarded – undo
1019 1019
 	 */
1020 1020
 	function getFolderPrefixFromNamespace($nameSpace, $folderName)
1021 1021
 	{
1022
-		foreach($nameSpace as &$singleNameSpace)
1022
+		foreach ($nameSpace as &$singleNameSpace)
1023 1023
 		{
1024 1024
 			//if (substr($singleNameSpace['prefix'],0,strlen($folderName))==$folderName) return $singleNameSpace['prefix'];
1025
-			if (substr($folderName,0,strlen($singleNameSpace['prefix']))==$singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1025
+			if (substr($folderName, 0, strlen($singleNameSpace['prefix'])) == $singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1026 1026
 		}
1027 1027
 		return "";
1028 1028
 	}
@@ -1033,12 +1033,12 @@  discard block
 block discarded – undo
1033 1033
 	 * @var boolean $_useCache
1034 1034
 	 * @return string the hierarchyDelimiter
1035 1035
 	 */
1036
-	function getHierarchyDelimiter($_useCache=true)
1036
+	function getHierarchyDelimiter($_useCache = true)
1037 1037
 	{
1038 1038
 		static $HierarchyDelimiter = null;
1039
-		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1040
-		if ($_useCache===false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1041
-		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId])&&!empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1039
+		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 24 * 5);
1040
+		if ($_useCache === false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1041
+		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId]) && !empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1042 1042
 		{
1043 1043
 			return $HierarchyDelimiter[$this->icServer->ImapServerId];
1044 1044
 		}
@@ -1048,17 +1048,17 @@  discard block
 block discarded – undo
1048 1048
 			$this->icServer->getCurrentMailbox();
1049 1049
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = $this->icServer->getDelimiter();
1050 1050
 		}
1051
-		catch(\Exception $e)
1051
+		catch (\Exception $e)
1052 1052
 		{
1053
-			if ($e->getCode()==102)
1053
+			if ($e->getCode() == 102)
1054 1054
 			{
1055
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1056
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1055
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1056
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1057 1057
 			}
1058 1058
 			unset($e);
1059 1059
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = '/';
1060 1060
 		}
1061
-		Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),$HierarchyDelimiter, 60*60*24*5);
1061
+		Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), $HierarchyDelimiter, 60 * 60 * 24 * 5);
1062 1062
 		return $HierarchyDelimiter[$this->icServer->ImapServerId];
1063 1063
 	}
1064 1064
 
@@ -1071,7 +1071,7 @@  discard block
 block discarded – undo
1071 1071
 	{
1072 1072
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$this->icServer->ImapServerId.' Connected:'.$this->icServer->_connected);
1073 1073
 		static $_specialUseFolders = null;
1074
-		if (is_null($_specialUseFolders)||empty($_specialUseFolders)) $_specialUseFolders = Cache::getCache(Cache::INSTANCE,'email','specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1074
+		if (is_null($_specialUseFolders) || empty($_specialUseFolders)) $_specialUseFolders = Cache::getCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 24 * 5);
1075 1075
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_trash));
1076 1076
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_sent));
1077 1077
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_draft));
@@ -1079,20 +1079,20 @@  discard block
 block discarded – undo
1079 1079
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1080 1080
 		if (isset($_specialUseFolders[$this->icServer->ImapServerId]) && !empty($_specialUseFolders[$this->icServer->ImapServerId]))
1081 1081
 			return $_specialUseFolders[$this->icServer->ImapServerId];
1082
-		$_specialUseFolders[$this->icServer->ImapServerId]=array();
1082
+		$_specialUseFolders[$this->icServer->ImapServerId] = array();
1083 1083
 		//if (!empty($this->icServer->acc_folder_trash) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]))
1084
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]='Trash';
1084
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash] = 'Trash';
1085 1085
 		//if (!empty($this->icServer->acc_folder_draft) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]))
1086
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]='Drafts';
1086
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft] = 'Drafts';
1087 1087
 		//if (!empty($this->icServer->acc_folder_sent) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]))
1088
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]='Sent';
1088
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent] = 'Sent';
1089 1089
 		//if (!empty($this->icServer->acc_folder_template) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]))
1090
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]='Templates';
1091
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk]='Junk';
1092
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive]='Archive';
1090
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template] = 'Templates';
1091
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk] = 'Junk';
1092
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive] = 'Archive';
1093 1093
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_specialUseFolders));//.'<->'.array2string($this->icServer));
1094 1094
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1095
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$_specialUseFolders, 60*60*24*5);
1095
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $_specialUseFolders, 60 * 60 * 24 * 5);
1096 1096
 		return $_specialUseFolders[$this->icServer->ImapServerId];
1097 1097
 	}
1098 1098
 
@@ -1106,8 +1106,8 @@  discard block
 block discarded – undo
1106 1106
 	function folderIsSelectable($folderToSelect)
1107 1107
 	{
1108 1108
 		$retval = true;
1109
-		if($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect,false,true))) {
1110
-			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']),'noselect')!==false)
1109
+		if ($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect, false, true))) {
1110
+			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']), 'noselect') !== false)
1111 1111
 			{
1112 1112
 				$retval = false;
1113 1113
 			}
@@ -1127,7 +1127,7 @@  discard block
 block discarded – undo
1127 1127
 	 *
1128 1128
 	 * @throws Exception
1129 1129
 	 */
1130
-	function _getStatus($folderName,$ignoreStatusCache=false)
1130
+	function _getStatus($folderName, $ignoreStatusCache = false)
1131 1131
 	{
1132 1132
 		static $folderStatus = null;
1133 1133
 		if (!$ignoreStatusCache && isset($folderStatus[$this->icServer->ImapServerId][$folderName]))
@@ -1137,11 +1137,11 @@  discard block
 block discarded – undo
1137 1137
 		}
1138 1138
 		try
1139 1139
 		{
1140
-			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName,$ignoreStatusCache);
1140
+			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName, $ignoreStatusCache);
1141 1141
 		}
1142 1142
 		catch (\Exception $e)
1143 1143
 		{
1144
-			throw new Exception(__METHOD__.' ('.__LINE__.') '." failed for $folderName with error:".$e->getMessage().($e->details?', '.$e->details:''));
1144
+			throw new Exception(__METHOD__.' ('.__LINE__.') '." failed for $folderName with error:".$e->getMessage().($e->details ? ', '.$e->details : ''));
1145 1145
 		}
1146 1146
 		return $folderStatus[$this->icServer->ImapServerId][$folderName];
1147 1147
 	}
@@ -1157,10 +1157,10 @@  discard block
 block discarded – undo
1157 1157
 	 * @param fetchSubscribedInfo bool fetch Subscribed Info on folder
1158 1158
 	 * @return array
1159 1159
 	 */
1160
-	function getFolderStatus($_folderName,$ignoreStatusCache=false,$basicInfoOnly=false,$fetchSubscribedInfo=true)
1160
+	function getFolderStatus($_folderName, $ignoreStatusCache = false, $basicInfoOnly = false, $fetchSubscribedInfo = true)
1161 1161
 	{
1162 1162
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." called with:$_folderName,$ignoreStatusCache,$basicInfoOnly");
1163
-		if (!is_string($_folderName) || empty($_folderName)||(isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID])))
1163
+		if (!is_string($_folderName) || empty($_folderName) || (isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID])))
1164 1164
 		{
1165 1165
 			// something is wrong. Do not proceed. either no folder or profile is marked as defunct for this request
1166 1166
 			return false;
@@ -1171,7 +1171,7 @@  discard block
 block discarded – undo
1171 1171
 		{
1172 1172
 			$folderInfoCache = $folderBasicInfo[$this->profileID];
1173 1173
 		}
1174
-		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache==false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1174
+		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache == false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1175 1175
 		$retValue = array();
1176 1176
 		$retValue['subscribed'] = false;
1177 1177
 /*
@@ -1192,41 +1192,41 @@  discard block
 block discarded – undo
1192 1192
 			{
1193 1193
 				//error_log(__METHOD__.array2string($e));
1194 1194
 				//error_log(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
1195
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1196
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1197
-				throw new Exception(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
1195
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1196
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1197
+				throw new Exception(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : ''));
1198 1198
 			}
1199 1199
 			//error_log(__METHOD__.' ('.__LINE__.') '.$_folderName.' '.array2string($ret));
1200 1200
 			if (is_array($ret))
1201 1201
 			{
1202 1202
 				$retkeys = array_keys($ret);
1203
-				if ($retkeys[0]==$_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1203
+				if ($retkeys[0] == $_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1204 1204
 			}
1205 1205
 			else
1206 1206
 			{
1207
-				$folderInfoCache[$_folderName]=false;
1207
+				$folderInfoCache[$_folderName] = false;
1208 1208
 			}
1209 1209
 		}
1210 1210
 		$folderInfo = $folderInfoCache[$_folderName];
1211 1211
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($folderInfo).'->'.function_backtrace());
1212
-		if($ignoreStatusCache||!$folderInfo|| !is_array($folderInfo)) {
1212
+		if ($ignoreStatusCache || !$folderInfo || !is_array($folderInfo)) {
1213 1213
 			try
1214 1214
 			{
1215
-				$folderInfo = $this->_getStatus($_folderName,$ignoreStatusCache);
1215
+				$folderInfo = $this->_getStatus($_folderName, $ignoreStatusCache);
1216 1216
 			}
1217 1217
 			catch (\Exception $e)
1218 1218
 			{
1219 1219
 				//error_log(__METHOD__.array2string($e));
1220
-				error_log(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
1221
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1222
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1220
+				error_log(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : '')/*.function_backtrace()*/);
1221
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1222
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1223 1223
 				//throw new Exception(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
1224
-				$folderInfo=null;
1224
+				$folderInfo = null;
1225 1225
 			}
1226 1226
 			if (!is_array($folderInfo))
1227 1227
 			{
1228 1228
 				// no folder info, but there is a status returned for the folder: something is wrong, try to cope with it
1229
-				$folderInfo = is_array($folderInfo)?$folderInfo:array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1229
+				$folderInfo = is_array($folderInfo) ? $folderInfo : array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1230 1230
 					'ATTRIBUTES' => '');
1231 1231
 				if (!isset($folderInfo['HIERACHY_DELIMITER']) || empty($folderInfo['HIERACHY_DELIMITER']) || (isset($folderInfo['delimiter']) && empty($folderInfo['delimiter'])))
1232 1232
 				{
@@ -1238,24 +1238,24 @@  discard block
 block discarded – undo
1238 1238
 		#if(!is_array($folderInfo)) {
1239 1239
 		#	return false;
1240 1240
 		#}
1241
-		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER']?$folderInfo['HIERACHY_DELIMITER']:$folderInfo['delimiter']);
1242
-		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES']?$folderInfo['ATTRIBUTES']:$folderInfo['attributes']);
1243
-		$shortNameParts			= explode($retValue['delimiter'], $_folderName);
1241
+		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER'] ? $folderInfo['HIERACHY_DELIMITER'] : $folderInfo['delimiter']);
1242
+		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES'] ? $folderInfo['ATTRIBUTES'] : $folderInfo['attributes']);
1243
+		$shortNameParts = explode($retValue['delimiter'], $_folderName);
1244 1244
 		$retValue['shortName']		= array_pop($shortNameParts);
1245 1245
 		$retValue['displayName']	= $_folderName;
1246
-		$retValue['shortDisplayName']	= $retValue['shortName'];
1247
-		if(strtoupper($retValue['shortName']) == 'INBOX') {
1248
-			$retValue['displayName']	= lang('INBOX');
1249
-			$retValue['shortDisplayName']	= lang('INBOX');
1246
+		$retValue['shortDisplayName'] = $retValue['shortName'];
1247
+		if (strtoupper($retValue['shortName']) == 'INBOX') {
1248
+			$retValue['displayName'] = lang('INBOX');
1249
+			$retValue['shortDisplayName'] = lang('INBOX');
1250 1250
 		}
1251 1251
 		// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
1252
-		elseif (in_array($retValue['shortName'],self::$autoFolders))
1252
+		elseif (in_array($retValue['shortName'], self::$autoFolders))
1253 1253
 		{
1254 1254
 			$retValue['displayName'] = $retValue['shortDisplayName'] = lang($retValue['shortName']);
1255 1255
 		}
1256
-		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName]=$retValue;
1256
+		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName] = $retValue;
1257 1257
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.$_folderName.array2string($retValue['attributes']));
1258
-		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']),'noselect')!==false))
1258
+		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']), 'noselect') !== false))
1259 1259
 		{
1260 1260
 			return $retValue;
1261 1261
 		}
@@ -1268,12 +1268,12 @@  discard block
 block discarded – undo
1268 1268
 		if (is_null($nameSpace) || empty($nameSpace[$this->profileID])) $nameSpace[$this->profileID] = $this->_getNameSpaces();
1269 1269
 		if (!empty($nameSpace[$this->profileID]))
1270 1270
 		{
1271
-			$nsNoPersonal=array();
1272
-			foreach($nameSpace[$this->profileID] as &$ns)
1271
+			$nsNoPersonal = array();
1272
+			foreach ($nameSpace[$this->profileID] as &$ns)
1273 1273
 			{
1274
-				if ($ns['type']!='personal') $nsNoPersonal[]=$ns;
1274
+				if ($ns['type'] != 'personal') $nsNoPersonal[] = $ns;
1275 1275
 			}
1276
-			$nameSpace[$this->profileID]=$nsNoPersonal;
1276
+			$nameSpace[$this->profileID] = $nsNoPersonal;
1277 1277
 		}
1278 1278
 		if (is_null($prefix) || empty($prefix[$this->profileID]) || empty($prefix[$this->profileID][$_folderName])) $prefix[$this->profileID][$_folderName] = $this->getFolderPrefixFromNamespace($nameSpace[$this->profileID], $_folderName);
1279 1279
 
@@ -1282,34 +1282,34 @@  discard block
 block discarded – undo
1282 1282
 			$subscribedFolders[$this->profileID] = $this->icServer->listSubscribedMailboxes();
1283 1283
 		}
1284 1284
 
1285
-		if($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName,$subscribedFolders[$this->profileID])) {
1285
+		if ($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName, $subscribedFolders[$this->profileID])) {
1286 1286
 			$retValue['subscribed'] = true;
1287 1287
 		}
1288 1288
 
1289 1289
 		try
1290 1290
 		{
1291 1291
 			//$folderStatus = $this->_getStatus($_folderName,$ignoreStatusCache);
1292
-			$folderStatus = $this->getMailBoxCounters($_folderName,false);
1293
-			$retValue['messages']		= $folderStatus['MESSAGES'];
1292
+			$folderStatus = $this->getMailBoxCounters($_folderName, false);
1293
+			$retValue['messages'] = $folderStatus['MESSAGES'];
1294 1294
 			$retValue['recent']		= $folderStatus['RECENT'];
1295
-			$retValue['uidnext']		= $folderStatus['UIDNEXT'];
1296
-			$retValue['uidvalidity']	= $folderStatus['UIDVALIDITY'];
1295
+			$retValue['uidnext'] = $folderStatus['UIDNEXT'];
1296
+			$retValue['uidvalidity'] = $folderStatus['UIDVALIDITY'];
1297 1297
 			$retValue['unseen']		= $folderStatus['UNSEEN'];
1298 1298
 			if (//$retValue['unseen']==0 &&
1299 1299
 				(isset($this->mailPreferences['trustServersUnseenInfo']) && // some servers dont serve the UNSEEN information
1300
-				$this->mailPreferences['trustServersUnseenInfo']==false) ||
1300
+				$this->mailPreferences['trustServersUnseenInfo'] == false) ||
1301 1301
 				(isset($this->mailPreferences['trustServersUnseenInfo']) &&
1302
-				$this->mailPreferences['trustServersUnseenInfo']==2 &&
1303
-				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName,$prefix[$this->profileID][$_folderName]) !== false)
1302
+				$this->mailPreferences['trustServersUnseenInfo'] == 2 &&
1303
+				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName, $prefix[$this->profileID][$_folderName]) !== false)
1304 1304
 			)
1305 1305
 			{
1306 1306
 				//error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($prefix,true).' TS:'.$this->mailPreferences['trustServersUnseenInfo']);
1307 1307
 				// we filter for the combined status of unseen and undeleted, as this is what we show in list
1308 1308
 				try
1309 1309
 				{
1310
-					$byUid=true;
1311
-					$_reverse=1;
1312
-					$sortResult = $this->getSortedList($_folderName, $_sort=0, $_reverse, array('status'=>array('UNSEEN','UNDELETED')),$byUid,false);
1310
+					$byUid = true;
1311
+					$_reverse = 1;
1312
+					$sortResult = $this->getSortedList($_folderName, $_sort = 0, $_reverse, array('status'=>array('UNSEEN', 'UNDELETED')), $byUid, false);
1313 1313
 					$retValue['unseen'] = $sortResult['count'];
1314 1314
 				}
1315 1315
 				catch (\Exception $ee)
@@ -1320,7 +1320,7 @@  discard block
 block discarded – undo
1320 1320
 		}
1321 1321
 		catch (\Exception $e)
1322 1322
 		{
1323
-			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(),true));
1323
+			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(), true));
1324 1324
 		}
1325 1325
 
1326 1326
 		return $retValue;
@@ -1342,7 +1342,7 @@  discard block
 block discarded – undo
1342 1342
 	 * @param mixed $_fetchPreviews = false (boolean/int) fetch part of the body of the messages requested (if integer the number is assumed to be the number of chars to be returned for preview; if set to true 300 chars are returned (when available))
1343 1343
 	 * @return array result as array(header=>array,total=>int,first=>int,last=>int)
1344 1344
 	 */
1345
-	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly=null, $_cacheResult=true, $_fetchPreviews=false)
1345
+	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly = null, $_cacheResult = true, $_fetchPreviews = false)
1346 1346
 	{
1347 1347
 		//self::$debug=true;
1348 1348
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.function_backtrace());
@@ -1355,7 +1355,7 @@  discard block
 block discarded – undo
1355 1355
 		$rByUid = true; // try searching by uid. this var will be passed by reference to getSortedList, and may be set to false, if UID retrieval fails
1356 1356
 		#print "<pre>";
1357 1357
 		#$this->icServer->setDebug(true);
1358
-		$total=0;
1358
+		$total = 0;
1359 1359
 		if ($_thisUIDOnly === null)
1360 1360
 		{
1361 1361
 			if (($_startMessage || $_numberOfMessages) && !isset($_filter['range']))
@@ -1368,24 +1368,24 @@  discard block
 block discarded – undo
1368 1368
 				//$_filter['range'] ="$_startMessage:*";
1369 1369
 			}
1370 1370
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_sort, $reverse, ".array2string($_filter).", $rByUid");
1371
-			if (self::$debug||self::$debugTimes) $starttime = microtime (true);
1371
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1372 1372
 			//see this example below for a 12 week datefilter (since)
1373 1373
 			//$_filter = array('status'=>array('UNDELETED'),'type'=>"SINCE",'string'=> date("d-M-Y", $starttime-(3600*24*7*12)));
1374 1374
 			$_sortResult = $this->getSortedList($_folderName, $_sort, $reverse, $_filter, $rByUid, $_cacheResult);
1375 1375
 			$sortResult = $_sortResult['match']->ids;
1376 1376
 			//$modseq = $_sortResult['modseq'];
1377 1377
 			//error_log(__METHOD__.' ('.__LINE__.') '.'Modsequence:'.$modseq);
1378
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly),__METHOD__.' ('.__LINE__.') ');
1378
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly), __METHOD__.' ('.__LINE__.') ');
1379 1379
 
1380 1380
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1381 1381
 			#$this->icServer->setDebug(false);
1382 1382
 			#print "</pre>";
1383 1383
 			// nothing found
1384
-			if(!is_array($sortResult) || empty($sortResult)) {
1384
+			if (!is_array($sortResult) || empty($sortResult)) {
1385 1385
 				$retValue = array();
1386 1386
 				$retValue['info']['total']	= 0;
1387 1387
 				$retValue['info']['first']	= 0;
1388
-				$retValue['info']['last']	= 0;
1388
+				$retValue['info']['last'] = 0;
1389 1389
 				return $retValue;
1390 1390
 			}
1391 1391
 
@@ -1393,54 +1393,54 @@  discard block
 block discarded – undo
1393 1393
 			#_debug_array($sortResult);
1394 1394
 			#_debug_array(array_slice($sortResult, -5, -2));
1395 1395
 			//error_log("REVERSE: $reverse");
1396
-			if($reverse === true) {
1397
-				if  ($_startMessage<=$total)
1396
+			if ($reverse === true) {
1397
+				if ($_startMessage <= $total)
1398 1398
 				{
1399
-					$startMessage = $_startMessage-1;
1399
+					$startMessage = $_startMessage - 1;
1400 1400
 				}
1401 1401
 				else
1402 1402
 				{
1403 1403
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1404
-					if ($_startMessage+$_numberOfMessages>$total)
1404
+					if ($_startMessage + $_numberOfMessages > $total)
1405 1405
 					{
1406
-						$numberOfMessages = $total%$_numberOfMessages;
1406
+						$numberOfMessages = $total % $_numberOfMessages;
1407 1407
 						//$numberOfMessages = abs($_startMessage-$total-1);
1408
-						if ($numberOfMessages>0 && $numberOfMessages<=$_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1408
+						if ($numberOfMessages > 0 && $numberOfMessages <= $_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1409 1409
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1410 1410
 					}
1411
-					$startMessage=($total-$_numberOfMessages)-1;
1411
+					$startMessage = ($total - $_numberOfMessages) - 1;
1412 1412
 					//$retValue['info']['first'] = $startMessage;
1413 1413
 					//$retValue['info']['last'] = $total;
1414 1414
 
1415 1415
 				}
1416
-				if ($startMessage+$_numberOfMessages>$total)
1416
+				if ($startMessage + $_numberOfMessages > $total)
1417 1417
 				{
1418
-					$_numberOfMessages = $_numberOfMessages-($total-($startMessage+$_numberOfMessages));
1418
+					$_numberOfMessages = $_numberOfMessages - ($total - ($startMessage + $_numberOfMessages));
1419 1419
 					//$retValue['info']['first'] = $startMessage;
1420 1420
 					//$retValue['info']['last'] = $total;
1421 1421
 				}
1422
-				if($startMessage > 0) {
1423
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+$startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1424
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+$startMessage), -$startMessage);
1422
+				if ($startMessage > 0) {
1423
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + $startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1424
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + $startMessage), -$startMessage);
1425 1425
 				} else {
1426
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+($_startMessage-1))).', AllTheRest, Number of Messages:'.count($sortResult));
1427
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+($_startMessage-1)));
1426
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + ($_startMessage - 1))).', AllTheRest, Number of Messages:'.count($sortResult));
1427
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + ($_startMessage - 1)));
1428 1428
 				}
1429 1429
 				$sortResult = array_reverse($sortResult);
1430 1430
 			} else {
1431
-				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage-1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1432
-				$sortResult = array_slice($sortResult, $_startMessage-1, $_numberOfMessages);
1431
+				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage - 1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1432
+				$sortResult = array_slice($sortResult, $_startMessage - 1, $_numberOfMessages);
1433 1433
 			}
1434 1434
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1435 1435
 		}
1436 1436
 		else
1437 1437
 		{
1438
-			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly:(array)$_thisUIDOnly);
1438
+			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly : (array)$_thisUIDOnly);
1439 1439
 		}
1440 1440
 
1441 1441
 
1442 1442
 		// fetch the data for the selected messages
1443
-		if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1443
+		if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1444 1444
 		try
1445 1445
 		{
1446 1446
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -1449,22 +1449,22 @@  discard block
 block discarded – undo
1449 1449
 			$fquery = new Horde_Imap_Client_Fetch_Query();
1450 1450
 
1451 1451
 			// Pre-cache the headers we want, 'fetchHeaders' is a label into the cache
1452
-			$fquery->headers('fetchHeaders',array(
1453
-				'DISPOSITION-NOTIFICATION-TO','RETURN-RECEIPT-TO','X-CONFIRM-READING-TO',
1454
-				'DATE','SUBJECT','FROM','TO','CC','REPLY-TO',
1452
+			$fquery->headers('fetchHeaders', array(
1453
+				'DISPOSITION-NOTIFICATION-TO', 'RETURN-RECEIPT-TO', 'X-CONFIRM-READING-TO',
1454
+				'DATE', 'SUBJECT', 'FROM', 'TO', 'CC', 'REPLY-TO',
1455 1455
 				'X-PRIORITY'
1456
-			),array(
1456
+			), array(
1457 1457
 				// Cache headers, we'll look at them below
1458
-				'cache' => true,//$_cacheResult,
1458
+				'cache' => true, //$_cacheResult,
1459 1459
 				// Set peek so messages are not flagged as read
1460 1460
 				'peek' => true
1461 1461
 			));
1462 1462
 			$fquery->size();
1463 1463
 			$fquery->structure();
1464 1464
 			$fquery->flags();
1465
-			$fquery->imapDate();// needed to ensure getImapDate fetches the internaldate, not the current time
1465
+			$fquery->imapDate(); // needed to ensure getImapDate fetches the internaldate, not the current time
1466 1466
 			// if $_fetchPreviews is activated fetch part of the messages too
1467
-			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true,'length'=>((int)$_fetchPreviews<5000?5000:$_fetchPreviews),'start'=>0));
1467
+			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true, 'length'=>((int)$_fetchPreviews < 5000 ? 5000 : $_fetchPreviews), 'start'=>0));
1468 1468
 			$headersNew = $this->icServer->fetch($_folderName, $fquery, array(
1469 1469
 				'ids' => $uidsToFetch,
1470 1470
 			));
@@ -1475,9 +1475,9 @@  discard block
 block discarded – undo
1475 1475
 			$headersNew = array();
1476 1476
 			$sortResult = array();
1477 1477
 		}
1478
-		if (self::$debug||self::$debugTimes)
1478
+		if (self::$debug || self::$debugTimes)
1479 1479
 		{
1480
-			self::logRunTimes($starttime,null,'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter),__METHOD__.' ('.__LINE__.') ');
1480
+			self::logRunTimes($starttime, null, 'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter), __METHOD__.' ('.__LINE__.') ');
1481 1481
 			if (self::$debug)
1482 1482
 			{
1483 1483
 				$queryString = implode(',', $sortResult);
@@ -1487,27 +1487,27 @@  discard block
 block discarded – undo
1487 1487
 
1488 1488
 		$cnt = 0;
1489 1489
 
1490
-		foreach((array)$sortResult as $uid) {
1490
+		foreach ((array)$sortResult as $uid) {
1491 1491
 			$sortOrder[$uid] = $cnt++;
1492 1492
 		}
1493 1493
 
1494 1494
 		$count = 0;
1495 1495
 		if (is_object($headersNew)) {
1496
-			if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1497
-			foreach($headersNew->ids() as $id) {
1496
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1497
+			foreach ($headersNew->ids() as $id) {
1498 1498
 				$_headerObject = $headersNew->get($id);
1499 1499
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject));
1500 1500
 				$headerObject = array();
1501 1501
 				$bodyPreview = null;
1502
-				$uid = $headerObject['UID']= ($_headerObject->getUid()?$_headerObject->getUid():$id);
1502
+				$uid = $headerObject['UID'] = ($_headerObject->getUid() ? $_headerObject->getUid() : $id);
1503 1503
 				$headerObject['MSG_NUM'] = $_headerObject->getSeq();
1504 1504
 				$headerObject['SIZE'] = $_headerObject->getSize();
1505 1505
 				$headerObject['INTERNALDATE'] = $_headerObject->getImapDate();
1506 1506
 
1507 1507
 				// Get already cached headers, 'fetchHeaders' is a label matchimg above
1508
-				$headerForPrio = $_headerObject->getHeaders('fetchHeaders',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1508
+				$headerForPrio = $_headerObject->getHeaders('fetchHeaders', Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1509 1509
 				// Try to fetch header with key='' as some servers might have no fetchHeaders index. e.g. yandex.com
1510
-				if (empty($headerForPrio)) $headerForPrio = $_headerObject->getHeaders('',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1510
+				if (empty($headerForPrio)) $headerForPrio = $_headerObject->getHeaders('', Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1511 1511
 				//fetch the fullMsg part if all conditions match to be available in case $_headerObject->getHeaders returns
1512 1512
 				//nothing worthwhile (as it does for googlemail accounts, when preview is switched on
1513 1513
 				if ($_fetchPreviews)
@@ -1515,16 +1515,16 @@  discard block
 block discarded – undo
1515 1515
 					// on enabled preview $bodyPreview is needed lateron. fetched here, for fallback-reasons
1516 1516
 					// in case of failed Header-Retrieval
1517 1517
 					$bodyPreview = $_headerObject->getFullMsg();
1518
-					if (empty($headerForPrio)||(is_array($headerForPrio)&&count($headerForPrio)===1&&$headerForPrio['']))
1518
+					if (empty($headerForPrio) || (is_array($headerForPrio) && count($headerForPrio) === 1 && $headerForPrio['']))
1519 1519
 					{
1520 1520
 						$length = strpos($bodyPreview, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
1521
-						if ($length===false) $length = strlen($bodyPreview);
1522
-						$headerForPrio =  Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0,$length))->toArray();
1521
+						if ($length === false) $length = strlen($bodyPreview);
1522
+						$headerForPrio = Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0, $length))->toArray();
1523 1523
 					}
1524 1524
 				}
1525 1525
 				$headerForPrio = array_change_key_case($headerForPrio, CASE_UPPER);
1526 1526
 				if (self::$debug) {
1527
-					error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject).'UID:'.$_headerObject->getUid().' Size:'.$_headerObject->getSize().' Date:'.$_headerObject->getImapDate().'/'.DateTime::to($_headerObject->getImapDate(),'Y-m-d H:i:s'));
1527
+					error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject).'UID:'.$_headerObject->getUid().' Size:'.$_headerObject->getSize().' Date:'.$_headerObject->getImapDate().'/'.DateTime::to($_headerObject->getImapDate(), 'Y-m-d H:i:s'));
1528 1528
 					error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerForPrio));
1529 1529
 				}
1530 1530
 				// message deleted from server but cache still reporting its existence ; may happen on QRESYNC with No permanent modsequences
@@ -1533,22 +1533,22 @@  discard block
 block discarded – undo
1533 1533
 					$total--;
1534 1534
 					continue;
1535 1535
 				}
1536
-				if ( isset($headerForPrio['DISPOSITION-NOTIFICATION-TO']) ) {
1536
+				if (isset($headerForPrio['DISPOSITION-NOTIFICATION-TO'])) {
1537 1537
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['DISPOSITION-NOTIFICATION-TO']));
1538
-				} else if ( isset($headerForPrio['RETURN-RECEIPT-TO']) ) {
1538
+				} else if (isset($headerForPrio['RETURN-RECEIPT-TO'])) {
1539 1539
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['RETURN-RECEIPT-TO']));
1540
-				} else if ( isset($headerForPrio['X-CONFIRM-READING-TO']) ) {
1540
+				} else if (isset($headerForPrio['X-CONFIRM-READING-TO'])) {
1541 1541
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['X-CONFIRM-READING-TO']));
1542 1542
 				} /*else $sent_not = "";*/
1543 1543
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1544 1544
 				$headerObject['DATE'] = $headerForPrio['DATE'];
1545
-				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT'])?$headerForPrio['SUBJECT'][0]:$headerForPrio['SUBJECT']);
1546
-				$headerObject['FROM'] = (array)($headerForPrio['FROM']?$headerForPrio['FROM']:($headerForPrio['REPLY-TO']?$headerForPrio['REPLY-TO']:$headerForPrio['RETURN-PATH']));
1545
+				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT']) ? $headerForPrio['SUBJECT'][0] : $headerForPrio['SUBJECT']);
1546
+				$headerObject['FROM'] = (array)($headerForPrio['FROM'] ? $headerForPrio['FROM'] : ($headerForPrio['REPLY-TO'] ? $headerForPrio['REPLY-TO'] : $headerForPrio['RETURN-PATH']));
1547 1547
 				$headerObject['TO'] = (array)$headerForPrio['TO'];
1548
-				$headerObject['CC'] = isset($headerForPrio['CC'])?(array)$headerForPrio['CC']:array();
1549
-				$headerObject['REPLY-TO'] = isset($headerForPrio['REPLY-TO'])?(array)$headerForPrio['REPLY-TO']:array();
1550
-				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY'])?$headerForPrio['X-PRIORITY']:null;
1551
-				foreach (array('FROM','TO','CC','REPLY-TO') as $key)
1548
+				$headerObject['CC'] = isset($headerForPrio['CC']) ? (array)$headerForPrio['CC'] : array();
1549
+				$headerObject['REPLY-TO'] = isset($headerForPrio['REPLY-TO']) ? (array)$headerForPrio['REPLY-TO'] : array();
1550
+				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY']) ? $headerForPrio['X-PRIORITY'] : null;
1551
+				foreach (array('FROM', 'TO', 'CC', 'REPLY-TO') as $key)
1552 1552
 				{
1553 1553
 					$address = array();
1554 1554
 					foreach ($headerObject[$key] as $k => $ad)
@@ -1570,13 +1570,13 @@  discard block
 block discarded – undo
1570 1570
 						foreach ($rfcAddr as $_rfcAddr)
1571 1571
 						{
1572 1572
 							if (!$_rfcAddr->valid)	continue; // skip. not a valid address
1573
-							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox,$_rfcAddr->host,$_rfcAddr->personal);
1573
+							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox, $_rfcAddr->host, $_rfcAddr->personal);
1574 1574
 						}
1575 1575
 					}
1576 1576
 					$headerObject[$key] = $address;
1577 1577
 				}
1578 1578
 				$headerObject['FLAGS'] = $_headerObject->getFlags();
1579
-				$headerObject['BODYPREVIEW']=null;
1579
+				$headerObject['BODYPREVIEW'] = null;
1580 1580
 				// this section fetches part of the message-body (if enabled) for some kind of preview
1581 1581
 				// if we fail to succeed, we fall back to the retrieval of the message-body with
1582 1582
 				// fetchPartContents (see below, when we iterate over the structure to determine the
@@ -1588,17 +1588,17 @@  discard block
 block discarded – undo
1588 1588
 					if (empty($bodyPreview)) $bodyPreview = $_headerObject->getFullMsg();
1589 1589
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($bodyPreview));
1590 1590
 					$base = Horde_Mime_Part::parseMessage($bodyPreview);
1591
-					foreach($base->partIterator() as $part)
1591
+					foreach ($base->partIterator() as $part)
1592 1592
 					{
1593 1593
 						//error_log(__METHOD__.__LINE__.'Part:'.$part->getPrimaryType());
1594
-						if (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'text')
1594
+						if (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'text')
1595 1595
 						{
1596 1596
 							$charset = $part->getContentTypeParameter('charset');
1597 1597
 							$buffer = Mail\Html::convertHTMLToText($part->toString(array(
1598
-												'encode' => Horde_Mime_Part::ENCODE_BINARY,	// otherwise we cant recode charset
1598
+												'encode' => Horde_Mime_Part::ENCODE_BINARY, // otherwise we cant recode charset
1599 1599
 											)), $charset, 'utf-8');
1600
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Translation::convert_jsonsafe($buffer),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1601
-						} elseif (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'multipart')
1600
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Translation::convert_jsonsafe($buffer), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1601
+						} elseif (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'multipart')
1602 1602
 						{
1603 1603
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part));
1604 1604
 						}
@@ -1609,12 +1609,12 @@  discard block
 block discarded – undo
1609 1609
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1610 1610
 				//error_log(__METHOD__.' ('.__LINE__.') '.' MimeMap:'.array2string($mailStructureObject->contentTypeMap()));
1611 1611
 				//foreach ($_headerObject->getStructure()->getParts() as $p => $part)
1612
-				$headerObject['ATTACHMENTS']=null;
1613
-				$skipParts=array();
1614
-				$messageMimeType='';
1612
+				$headerObject['ATTACHMENTS'] = null;
1613
+				$skipParts = array();
1614
+				$messageMimeType = '';
1615 1615
 				foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
1616 1616
 				{
1617
-					if ($mime_id==0 || $messageMimeType==='') $messageMimeType = $mime_type;
1617
+					if ($mime_id == 0 || $messageMimeType === '') $messageMimeType = $mime_type;
1618 1618
 					$part = $mailStructureObject->getPart($mime_id);
1619 1619
 					$partdisposition = $part->getDisposition();
1620 1620
 					$partPrimaryType = $part->getPrimaryType();
@@ -1622,16 +1622,16 @@  discard block
 block discarded – undo
1622 1622
 					// drawback here it is talking to the mailserver for each mail thus consuming
1623 1623
 					// more time than expected; so we call this section only when there is no
1624 1624
 					// bodypreview could be found (multipart/....)
1625
-					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW'])&&($partPrimaryType == 'text') &&
1625
+					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW']) && ($partPrimaryType == 'text') &&
1626 1626
 						((intval($mime_id) === 1) || !$mime_id) &&
1627 1627
 						($partdisposition !== 'attachment')) {
1628
-							$_structure=$part;
1629
-							$this->fetchPartContents($uid, $_structure, false,true);
1630
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1631
-							$charSet=Translation::detect_encoding($headerObject['BODYPREVIEW']);
1628
+							$_structure = $part;
1629
+							$this->fetchPartContents($uid, $_structure, false, true);
1630
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1631
+							$charSet = Translation::detect_encoding($headerObject['BODYPREVIEW']);
1632 1632
 							// add line breaks to $bodyParts
1633 1633
 							//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
1634
-							$headerObject['BODYPREVIEW']  = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1634
+							$headerObject['BODYPREVIEW'] = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1635 1635
 							//error_log(__METHOD__.__LINE__.$headerObject['BODYPREVIEW']);
1636 1636
 					}
1637 1637
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType);
@@ -1641,28 +1641,28 @@  discard block
 block discarded – undo
1641 1641
 						// the presence of an cid does not necessarily indicate its inline. it may lack the needed
1642 1642
 						// link to show the image. Considering this: we "list" everything that matches the above criteria
1643 1643
 						// as attachment in order to not loose/miss information on our data
1644
-						$partdisposition='attachment';//($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1644
+						$partdisposition = 'attachment'; //($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1645 1645
 					}
1646
-					if ($mime_type=='message/rfc822')
1646
+					if ($mime_type == 'message/rfc822')
1647 1647
 					{
1648 1648
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
1649
-						foreach($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
1649
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
1650 1650
 					}
1651 1651
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType.' Skip:'.array2string($skipParts));
1652
-					if (array_key_exists($mime_id,$skipParts)) continue;
1653
-					if ($partdisposition=='attachment' ||
1654
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&$mime_type=='image/tiff') || // as we are not able to display tiffs
1655
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&empty($cid)) ||
1656
-						($partdisposition=='inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1652
+					if (array_key_exists($mime_id, $skipParts)) continue;
1653
+					if ($partdisposition == 'attachment' ||
1654
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && $mime_type == 'image/tiff') || // as we are not able to display tiffs
1655
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && empty($cid)) ||
1656
+						($partdisposition == 'inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1657 1657
 					{
1658
-						$headerObject['ATTACHMENTS'][$mime_id]=$part->getAllDispositionParameters();
1659
-						$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=$mime_type;
1660
-						$headerObject['ATTACHMENTS'][$mime_id]['uid']=$uid;
1658
+						$headerObject['ATTACHMENTS'][$mime_id] = $part->getAllDispositionParameters();
1659
+						$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] = $mime_type;
1660
+						$headerObject['ATTACHMENTS'][$mime_id]['uid'] = $uid;
1661 1661
 						$headerObject['ATTACHMENTS'][$mime_id]['cid'] = $cid;
1662
-						$headerObject['ATTACHMENTS'][$mime_id]['partID']=$mime_id;
1663
-						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))$headerObject['ATTACHMENTS'][$mime_id]['name']=$part->getName();
1664
-						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'],'winmail.dat') ||
1665
-							$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=='application/ms-tnef')
1662
+						$headerObject['ATTACHMENTS'][$mime_id]['partID'] = $mime_id;
1663
+						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))$headerObject['ATTACHMENTS'][$mime_id]['name'] = $part->getName();
1664
+						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'], 'winmail.dat') ||
1665
+							$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] == 'application/ms-tnef')
1666 1666
 						{
1667 1667
 							$headerObject['ATTACHMENTS'][$mime_id]['is_winmail'] = true;
1668 1668
 						}
@@ -1677,57 +1677,57 @@  discard block
 block discarded – undo
1677 1677
 				if (empty($headerObject['UID'])) continue;
1678 1678
 				//$uid = ($rByUid ? $headerObject['UID'] : $headerObject['MSG_NUM']);
1679 1679
 				// make dates like "Mon, 23 Apr 2007 10:11:06 UT" working with strtotime
1680
-				if(substr($headerObject['DATE'],-2) === 'UT') {
1680
+				if (substr($headerObject['DATE'], -2) === 'UT') {
1681 1681
 					$headerObject['DATE'] .= 'C';
1682 1682
 				}
1683
-				if(substr($headerObject['INTERNALDATE'],-2) === 'UT') {
1683
+				if (substr($headerObject['INTERNALDATE'], -2) === 'UT') {
1684 1684
 					$headerObject['INTERNALDATE'] .= 'C';
1685 1685
 				}
1686 1686
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$headerObject['SUBJECT'].'->'.$headerObject['DATE'].'<->'.$headerObject['INTERNALDATE'] .'#');
1687 1687
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$this->decode_subject($headerObject['SUBJECT']).'->'.$headerObject['DATE']);
1688
-				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][]=$a;}
1689
-				$retValue['header'][$sortOrder[$uid]]['subject']	= $this->decode_subject($headerObject['SUBJECT']);
1690
-				$retValue['header'][$sortOrder[$uid]]['size'] 		= $headerObject['SIZE'];
1691
-				$retValue['header'][$sortOrder[$uid]]['date']		= self::_strtotime(($headerObject['DATE']&&!($headerObject['DATE']=='NIL')?$headerObject['DATE']:$headerObject['INTERNALDATE']),'ts',true);
1692
-				$retValue['header'][$sortOrder[$uid]]['internaldate']= self::_strtotime($headerObject['INTERNALDATE'],'ts',true);
1693
-				$retValue['header'][$sortOrder[$uid]]['mimetype']	= $messageMimeType;
1694
-				$retValue['header'][$sortOrder[$uid]]['id']		= $headerObject['MSG_NUM'];
1695
-				$retValue['header'][$sortOrder[$uid]]['uid']		= $headerObject['UID'];
1696
-				$retValue['header'][$sortOrder[$uid]]['bodypreview']		= $headerObject['BODYPREVIEW'];
1697
-				$retValue['header'][$sortOrder[$uid]]['priority']		= ($headerObject['PRIORITY']?$headerObject['PRIORITY']:3);
1688
+				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][] = $a; }
1689
+				$retValue['header'][$sortOrder[$uid]]['subject'] = $this->decode_subject($headerObject['SUBJECT']);
1690
+				$retValue['header'][$sortOrder[$uid]]['size'] = $headerObject['SIZE'];
1691
+				$retValue['header'][$sortOrder[$uid]]['date'] = self::_strtotime(($headerObject['DATE'] && !($headerObject['DATE'] == 'NIL') ? $headerObject['DATE'] : $headerObject['INTERNALDATE']), 'ts', true);
1692
+				$retValue['header'][$sortOrder[$uid]]['internaldate'] = self::_strtotime($headerObject['INTERNALDATE'], 'ts', true);
1693
+				$retValue['header'][$sortOrder[$uid]]['mimetype'] = $messageMimeType;
1694
+				$retValue['header'][$sortOrder[$uid]]['id'] = $headerObject['MSG_NUM'];
1695
+				$retValue['header'][$sortOrder[$uid]]['uid'] = $headerObject['UID'];
1696
+				$retValue['header'][$sortOrder[$uid]]['bodypreview'] = $headerObject['BODYPREVIEW'];
1697
+				$retValue['header'][$sortOrder[$uid]]['priority'] = ($headerObject['PRIORITY'] ? $headerObject['PRIORITY'] : 3);
1698 1698
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.array2string($retValue['header'][$sortOrder[$uid]]));
1699 1699
 				if (isset($headerObject['DISPOSITION-NOTIFICATION-TO'])) $retValue['header'][$sortOrder[$uid]]['disposition-notification-to'] = $headerObject['DISPOSITION-NOTIFICATION-TO'];
1700 1700
 				if (is_array($headerObject['FLAGS'])) {
1701
-					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]],self::prepareFlagsArray($headerObject));
1701
+					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]], self::prepareFlagsArray($headerObject));
1702 1702
 				}
1703 1703
 				//error_log(__METHOD__.' ('.__LINE__.') '.$headerObject['SUBJECT'].'->'.array2string($_headerObject->getEnvelope()->__get('from')));
1704
-				if(is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1705
-					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0],true);
1704
+				if (is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1705
+					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0], true);
1706 1706
 				}
1707
-				if(is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0]) {
1708
-					$retValue['header'][$sortOrder[$uid]]['reply_to_address'] = self::decode_header($headerObject['REPLY-TO'][0],true);
1707
+				if (is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0]) {
1708
+					$retValue['header'][$sortOrder[$uid]]['reply_to_address'] = self::decode_header($headerObject['REPLY-TO'][0], true);
1709 1709
 				}
1710
-				if(is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1711
-					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0],true);
1712
-					if (count($headerObject['TO'])>1)
1710
+				if (is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1711
+					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0], true);
1712
+					if (count($headerObject['TO']) > 1)
1713 1713
 					{
1714
-						$ki=0;
1715
-						foreach($headerObject['TO'] as $k => $add)
1714
+						$ki = 0;
1715
+						foreach ($headerObject['TO'] as $k => $add)
1716 1716
 						{
1717
-							if ($k==0) continue;
1717
+							if ($k == 0) continue;
1718 1718
 							//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1719
-							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add,true);
1719
+							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add, true);
1720 1720
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1721 1721
 							$ki++;
1722 1722
 						}
1723 1723
 					}
1724 1724
 				}
1725
-				if(is_array($headerObject['CC']) && count($headerObject['CC'])>0) {
1726
-					$ki=0;
1727
-					foreach($headerObject['CC'] as $k => $add)
1725
+				if (is_array($headerObject['CC']) && count($headerObject['CC']) > 0) {
1726
+					$ki = 0;
1727
+					foreach ($headerObject['CC'] as $k => $add)
1728 1728
 					{
1729 1729
 						//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1730
-						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add,true);
1730
+						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add, true);
1731 1731
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1732 1732
 						$ki++;
1733 1733
 					}
@@ -1736,27 +1736,27 @@  discard block
 block discarded – undo
1736 1736
 
1737 1737
 				$count++;
1738 1738
 			}
1739
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' fetching Headers and stuff for Folder:'.$_folderName,__METHOD__.' ('.__LINE__.') ');
1739
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' fetching Headers and stuff for Folder:'.$_folderName, __METHOD__.' ('.__LINE__.') ');
1740 1740
 			//self::$debug=false;
1741 1741
 			// sort the messages to the requested displayorder
1742
-			if(is_array($retValue['header'])) {
1742
+			if (is_array($retValue['header'])) {
1743 1743
 				$countMessages = $total;
1744 1744
 				if (isset($_filter['range'])) $countMessages = self::$folderStatusCache[$this->profileID][$_folderName]['messages'];
1745 1745
 				ksort($retValue['header']);
1746 1746
 				$retValue['info']['total']	= $total;
1747 1747
 				//if ($_startMessage>$total) $_startMessage = $total-($count-1);
1748 1748
 				$retValue['info']['first']	= $_startMessage;
1749
-				$retValue['info']['last']	= $_startMessage + $count - 1 ;
1749
+				$retValue['info']['last'] = $_startMessage + $count - 1;
1750 1750
 				return $retValue;
1751 1751
 			} else {
1752 1752
 				$retValue = array();
1753 1753
 				$retValue['info']['total']	= 0;
1754 1754
 				$retValue['info']['first']	= 0;
1755
-				$retValue['info']['last']	= 0;
1755
+				$retValue['info']['last'] = 0;
1756 1756
 				return $retValue;
1757 1757
 			}
1758 1758
 		} else {
1759
-			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew,TRUE));
1759
+			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew, TRUE));
1760 1760
 			$retValue = array();
1761 1761
 			$retValue['info']['total']  = 0;
1762 1762
 			$retValue['info']['first']  = 0;
@@ -1773,17 +1773,17 @@  discard block
 block discarded – undo
1773 1773
 	 */
1774 1774
 	static function prepareFlagsArray($headerObject)
1775 1775
 	{
1776
-		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower',$headerObject['FLAGS']);
1776
+		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower', $headerObject['FLAGS']);
1777 1777
 		$retValue = array();
1778 1778
 		$retValue['recent']		= in_array('\\recent', $headerFlags);
1779 1779
 		$retValue['flagged']	= in_array('\\flagged', $headerFlags);
1780
-		$retValue['answered']	= in_array('\\answered', $headerFlags);
1781
-		$retValue['forwarded']   = in_array('$forwarded', $headerFlags);
1780
+		$retValue['answered'] = in_array('\\answered', $headerFlags);
1781
+		$retValue['forwarded'] = in_array('$forwarded', $headerFlags);
1782 1782
 		$retValue['deleted']	= in_array('\\deleted', $headerFlags);
1783
-		$retValue['seen']		= in_array('\\seen', $headerFlags);
1784
-		$retValue['draft']		= in_array('\\draft', $headerFlags);
1785
-		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags)||in_array('mdnsent', $headerFlags);
1786
-		$retValue['mdnnotsent']	= in_array('$mdnnotsent', $headerFlags)||in_array('mdnnotsent', $headerFlags);
1783
+		$retValue['seen'] = in_array('\\seen', $headerFlags);
1784
+		$retValue['draft'] = in_array('\\draft', $headerFlags);
1785
+		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags) || in_array('mdnsent', $headerFlags);
1786
+		$retValue['mdnnotsent'] = in_array('$mdnnotsent', $headerFlags) || in_array('mdnnotsent', $headerFlags);
1787 1787
 		$retValue['label1']   = in_array('$label1', $headerFlags);
1788 1788
 		$retValue['label2']   = in_array('$label2', $headerFlags);
1789 1789
 		$retValue['label3']   = in_array('$label3', $headerFlags);
@@ -1807,12 +1807,12 @@  discard block
 block discarded – undo
1807 1807
 	 * @param bool $setSession if set to true the session will be populated with the result of the query
1808 1808
 	 * @return mixed bool/array false or array of ids
1809 1809
 	 */
1810
-	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid=true, $setSession=true)
1810
+	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid = true, $setSession = true)
1811 1811
 	{
1812 1812
 		static $cachedFolderStatus = null;
1813 1813
 		// in the past we needed examineMailbox to figure out if the server with the serverID support keywords
1814 1814
 		// this information is filled/provided by examineMailbox; but caching within one request seems o.k.
1815
-		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]) )
1815
+		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]))
1816 1816
 		{
1817 1817
 			$folderStatus = $cachedFolderStatus[$this->profileID][$_folderName] = $this->icServer->examineMailbox($_folderName);
1818 1818
 		}
@@ -1824,29 +1824,29 @@  discard block
 block discarded – undo
1824 1824
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Filter:'.array2string($_filter));
1825 1825
 		$try2useCache = true;
1826 1826
 		static $eMailListContainsDeletedMessages = null;
1827
-		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
1827
+		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
1828 1828
 		// this indicates, that there is no Filter set, and the returned set/subset should not contain DELETED Messages, nor filtered for UNDELETED
1829
-		if ($setSession==true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1829
+		if ($setSession == true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1830 1830
 		{
1831 1831
 			if (self::$debugTimes) $starttime = microtime(true);
1832
-			if (is_null($eMailListContainsDeletedMessages) || empty($eMailListContainsDeletedMessages[$this->profileID]) || empty($eMailListContainsDeletedMessages[$this->profileID][$_folderName])) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
1833
-			$five=true;
1834
-			$dReverse=1;
1835
-			$deletedMessages = $this->getSortedList($_folderName, 0, $dReverse, array('status'=>array('DELETED')),$five,false);
1832
+			if (is_null($eMailListContainsDeletedMessages) || empty($eMailListContainsDeletedMessages[$this->profileID]) || empty($eMailListContainsDeletedMessages[$this->profileID][$_folderName])) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
1833
+			$five = true;
1834
+			$dReverse = 1;
1835
+			$deletedMessages = $this->getSortedList($_folderName, 0, $dReverse, array('status'=>array('DELETED')), $five, false);
1836 1836
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') Found DeletedMessages:'.array2string($eMailListContainsDeletedMessages));
1837
-			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] =$deletedMessages['count'];
1838
-			Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),$eMailListContainsDeletedMessages, 60*60*1);
1839
-			if (self::$debugTimes) self::logRunTimes($starttime,null,'setting eMailListContainsDeletedMessages for Profile:'.$this->profileID.' Folder:'.$_folderName.' to '.$eMailListContainsDeletedMessages[$this->profileID][$_folderName],__METHOD__.' ('.__LINE__.') ');			//error_log(__METHOD__.' ('.__LINE__.') '.' Profile:'.$this->profileID.' Folder:'.$_folderName.' -> EXISTS/SessStat:'.array2string($folderStatus['MESSAGES']).'/'.self::$folderStatusCache[$this->profileID][$_folderName]['messages'].' ListContDelMsg/SessDeleted:'.$eMailListContainsDeletedMessages[$this->profileID][$_folderName].'/'.self::$folderStatusCache[$this->profileID][$_folderName]['deleted']);
1837
+			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] = $deletedMessages['count'];
1838
+			Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), $eMailListContainsDeletedMessages, 60 * 60 * 1);
1839
+			if (self::$debugTimes) self::logRunTimes($starttime, null, 'setting eMailListContainsDeletedMessages for Profile:'.$this->profileID.' Folder:'.$_folderName.' to '.$eMailListContainsDeletedMessages[$this->profileID][$_folderName], __METHOD__.' ('.__LINE__.') '); //error_log(__METHOD__.' ('.__LINE__.') '.' Profile:'.$this->profileID.' Folder:'.$_folderName.' -> EXISTS/SessStat:'.array2string($folderStatus['MESSAGES']).'/'.self::$folderStatusCache[$this->profileID][$_folderName]['messages'].' ListContDelMsg/SessDeleted:'.$eMailListContainsDeletedMessages[$this->profileID][$_folderName].'/'.self::$folderStatusCache[$this->profileID][$_folderName]['deleted']);
1840 1840
 		}
1841 1841
 		$try2useCache = false;
1842 1842
 		//self::$supportsORinQuery[$this->profileID]=true;
1843 1843
 		if (is_null(self::$supportsORinQuery) || !isset(self::$supportsORinQuery[$this->profileID]))
1844 1844
 		{
1845
-			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
1846
-			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID]=true;
1845
+			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
1846
+			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID] = true;
1847 1847
 		}
1848 1848
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_filter).' SupportsOrInQuery:'.self::$supportsORinQuery[$this->profileID]);
1849
-		$filter = $this->createIMAPFilter($_folderName, $_filter,self::$supportsORinQuery[$this->profileID]);
1849
+		$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1850 1850
 		if (self::$debug)
1851 1851
 		{
1852 1852
 			$query_str = $filter->build();
@@ -1854,14 +1854,14 @@  discard block
 block discarded – undo
1854 1854
 		}
1855 1855
 		//_debug_array($filter);
1856 1856
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($filter).'#'.array2string($this->icServer->capability()));
1857
-		if($this->icServer->hasCapability('SORT')) {
1857
+		if ($this->icServer->hasCapability('SORT')) {
1858 1858
 			// when using an orQuery and we sort by date. sort seems to fail on certain servers => ZIMBRA with Horde_Imap_Client
1859 1859
 			// thus we translate the search request from date to Horde_Imap_Client::SORT_SEQUENCE (which should be the same, if
1860 1860
 			// there is no messing with the dates)
1861 1861
 			//if (self::$supportsORinQuery[$this->profileID]&&$_sort=='date'&&$_filter['type']=='quick'&&!empty($_filter['string']))$_sort='INTERNALDATE';
1862 1862
 			if (self::$debug) error_log(__METHOD__." Mailserver has SORT Capability, SortBy: ".array2string($_sort)." Reverse: $_reverse");
1863 1863
 			$sortOrder = $this->_getSortString($_sort, $_reverse);
1864
-			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE,$sortOrder)) $_reverse=false; // as we reversed the result already
1864
+			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE, $sortOrder)) $_reverse = false; // as we reversed the result already
1865 1865
 			if (self::$debug) error_log(__METHOD__." Mailserver runs SORT: SortBy:".array2string($_sort)."->".array2string($sortOrder)." Filter: ".array2string($filter));
1866 1866
 			try
1867 1867
 			{
@@ -1869,24 +1869,24 @@  discard block
 block discarded – undo
1869 1869
 					'sort' => $sortOrder,));
1870 1870
 			// if there is an Error, we assume that the server is not capable of sorting
1871 1871
 			}
1872
-			catch(\Exception $e)
1872
+			catch (\Exception $e)
1873 1873
 			{
1874 1874
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1875 1875
 				$resultByUid = false;
1876 1876
 				$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
1877
-				if ($_reverse) array_unshift($sortOrder,Horde_Imap_Client::SORT_REVERSE);
1877
+				if ($_reverse) array_unshift($sortOrder, Horde_Imap_Client::SORT_REVERSE);
1878 1878
 				try
1879 1879
 				{
1880 1880
 					$sortResult = $this->icServer->search($_folderName, $filter, array(
1881 1881
 						'sort' => $sortOrder));
1882 1882
 				}
1883
-				catch(\Exception $e)
1883
+				catch (\Exception $e)
1884 1884
 				{
1885 1885
 					error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1886 1886
 					$sortResult = self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'];
1887 1887
 				}
1888 1888
 			}
1889
-			if (self::$debug) error_log(__METHOD__.print_r($sortResult,true));
1889
+			if (self::$debug) error_log(__METHOD__.print_r($sortResult, true));
1890 1890
 		} else {
1891 1891
 			if (self::$debug) error_log(__METHOD__." Mailserver has NO SORT Capability");
1892 1892
 			//$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
@@ -1896,12 +1896,12 @@  discard block
 block discarded – undo
1896 1896
 				$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
1897 1897
 					'sort' => $sortOrder)*/);
1898 1898
 			}
1899
-			catch(\Exception $e)
1899
+			catch (\Exception $e)
1900 1900
 			{
1901 1901
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1902 1902
 				// possible error OR Query. But Horde gives no detailed Info :-(
1903
-				self::$supportsORinQuery[$this->profileID]=false;
1904
-				Cache::setCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),self::$supportsORinQuery,60*60*10);
1903
+				self::$supportsORinQuery[$this->profileID] = false;
1904
+				Cache::setCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), self::$supportsORinQuery, 60 * 60 * 10);
1905 1905
 				if (self::$debug) error_log(__METHOD__.__LINE__." Mailserver seems to have NO OR Capability for Search:".$sortResult->message);
1906 1906
 				$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1907 1907
 				try
@@ -1909,25 +1909,25 @@  discard block
 block discarded – undo
1909 1909
 					$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
1910 1910
 						'sort' => $sortOrder)*/);
1911 1911
 				}
1912
-				catch(\Exception $e)
1912
+				catch (\Exception $e)
1913 1913
 				{
1914 1914
 				}
1915 1915
 			}
1916
-			if(is_array($sortResult['match'])) {
1916
+			if (is_array($sortResult['match'])) {
1917 1917
 					// not sure that this is going so succeed as $sortResult['match'] is a hordeObject
1918 1918
 					sort($sortResult['match'], SORT_NUMERIC);
1919 1919
 			}
1920
-			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
1920
+			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter, true)." ->".print_r($sortResult, true));
1921 1921
 		}
1922 1922
 		if ($setSession)
1923 1923
 		{
1924 1924
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidValidity'] = $folderStatus['UIDVALIDITY'];
1925
-			self::$folderStatusCache[$this->profileID][$_folderName]['messages']	= $folderStatus['MESSAGES'];
1925
+			self::$folderStatusCache[$this->profileID][$_folderName]['messages'] = $folderStatus['MESSAGES'];
1926 1926
 			self::$folderStatusCache[$this->profileID][$_folderName]['deleted']	= $eMailListContainsDeletedMessages[$this->profileID][$_folderName];
1927 1927
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidnext']	= $folderStatus['UIDNEXT'];
1928
-			self::$folderStatusCache[$this->profileID][$_folderName]['filter']	= $_filter;
1928
+			self::$folderStatusCache[$this->profileID][$_folderName]['filter'] = $_filter;
1929 1929
 			self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'] = $sortResult;
1930
-			self::$folderStatusCache[$this->profileID][$_folderName]['sort']	= $_sort;
1930
+			self::$folderStatusCache[$this->profileID][$_folderName]['sort'] = $_sort;
1931 1931
 		}
1932 1932
 		//error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
1933 1933
 		//_debug_array($sortResult['match']->ids);
@@ -1941,12 +1941,12 @@  discard block
 block discarded – undo
1941 1941
 	 * @param bool _reverse wether to add REVERSE to the Sort String or not
1942 1942
 	 * @return the sort sequence for horde search
1943 1943
 	 */
1944
-	function _getSortString($_sort, $_reverse=false)
1944
+	function _getSortString($_sort, $_reverse = false)
1945 1945
 	{
1946
-		$_reverse=false;
1946
+		$_reverse = false;
1947 1947
 		if (is_numeric($_sort))
1948 1948
 		{
1949
-			switch($_sort) {
1949
+			switch ($_sort) {
1950 1950
 				case 2:
1951 1951
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1952 1952
 					break;
@@ -1968,7 +1968,7 @@  discard block
 block discarded – undo
1968 1968
 		}
1969 1969
 		else
1970 1970
 		{
1971
-			switch(strtoupper($_sort)) {
1971
+			switch (strtoupper($_sort)) {
1972 1972
 				case 'FROMADDRESS':
1973 1973
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1974 1974
 					break;
@@ -1994,7 +1994,7 @@  discard block
 block discarded – undo
1994 1994
 					break;
1995 1995
 			}
1996 1996
 		}
1997
-		if ($_reverse) array_unshift($retValue,Horde_Imap_Client::SORT_REVERSE);
1997
+		if ($_reverse) array_unshift($retValue, Horde_Imap_Client::SORT_REVERSE);
1998 1998
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.($_reverse?'REVERSE ':'').$_sort.'->'.$retValue);
1999 1999
 		return $retValue;
2000 2000
 	}
@@ -2007,28 +2007,28 @@  discard block
 block discarded – undo
2007 2007
 	 * @param boolean $_supportsOrInQuery wether to use the OR Query on QuickSearch
2008 2008
 	 * @return Horde_Imap_Client_Search_Query the IMAP filter
2009 2009
 	 */
2010
-	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery=true)
2010
+	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery = true)
2011 2011
 	{
2012 2012
 		$imapFilter = new Horde_Imap_Client_Search_Query();
2013 2013
 		$imapFilter->charset('UTF-8');
2014 2014
 
2015 2015
 		//_debug_array($_criterias);
2016
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2017
-		if((!is_array($_criterias) || $_criterias['status']=='any') &&
2016
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias) ? " none -> returning" : array2string($_criterias)));
2017
+		if ((!is_array($_criterias) || $_criterias['status'] == 'any') &&
2018 2018
 			(!isset($_criterias['string']) || empty($_criterias['string'])) &&
2019
-			(!isset($_criterias['range'])|| empty($_criterias['range']) ||
2020
-			( !empty($_criterias['range'])&& ($_criterias['range']!='BETWEEN' && empty($_criterias['date'])||
2021
-			($_criterias['range']=='BETWEEN' && empty($_criterias['since'])&& empty($_criterias['before']))))))
2019
+			(!isset($_criterias['range']) || empty($_criterias['range']) ||
2020
+			(!empty($_criterias['range']) && ($_criterias['range'] != 'BETWEEN' && empty($_criterias['date']) ||
2021
+			($_criterias['range'] == 'BETWEEN' && empty($_criterias['since']) && empty($_criterias['before']))))))
2022 2022
 		{
2023 2023
 			//error_log(__METHOD__.' ('.__LINE__.') returning early Criterias:'.print_r($_criterias, true));
2024
-			$imapFilter->flag('DELETED', $set=false);
2024
+			$imapFilter->flag('DELETED', $set = false);
2025 2025
 			return $imapFilter;
2026 2026
 		}
2027 2027
 		$queryValid = false;
2028 2028
 		// statusQuery MUST be placed first, as search for subject/mailbody and such is
2029 2029
 		// depending on charset. flagSearch is not BUT messes the charset if called afterwards
2030 2030
 		$statusQueryValid = false;
2031
-		foreach((array)$_criterias['status'] as $k => $criteria) {
2031
+		foreach ((array)$_criterias['status'] as $k => $criteria) {
2032 2032
 			$imapStatusFilter = new Horde_Imap_Client_Search_Query();
2033 2033
 			$imapStatusFilter->charset('UTF-8');
2034 2034
 			$criteria = strtoupper($criteria);
@@ -2038,12 +2038,12 @@  discard block
 block discarded – undo
2038 2038
 				case 'FLAGGED':
2039 2039
 				case 'RECENT':
2040 2040
 				case 'SEEN':
2041
-					$imapStatusFilter->flag($criteria, $set=true);
2042
-					$queryValid = $statusQueryValid =true;
2041
+					$imapStatusFilter->flag($criteria, $set = true);
2042
+					$queryValid = $statusQueryValid = true;
2043 2043
 					break;
2044 2044
 				case 'READ':
2045
-					$imapStatusFilter->flag('SEEN', $set=true);
2046
-					$queryValid = $statusQueryValid =true;
2045
+					$imapStatusFilter->flag('SEEN', $set = true);
2046
+					$queryValid = $statusQueryValid = true;
2047 2047
 					break;
2048 2048
 				case 'LABEL1':
2049 2049
 				case 'KEYWORD1':
@@ -2055,38 +2055,38 @@  discard block
 block discarded – undo
2055 2055
 				case 'KEYWORD4':
2056 2056
 				case 'LABEL5':
2057 2057
 				case 'KEYWORD5':
2058
-					$imapStatusFilter->flag(str_ireplace('KEYWORD','$LABEL',$criteria), $set=true);
2059
-					$queryValid = $statusQueryValid =true;
2058
+					$imapStatusFilter->flag(str_ireplace('KEYWORD', '$LABEL', $criteria), $set = true);
2059
+					$queryValid = $statusQueryValid = true;
2060 2060
 					break;
2061 2061
 				case 'NEW':
2062
-					$imapStatusFilter->flag('RECENT', $set=true);
2063
-					$imapStatusFilter->flag('SEEN', $set=false);
2064
-					$queryValid = $statusQueryValid =true;
2062
+					$imapStatusFilter->flag('RECENT', $set = true);
2063
+					$imapStatusFilter->flag('SEEN', $set = false);
2064
+					$queryValid = $statusQueryValid = true;
2065 2065
 					break;
2066 2066
 				case 'OLD':
2067
-					$imapStatusFilter->flag('RECENT', $set=false);
2068
-					$queryValid = $statusQueryValid =true;
2067
+					$imapStatusFilter->flag('RECENT', $set = false);
2068
+					$queryValid = $statusQueryValid = true;
2069 2069
 					break;
2070 2070
 // operate only on system flags
2071 2071
 //        $systemflags = array(
2072 2072
 //            'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'RECENT', 'SEEN'
2073 2073
 //        );
2074 2074
 				case 'UNANSWERED':
2075
-					$imapStatusFilter->flag('ANSWERED', $set=false);
2076
-					$queryValid = $statusQueryValid =true;
2075
+					$imapStatusFilter->flag('ANSWERED', $set = false);
2076
+					$queryValid = $statusQueryValid = true;
2077 2077
 					break;
2078 2078
 				case 'UNDELETED':
2079
-					$imapFilter->flag('DELETED', $set=false);
2079
+					$imapFilter->flag('DELETED', $set = false);
2080 2080
 					$queryValid = true;
2081 2081
 					break;
2082 2082
 				case 'UNFLAGGED':
2083
-					$imapStatusFilter->flag('FLAGGED', $set=false);
2084
-					$queryValid = $statusQueryValid =true;
2083
+					$imapStatusFilter->flag('FLAGGED', $set = false);
2084
+					$queryValid = $statusQueryValid = true;
2085 2085
 					break;
2086 2086
 				case 'UNREAD':
2087 2087
 				case 'UNSEEN':
2088
-					$imapStatusFilter->flag('SEEN', $set=false);
2089
-					$queryValid = $statusQueryValid =true;
2088
+					$imapStatusFilter->flag('SEEN', $set = false);
2089
+					$queryValid = $statusQueryValid = true;
2090 2090
 					break;
2091 2091
 				case 'UNLABEL1':
2092 2092
 				case 'UNKEYWORD1':
@@ -2098,8 +2098,8 @@  discard block
 block discarded – undo
2098 2098
 				case 'UNKEYWORD4':
2099 2099
 				case 'UNLABEL5':
2100 2100
 				case 'UNKEYWORD5':
2101
-					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD','UNLABEL'),'$LABEL',$criteria), $set=false);
2102
-					$queryValid = $statusQueryValid =true;
2101
+					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD', 'UNLABEL'), '$LABEL', $criteria), $set = false);
2102
+					$queryValid = $statusQueryValid = true;
2103 2103
 					break;
2104 2104
 				default:
2105 2105
 					$statusQueryValid = false;
@@ -2115,20 +2115,20 @@  discard block
 block discarded – undo
2115 2115
 		$imapSearchFilter = new Horde_Imap_Client_Search_Query();
2116 2116
 		$imapSearchFilter->charset('UTF-8');
2117 2117
 
2118
-		if(!empty($_criterias['string'])) {
2118
+		if (!empty($_criterias['string'])) {
2119 2119
 			$criteria = strtoupper($_criterias['type']);
2120 2120
 			switch ($criteria) {
2121 2121
 				case 'BYDATE':
2122 2122
 				case 'QUICK':
2123 2123
 				case 'QUICKWITHCC':
2124
-					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not=false);
2124
+					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not = false);
2125 2125
 					//$imapSearchFilter->charset('UTF-8');
2126 2126
 					$imapFilter2 = new Horde_Imap_Client_Search_Query();
2127 2127
 					$imapFilter2->charset('UTF-8');
2128
-					if($this->isSentFolder($_folder)) {
2129
-						$imapFilter2->headerText('TO', $_criterias['string'], $not=false);
2128
+					if ($this->isSentFolder($_folder)) {
2129
+						$imapFilter2->headerText('TO', $_criterias['string'], $not = false);
2130 2130
 					} else {
2131
-						$imapFilter2->headerText('FROM', $_criterias['string'], $not=false);
2131
+						$imapFilter2->headerText('FROM', $_criterias['string'], $not = false);
2132 2132
 					}
2133 2133
 					if ($_supportsOrInQuery)
2134 2134
 					{
@@ -2138,31 +2138,31 @@  discard block
 block discarded – undo
2138 2138
 					{
2139 2139
 						$imapSearchFilter->andSearch($imapFilter2);
2140 2140
 					}
2141
-					if ($_supportsOrInQuery && $criteria=='QUICKWITHCC')
2141
+					if ($_supportsOrInQuery && $criteria == 'QUICKWITHCC')
2142 2142
 					{
2143 2143
 						$imapFilter3 = new Horde_Imap_Client_Search_Query();
2144 2144
 						$imapFilter3->charset('UTF-8');
2145
-						$imapFilter3->headerText('CC', $_criterias['string'], $not=false);
2145
+						$imapFilter3->headerText('CC', $_criterias['string'], $not = false);
2146 2146
 						$imapSearchFilter->orSearch($imapFilter3);
2147 2147
 					}
2148 2148
 					$queryValid = true;
2149 2149
 					break;
2150 2150
 				case 'LARGER':
2151 2151
 				case 'SMALLER':
2152
-					if (strlen(trim($_criterias['string'])) != strlen((float) trim($_criterias['string'])))
2152
+					if (strlen(trim($_criterias['string'])) != strlen((float)trim($_criterias['string'])))
2153 2153
 					{
2154 2154
 						//examine string to evaluate size
2155
-						$unit = strtoupper(trim(substr(trim($_criterias['string']),strlen((float) trim($_criterias['string'])))));
2156
-						$multipleBy = array('KB'=>1024,'K'=>1024,
2157
-											'MB'=>1024*1000,'M'=>1024*1000,
2158
-											'GB'=>1024*1000*1000,'G'=>1024*1000*1000,
2159
-											'TB'=>1024*1000*1000*1000,'T'=>1024*1000*1000*1000);
2160
-						$numberinBytes=(float)$_criterias['string'];
2161
-						if (isset($multipleBy[$unit])) $numberinBytes=(float)$_criterias['string']*$multipleBy[$unit];
2155
+						$unit = strtoupper(trim(substr(trim($_criterias['string']), strlen((float)trim($_criterias['string'])))));
2156
+						$multipleBy = array('KB'=>1024, 'K'=>1024,
2157
+											'MB'=>1024 * 1000, 'M'=>1024 * 1000,
2158
+											'GB'=>1024 * 1000 * 1000, 'G'=>1024 * 1000 * 1000,
2159
+											'TB'=>1024 * 1000 * 1000 * 1000, 'T'=>1024 * 1000 * 1000 * 1000);
2160
+						$numberinBytes = (float)$_criterias['string'];
2161
+						if (isset($multipleBy[$unit])) $numberinBytes = (float)$_criterias['string'] * $multipleBy[$unit];
2162 2162
 						//error_log(__METHOD__.__LINE__.'#'.$_criterias['string'].'->'.(float)$_criterias['string'].'#'.$unit.' ='.$numberinBytes);
2163
-						$_criterias['string']=$numberinBytes;
2163
+						$_criterias['string'] = $numberinBytes;
2164 2164
 					}
2165
-					$imapSearchFilter->size( $_criterias['string'], ($criteria=='LARGER'?true:false), $not=false);
2165
+					$imapSearchFilter->size($_criterias['string'], ($criteria == 'LARGER' ? true : false), $not = false);
2166 2166
 					//$imapSearchFilter->charset('UTF-8');
2167 2167
 					$queryValid = true;
2168 2168
 					break;
@@ -2171,31 +2171,31 @@  discard block
 block discarded – undo
2171 2171
 				case 'CC':
2172 2172
 				case 'BCC':
2173 2173
 				case 'SUBJECT':
2174
-					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not=false);
2174
+					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not = false);
2175 2175
 					//$imapSearchFilter->charset('UTF-8');
2176 2176
 					$queryValid = true;
2177 2177
 					break;
2178 2178
 				case 'BODY':
2179 2179
 				case 'TEXT':
2180
-					$imapSearchFilter->text($_criterias['string'],($criteria=='BODY'?true:false), $not=false);
2180
+					$imapSearchFilter->text($_criterias['string'], ($criteria == 'BODY' ? true : false), $not = false);
2181 2181
 					//$imapSearchFilter->charset('UTF-8');
2182 2182
 					$queryValid = true;
2183 2183
 					break;
2184 2184
 				case 'SINCE':
2185
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2185
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2186 2186
 					$queryValid = true;
2187 2187
 					break;
2188 2188
 				case 'BEFORE':
2189
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2189
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2190 2190
 					$queryValid = true;
2191 2191
 					break;
2192 2192
 				case 'ON':
2193
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2193
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2194 2194
 					$queryValid = true;
2195 2195
 					break;
2196 2196
 			}
2197 2197
 		}
2198
-		if ($statusQueryValid && !$queryValid) $queryValid=true;
2198
+		if ($statusQueryValid && !$queryValid) $queryValid = true;
2199 2199
 		if ($queryValid) $imapFilter->andSearch($imapSearchFilter);
2200 2200
 
2201 2201
 		if (isset($_criterias['range']) && !empty($_criterias['range']))
@@ -2204,12 +2204,12 @@  discard block
 block discarded – undo
2204 2204
 			$imapRangeFilter = new Horde_Imap_Client_Search_Query();
2205 2205
 			$imapRangeFilter->charset('UTF-8');
2206 2206
 			$criteria = strtoupper($_criterias['range']);
2207
-			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since']==$_criterias['before'])
2207
+			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since'] == $_criterias['before'])
2208 2208
 			{
2209
-				$_criterias['date']=$_criterias['since'];
2209
+				$_criterias['date'] = $_criterias['since'];
2210 2210
 				unset($_criterias['since']);
2211 2211
 				unset($_criterias['before']);
2212
-				$criteria=$_criterias['range']='ON';
2212
+				$criteria = $_criterias['range'] = 'ON';
2213 2213
 			}
2214 2214
 			switch ($criteria) {
2215 2215
 				case 'BETWEEN':
@@ -2217,7 +2217,7 @@  discard block
 block discarded – undo
2217 2217
 					//enddate
2218 2218
 					if ($_criterias['since'])
2219 2219
 					{
2220
-						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2220
+						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2221 2221
 						$rangeValid = true;
2222 2222
 					}
2223 2223
 					//startdate
@@ -2226,28 +2226,28 @@  discard block
 block discarded – undo
2226 2226
 						$imapRangeFilter2 = new Horde_Imap_Client_Search_Query();
2227 2227
 						$imapRangeFilter2->charset('UTF-8');
2228 2228
 						//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2229
-						$_criterias['before'] = date("d-M-Y",DateTime::to($_criterias['before'],'ts')+(3600*24));
2230
-						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2229
+						$_criterias['before'] = date("d-M-Y", DateTime::to($_criterias['before'], 'ts') + (3600 * 24));
2230
+						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2231 2231
 						$imapRangeFilter->andSearch($imapRangeFilter2);
2232 2232
 						$rangeValid = true;
2233 2233
 					}
2234 2234
 					break;
2235 2235
 				case 'SINCE'://enddate
2236
-					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since']?$_criterias['since']:$_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2236
+					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since'] ? $_criterias['since'] : $_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2237 2237
 					$rangeValid = true;
2238 2238
 					break;
2239 2239
 				case 'BEFORE'://startdate
2240 2240
 					//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2241
-					$_criterias['before'] = date("d-M-Y",DateTime::to(($_criterias['before']?$_criterias['before']:$_criterias['date']),'ts')+(3600*24));
2242
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2241
+					$_criterias['before'] = date("d-M-Y", DateTime::to(($_criterias['before'] ? $_criterias['before'] : $_criterias['date']), 'ts') + (3600 * 24));
2242
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2243 2243
 					$rangeValid = true;
2244 2244
 					break;
2245 2245
 				case 'ON':
2246
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2246
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2247 2247
 					$rangeValid = true;
2248 2248
 					break;
2249 2249
 			}
2250
-			if ($rangeValid && !$queryValid) $queryValid=true;
2250
+			if ($rangeValid && !$queryValid) $queryValid = true;
2251 2251
 			if ($rangeValid) $imapFilter->andSearch($imapRangeFilter);
2252 2252
 		}
2253 2253
 		if (self::$debug)
@@ -2256,8 +2256,8 @@  discard block
 block discarded – undo
2256 2256
 			$query_str = $imapFilter->build();
2257 2257
 			//error_log(__METHOD__.' ('.__LINE__.') '.' '.$query_str['query'].' created by Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2258 2258
 		}
2259
-		if($queryValid==false) {
2260
-			$imapFilter->flag('DELETED', $set=false);
2259
+		if ($queryValid == false) {
2260
+			$imapFilter->flag('DELETED', $set = false);
2261 2261
 			return $imapFilter;
2262 2262
 		} else {
2263 2263
 			return $imapFilter;
@@ -2271,11 +2271,11 @@  discard block
 block discarded – undo
2271 2271
 	 * @param  mixed/boolean $_tryIDNConversion (true/false AND FORCE): try IDN Conversion on domainparts of emailADRESSES
2272 2272
 	 * @return mixed - based on the input type
2273 2273
 	 */
2274
-	static function decode_header($_string, $_tryIDNConversion=false)
2274
+	static function decode_header($_string, $_tryIDNConversion = false)
2275 2275
 	{
2276 2276
 		if (is_array($_string))
2277 2277
 		{
2278
-			foreach($_string as $k=>$v)
2278
+			foreach ($_string as $k=>$v)
2279 2279
 			{
2280 2280
 				$_string[$k] = self::decode_header($v, $_tryIDNConversion);
2281 2281
 			}
@@ -2283,18 +2283,18 @@  discard block
 block discarded – undo
2283 2283
 		}
2284 2284
 		else
2285 2285
 		{
2286
-			$_string = Mail\Html::decodeMailHeader($_string,self::$displayCharset);
2286
+			$_string = Mail\Html::decodeMailHeader($_string, self::$displayCharset);
2287 2287
 			$test = @json_encode($_string);
2288 2288
 			//error_log(__METHOD__.__LINE__.' ->'.strlen($singleBodyPart['body']).' Error:'.json_last_error().'<- BodyPart:#'.$test.'#');
2289
-			if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2289
+			if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2290 2290
 			{
2291 2291
 				// try to fix broken utf8
2292 2292
 				$x = utf8_encode($_string);
2293 2293
 				$test = @json_encode($x);
2294
-				if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2294
+				if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2295 2295
 				{
2296 2296
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
2297
-					$_string = (function_exists('mb_convert_encoding')?mb_convert_encoding($_string,'UTF-8','UTF-8'):(function_exists('iconv')?@iconv("UTF-8","UTF-8//IGNORE",$_string):$_string));
2297
+					$_string = (function_exists('mb_convert_encoding') ? mb_convert_encoding($_string, 'UTF-8', 'UTF-8') : (function_exists('iconv') ? @iconv("UTF-8", "UTF-8//IGNORE", $_string) : $_string));
2298 2298
 				}
2299 2299
 				else
2300 2300
 				{
@@ -2302,7 +2302,7 @@  discard block
 block discarded – undo
2302 2302
 				}
2303 2303
 			}
2304 2304
 
2305
-			if ($_tryIDNConversion===true && stripos($_string,'@')!==false)
2305
+			if ($_tryIDNConversion === true && stripos($_string, '@') !== false)
2306 2306
 			{
2307 2307
 				$rfcAddr = self::parseAddressList($_string);
2308 2308
 				$stringA = array();
@@ -2314,11 +2314,11 @@  discard block
 block discarded – undo
2314 2314
 						$stringA = array();
2315 2315
 						break; // skip idna conversion if we encounter an error here
2316 2316
 					}
2317
-					$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox,Horde_Idna::decode($_rfcAddr->host),$_rfcAddr->personal);
2317
+					$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox, Horde_Idna::decode($_rfcAddr->host), $_rfcAddr->personal);
2318 2318
 				}
2319
-				if (!empty($stringA)) $_string = implode(',',$stringA);
2319
+				if (!empty($stringA)) $_string = implode(',', $stringA);
2320 2320
 			}
2321
-			if ($_tryIDNConversion==='FORCE')
2321
+			if ($_tryIDNConversion === 'FORCE')
2322 2322
 			{
2323 2323
 				//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_string.'='.Horde_Idna::decode($_string));
2324 2324
 				$_string = Horde_Idna::decode($_string);
@@ -2334,17 +2334,17 @@  discard block
 block discarded – undo
2334 2334
 	 * @param  boolean $decode try decoding
2335 2335
 	 * @return mixed - based on the input type
2336 2336
 	 */
2337
-	function decode_subject($_string,$decode=true)
2337
+	function decode_subject($_string, $decode = true)
2338 2338
 	{
2339 2339
 		#$string = $_string;
2340
-		if($_string=='NIL')
2340
+		if ($_string == 'NIL')
2341 2341
 		{
2342 2342
 			return 'No Subject';
2343 2343
 		}
2344 2344
 		if ($decode) $_string = self::decode_header($_string);
2345 2345
 		// make sure its utf-8
2346 2346
 		$test = @json_encode($_string);
2347
-		if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2347
+		if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2348 2348
 		{
2349 2349
 			$_string = utf8_encode($_string);
2350 2350
 		}
@@ -2396,18 +2396,18 @@  discard block
 block discarded – undo
2396 2396
 	function createFolder($_parent, $_folderName, &$_error)
2397 2397
 	{
2398 2398
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."->"."$_parent, $_folderName called from:".function_backtrace());
2399
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2400
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2399
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2400
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2401 2401
 
2402
-		if(empty($parent)) {
2402
+		if (empty($parent)) {
2403 2403
 			$newFolderName = $folderName;
2404 2404
 		} else {
2405 2405
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2406
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2406
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2407 2407
 		}
2408 2408
 		if (empty($newFolderName)) return false;
2409 2409
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.'->'.$newFolderName);
2410
-		if ($this->folderExists($newFolderName,true))
2410
+		if ($this->folderExists($newFolderName, true))
2411 2411
 		{
2412 2412
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." Folder $newFolderName already exists.");
2413 2413
 			return $newFolderName;
@@ -2424,7 +2424,7 @@  discard block
 block discarded – undo
2424 2424
 		}
2425 2425
 		catch (\Exception $e)
2426 2426
 		{
2427
-			$_error = lang('Could not create Folder %1 Reason: %2',$newFolderName,$e->getMessage());
2427
+			$_error = lang('Could not create Folder %1 Reason: %2', $newFolderName, $e->getMessage());
2428 2428
 			error_log(__METHOD__.' ('.__LINE__.') '.' create Folder '.$newFolderName.'->'.$e->getMessage().' ('.$e->details.') Namespace:'.array2string($this->icServer->getNameSpaces()).function_backtrace());
2429 2429
 			return false;
2430 2430
 		}
@@ -2453,15 +2453,15 @@  discard block
 block discarded – undo
2453 2453
 	 */
2454 2454
 	function renameFolder($_oldFolderName, $_parent, $_folderName)
2455 2455
 	{
2456
-		$oldFolderName	= $_oldFolderName;//$this->_encodeFolderName($_oldFolderName);
2457
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2458
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2456
+		$oldFolderName = $_oldFolderName; //$this->_encodeFolderName($_oldFolderName);
2457
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2458
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2459 2459
 
2460
-		if(empty($parent)) {
2460
+		if (empty($parent)) {
2461 2461
 			$newFolderName = $folderName;
2462 2462
 		} else {
2463 2463
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2464
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2464
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2465 2465
 		}
2466 2466
 		if (self::$debug) error_log("create folder: $newFolderName");
2467 2467
 		try
@@ -2470,10 +2470,10 @@  discard block
 block discarded – undo
2470 2470
 		}
2471 2471
 		catch (\Exception $e)
2472 2472
 		{
2473
-			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage());;
2473
+			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage()); ;
2474 2474
 		}
2475 2475
 		// clear FolderExistsInfoCache
2476
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2476
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2477 2477
 
2478 2478
 		return $newFolderName;
2479 2479
 
@@ -2492,15 +2492,15 @@  discard block
 block discarded – undo
2492 2492
 		//$folderName = $this->_encodeFolderName($_folderName);
2493 2493
 		try
2494 2494
 		{
2495
-			$this->icServer->subscribeMailbox($_folderName,false);
2495
+			$this->icServer->subscribeMailbox($_folderName, false);
2496 2496
 			$this->icServer->deleteMailbox($_folderName);
2497 2497
 		}
2498 2498
 		catch (\Exception $e)
2499 2499
 		{
2500
-			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage());;
2500
+			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage()); ;
2501 2501
 		}
2502 2502
 		// clear FolderExistsInfoCache
2503
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2503
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2504 2504
 
2505 2505
 		return true;
2506 2506
 	}
@@ -2535,10 +2535,10 @@  discard block
 block discarded – undo
2535 2535
 	 *
2536 2536
 	 * @return array with folder objects. eg.: INBOX => {inbox object}
2537 2537
 	 */
2538
-	function getFolderObjects($_subscribedOnly=false, $_getCounters=false, $_alwaysGetDefaultFolders=false,$_useCacheIfPossible=true)
2538
+	function getFolderObjects($_subscribedOnly = false, $_getCounters = false, $_alwaysGetDefaultFolders = false, $_useCacheIfPossible = true)
2539 2539
 	{
2540 2540
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' ServerID:'.$this->icServer->ImapServerId.", subscribedOnly:$_subscribedOnly, getCounters:$_getCounters, alwaysGetDefaultFolders:$_alwaysGetDefaultFolders, _useCacheIfPossible:$_useCacheIfPossible");
2541
-		if (self::$debugTimes) $starttime = microtime (true);
2541
+		if (self::$debugTimes) $starttime = microtime(true);
2542 2542
 		static $folders2return;
2543 2543
 		//$_subscribedOnly=false;
2544 2544
 		// always use static on single request if info is available;
@@ -2546,42 +2546,42 @@  discard block
 block discarded – undo
2546 2546
 		// set $_useCacheIfPossible to false !
2547 2547
 		if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2548 2548
 		{
2549
-			if (self::$debugTimes) self::logRunTimes($starttime,null,'using static',__METHOD__.' ('.__LINE__.') ');
2549
+			if (self::$debugTimes) self::logRunTimes($starttime, null, 'using static', __METHOD__.' ('.__LINE__.') ');
2550 2550
 			return $folders2return[$this->icServer->ImapServerId];
2551 2551
 		}
2552 2552
 
2553
-		if ($_subscribedOnly && $_getCounters===false)
2553
+		if ($_subscribedOnly && $_getCounters === false)
2554 2554
 		{
2555
-			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2555
+			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
2556 2556
 			if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2557 2557
 			{
2558 2558
 				//error_log(__METHOD__.' ('.__LINE__.') '.' using Cached folderObjects'.array2string($folders2return[$this->icServer->ImapServerId]));
2559
-				if (self::$debugTimes) self::logRunTimes($starttime,null,'from Cache',__METHOD__.' ('.__LINE__.') ');
2559
+				if (self::$debugTimes) self::logRunTimes($starttime, null, 'from Cache', __METHOD__.' ('.__LINE__.') ');
2560 2560
 				return $folders2return[$this->icServer->ImapServerId];
2561 2561
 			}
2562 2562
 		}
2563 2563
 		// use $folderBasicInfo for holding attributes and other basic folderinfo $folderBasicInfo[$this->icServer->ImapServerId]
2564 2564
 		static $folderBasicInfo;
2565
-		if (is_null($folderBasicInfo)||!isset($folderBasicInfo[$this->icServer->ImapServerId])) $folderBasicInfo = Cache::getCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2565
+		if (is_null($folderBasicInfo) || !isset($folderBasicInfo[$this->icServer->ImapServerId])) $folderBasicInfo = Cache::getCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
2566 2566
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($folderBasicInfo[$this->icServer->ImapServerId])));
2567 2567
 
2568 2568
 		$delimiter = $this->getHierarchyDelimiter();
2569 2569
 
2570 2570
 		$inboxData = new \stdClass;
2571
-		$inboxData->name 		= 'INBOX';
2571
+		$inboxData->name = 'INBOX';
2572 2572
 		$inboxData->folderName		= 'INBOX';
2573
-		$inboxData->displayName		= lang('INBOX');
2573
+		$inboxData->displayName = lang('INBOX');
2574 2574
 		$inboxData->delimiter 		= $delimiter;
2575
-		$inboxData->shortFolderName	= 'INBOX';
2576
-		$inboxData->shortDisplayName	= lang('INBOX');
2575
+		$inboxData->shortFolderName = 'INBOX';
2576
+		$inboxData->shortDisplayName = lang('INBOX');
2577 2577
 		$inboxData->subscribed = true;
2578
-		if($_getCounters == true) {
2578
+		if ($_getCounters == true) {
2579 2579
 			$inboxData->counter = $this->getMailBoxCounters('INBOX');
2580 2580
 		}
2581 2581
 		// force unsubscribed by preference showAllFoldersInFolderPane
2582 2582
 		if ($_subscribedOnly == true &&
2583 2583
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2584
-			$this->mailPreferences['showAllFoldersInFolderPane']==1)
2584
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1)
2585 2585
 		{
2586 2586
 			$_subscribedOnly = false;
2587 2587
 		}
@@ -2594,12 +2594,12 @@  discard block
 block discarded – undo
2594 2594
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2595 2595
 		if (is_array($nameSpace))
2596 2596
 		{
2597
-			foreach($nameSpace as $k => $singleNameSpace) {
2597
+			foreach ($nameSpace as $k => $singleNameSpace) {
2598 2598
 				$type = $singleNameSpace['type'];
2599 2599
 				// the following line (assumption that for the same namespace the delimiter should be equal) may be wrong
2600
-				$foldersNameSpace[$type]['delimiter']  = $singleNameSpace['delimiter'];
2600
+				$foldersNameSpace[$type]['delimiter'] = $singleNameSpace['delimiter'];
2601 2601
 
2602
-				if(is_array($singleNameSpace)&&$fetchedAllInOneGo==false) {
2602
+				if (is_array($singleNameSpace) && $fetchedAllInOneGo == false) {
2603 2603
 					// fetch and sort the subscribed folders
2604 2604
 					// we alway fetch the subscribed, as this provides the only way to tell
2605 2605
 					// if a folder is subscribed or not
@@ -2607,22 +2607,22 @@  discard block
 block discarded – undo
2607 2607
 					{
2608 2608
 						try
2609 2609
 						{
2610
-							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('',0,true);
2610
+							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('', 0, true);
2611 2611
 							if (!empty($subscribedMailboxes))
2612 2612
 							{
2613 2613
 								$fetchedAllInOneGo = true;
2614 2614
 							}
2615 2615
 							else
2616 2616
 							{
2617
-								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'],0,true);
2617
+								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'], 0, true);
2618 2618
 							}
2619 2619
 						}
2620
-						catch(Exception $e)
2620
+						catch (Exception $e)
2621 2621
 						{
2622 2622
 							continue;
2623 2623
 						}
2624 2624
 						//echo "subscribedMailboxes";_debug_array($subscribedMailboxes);
2625
-						$subscribedFoldersPerNS = (!empty($subscribedMailboxes)?array_keys($subscribedMailboxes):array());
2625
+						$subscribedFoldersPerNS = (!empty($subscribedMailboxes) ? array_keys($subscribedMailboxes) : array());
2626 2626
 						//if (is_array($foldersNameSpace[$type]['subscribed'])) sort($foldersNameSpace[$type]['subscribed']);
2627 2627
 						//_debug_array($foldersNameSpace);
2628 2628
 						//error_log(__METHOD__.__LINE__.array2string($singleNameSpace).':#:'.array2string($subscribedFoldersPerNS));
@@ -2632,18 +2632,18 @@  discard block
 block discarded – undo
2632 2632
 							foreach ($subscribedMailboxes as $k => $finfo)
2633 2633
 							{
2634 2634
 								//error_log(__METHOD__.__LINE__.$k.':#:'.array2string($finfo));
2635
-								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k]=
2636
-								$folderBasicInfo[$this->icServer->ImapServerId][$k]=array(
2635
+								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k] =
2636
+								$folderBasicInfo[$this->icServer->ImapServerId][$k] = array(
2637 2637
 									'MAILBOX'=>$finfo['MAILBOX'],
2638 2638
 									'ATTRIBUTES'=>$finfo['ATTRIBUTES'],
2639
-									'delimiter'=>$finfo['delimiter'],//lowercase for some reason???
2640
-									'SUBSCRIBED'=>$finfo['SUBSCRIBED'],//seeded by getMailboxes
2639
+									'delimiter'=>$finfo['delimiter'], //lowercase for some reason???
2640
+									'SUBSCRIBED'=>$finfo['SUBSCRIBED'], //seeded by getMailboxes
2641 2641
 								);
2642
-								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k,$foldersNameSpace[$type]['subscribed']))
2642
+								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k, $foldersNameSpace[$type]['subscribed']))
2643 2643
 								{
2644 2644
 									$foldersNameSpace[$type]['subscribed'][] = $k;
2645 2645
 								}
2646
-								if (empty($foldersNameSpace[$type]['all']) || !in_array($k,$foldersNameSpace[$type]['all']))
2646
+								if (empty($foldersNameSpace[$type]['all']) || !in_array($k, $foldersNameSpace[$type]['all']))
2647 2647
 								{
2648 2648
 									$foldersNameSpace[$type]['all'][] = $k;
2649 2649
 								}
@@ -2666,7 +2666,7 @@  discard block
 block discarded – undo
2666 2666
 						// that may produce problems, when encountering recursions probably
2667 2667
 						// horde is handling that, so we do not; keep that in mind!
2668 2668
 						//$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],2,true);
2669
-						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],0,true);
2669
+						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'], 0, true);
2670 2670
 					}
2671 2671
 					catch (\Exception $e)
2672 2672
 					{
@@ -2684,26 +2684,26 @@  discard block
 block discarded – undo
2684 2684
 					foreach ($allMailboxesExt as $mbx) {
2685 2685
 						if (!isset($folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2686 2686
 						{
2687
-							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]=array(
2687
+							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']] = array(
2688 2688
 								'MAILBOX'=>$mbx['MAILBOX'],
2689 2689
 								'ATTRIBUTES'=>$mbx['ATTRIBUTES'],
2690
-								'delimiter'=>$mbx['delimiter'],//lowercase for some reason???
2691
-								'SUBSCRIBED'=>$mbx['SUBSCRIBED'],//seeded by getMailboxes
2690
+								'delimiter'=>$mbx['delimiter'], //lowercase for some reason???
2691
+								'SUBSCRIBED'=>$mbx['SUBSCRIBED'], //seeded by getMailboxes
2692 2692
 							);
2693 2693
 							if ($mbx['SUBSCRIBED'] && !isset($subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2694 2694
 							{
2695 2695
 								$subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']] = $folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']];
2696 2696
 							}
2697 2697
 						}
2698
-						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'],$foldersNameSpace[$type]['subscribed'])))
2698
+						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'], $foldersNameSpace[$type]['subscribed'])))
2699 2699
 						{
2700 2700
 							$foldersNameSpace[$type]['subscribed'][] = $mbx['MAILBOX'];
2701 2701
 						}
2702 2702
 						//echo __METHOD__;_debug_array($mbx);
2703 2703
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
2704
-						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']])||
2705
-							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']])||
2706
-							(substr($mbx['MAILBOX'],-1)==$foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'],0,-1)]))
2704
+						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']]) ||
2705
+							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']]) ||
2706
+							(substr($mbx['MAILBOX'], -1) == $foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'], 0, -1)]))
2707 2707
 						) continue;
2708 2708
 
2709 2709
 						//echo '#'.$mbx['MAILBOX'].':'.array2string($mbx)."#<br>";
@@ -2713,7 +2713,7 @@  discard block
 block discarded – undo
2713 2713
 					//_debug_array(array_keys($allMailBoxesExtSorted));
2714 2714
 					$allMailboxes = array();
2715 2715
 					foreach ((array)$allMailBoxesExtSorted as $mbx) {
2716
-						if (!in_array($mbx['MAILBOX'],$allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2716
+						if (!in_array($mbx['MAILBOX'], $allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2717 2717
 						//echo "Result:";_debug_array($allMailboxes);
2718 2718
 					}
2719 2719
 					$foldersNameSpace[$type]['all'] = $allMailboxes;
@@ -2722,57 +2722,57 @@  discard block
 block discarded – undo
2722 2722
 			}
2723 2723
 		}
2724 2724
 		//subscribed folders may be used in getFolderStatus
2725
-		Cache::setCache(Cache::INSTANCE,'email','subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$subscribedFoldersForCache,$expiration=60*60*1);
2725
+		Cache::setCache(Cache::INSTANCE, 'email', 'subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $subscribedFoldersForCache, $expiration = 60 * 60 * 1);
2726 2726
 		//echo "<br>FolderNameSpace To Process:";_debug_array($foldersNameSpace);
2727 2727
 		$autoFolderObjects = $folders = array();
2728 2728
 		$autofolder_exists = array();
2729
-		foreach( array('personal', 'others', 'shared') as $type) {
2730
-			if(isset($foldersNameSpace[$type])) {
2731
-				if($_subscribedOnly) {
2732
-					if( !empty($foldersNameSpace[$type]['subscribed']) ) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2729
+		foreach (array('personal', 'others', 'shared') as $type) {
2730
+			if (isset($foldersNameSpace[$type])) {
2731
+				if ($_subscribedOnly) {
2732
+					if (!empty($foldersNameSpace[$type]['subscribed'])) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2733 2733
 				} else {
2734
-					if( !empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2734
+					if (!empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2735 2735
 				}
2736
-				foreach((array)$listOfFolders as $folderName) {
2736
+				foreach ((array)$listOfFolders as $folderName) {
2737 2737
 					//echo "<br>FolderToCheck:$folderName<br>";
2738 2738
 					//error_log(__METHOD__.__LINE__.'#Delimiter:'.$delimiter.':#'.$folderName);
2739
-					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue;//when subscribedonly, we fetch all folders in one go.
2740
-					if($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all'])||in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2739
+					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue; //when subscribedonly, we fetch all folders in one go.
2740
+					if ($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all']) || in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2741 2741
 						#echo "$folderName failed to be here <br>";
2742 2742
 						continue;
2743 2743
 					}
2744 2744
 					if (isset($folders[$folderName])) continue;
2745 2745
 					if (isset($autoFolderObjects[$folderName])) continue;
2746
-					if (empty($delimiter)||$delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2746
+					if (empty($delimiter) || $delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2747 2747
 					$folderParts = explode($delimiter, $folderName);
2748 2748
 					$shortName = array_pop($folderParts);
2749 2749
 
2750 2750
 					$folderObject = new \stdClass;
2751
-					$folderObject->delimiter	= $delimiter;
2752
-					$folderObject->folderName	= $folderName;
2753
-					$folderObject->shortFolderName	= $shortName;
2754
-					if(!$_subscribedOnly) {
2751
+					$folderObject->delimiter = $delimiter;
2752
+					$folderObject->folderName = $folderName;
2753
+					$folderObject->shortFolderName = $shortName;
2754
+					if (!$_subscribedOnly) {
2755 2755
 						#echo $folderName."->".$type."<br>";
2756 2756
 						#_debug_array($foldersNameSpace[$type]['subscribed']);
2757 2757
 						$folderObject->subscribed = in_array($folderName, (array)$foldersNameSpace[$type]['subscribed']);
2758 2758
 					}
2759 2759
 
2760
-					if($_getCounters == true) {
2760
+					if ($_getCounters == true) {
2761 2761
 						//error_log(__METHOD__.' ('.__LINE__.') '.' getCounter forFolder:'.$folderName);
2762 2762
 						$folderObject->counter = $this->getMailBoxCounters($folderName);
2763 2763
 					}
2764
-					if(strtoupper($folderName) == 'INBOX') {
2764
+					if (strtoupper($folderName) == 'INBOX') {
2765 2765
 						$folderName = 'INBOX';
2766
-						$folderObject->folderName	= 'INBOX';
2767
-						$folderObject->shortFolderName	= 'INBOX';
2768
-						$folderObject->displayName	= lang('INBOX');
2766
+						$folderObject->folderName = 'INBOX';
2767
+						$folderObject->shortFolderName = 'INBOX';
2768
+						$folderObject->displayName = lang('INBOX');
2769 2769
 						$folderObject->shortDisplayName = lang('INBOX');
2770
-						$folderObject->subscribed	= true;
2770
+						$folderObject->subscribed = true;
2771 2771
 					// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
2772
-					} elseif (in_array($shortName,self::$autoFolders)) {
2773
-						$tmpfolderparts = explode($delimiter,$folderObject->folderName);
2772
+					} elseif (in_array($shortName, self::$autoFolders)) {
2773
+						$tmpfolderparts = explode($delimiter, $folderObject->folderName);
2774 2774
 						array_pop($tmpfolderparts);
2775
-						$folderObject->displayName = implode($delimiter,$tmpfolderparts).$delimiter.lang($shortName);
2775
+						$folderObject->displayName = implode($delimiter, $tmpfolderparts).$delimiter.lang($shortName);
2776 2776
 						$folderObject->shortDisplayName = lang($shortName);
2777 2777
 						unset($tmpfolderparts);
2778 2778
 					} else {
@@ -2780,13 +2780,13 @@  discard block
 block discarded – undo
2780 2780
 						$folderObject->shortDisplayName = $shortName;
2781 2781
 					}
2782 2782
 					//$folderName = $folderName;
2783
-					if (in_array($shortName,self::$autoFolders)&&self::searchValueInFolderObjects($shortName,$autoFolderObjects)===false) {
2783
+					if (in_array($shortName, self::$autoFolders) && self::searchValueInFolderObjects($shortName, $autoFolderObjects) === false) {
2784 2784
 						$autoFolderObjects[$folderName] = $folderObject;
2785 2785
 					} else {
2786 2786
 						$folders[$folderName] = $folderObject;
2787 2787
 					}
2788 2788
 					//error_log(__METHOD__.' ('.__LINE__.') '.':'.$folderObject->folderName);
2789
-					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders ();
2789
+					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders();
2790 2790
 					if (isset(self::$specialUseFolders[$folderName]))
2791 2791
 					{
2792 2792
 						$autofolder_exists[$folderName] = self::$specialUseFolders[$folderName];
@@ -2795,27 +2795,27 @@  discard block
 block discarded – undo
2795 2795
 			}
2796 2796
 		}
2797 2797
 		if (is_array($autoFolderObjects) && !empty($autoFolderObjects)) {
2798
-			uasort($autoFolderObjects,array($this,"sortByAutoFolderPos"));
2798
+			uasort($autoFolderObjects, array($this, "sortByAutoFolderPos"));
2799 2799
 		}
2800 2800
 		// check if some standard folders are missing and need to be created
2801 2801
 		if (count($autofolder_exists) < count(self::$autoFolders) && $this->check_create_autofolders($autofolder_exists))
2802 2802
 		{
2803 2803
 			// if new folders have been created, re-read folders ignoring the cache
2804
-			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false);	// false = do NOT use cache
2804
+			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false); // false = do NOT use cache
2805 2805
 		}
2806
-		if (is_array($folders)) uasort($folders,array($this,"sortByDisplayName"));
2806
+		if (is_array($folders)) uasort($folders, array($this, "sortByDisplayName"));
2807 2807
 		//$folders2return = array_merge($autoFolderObjects,$folders);
2808 2808
 		//_debug_array($folders2return); #exit;
2809
-		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject,(array)$autoFolderObjects,(array)$folders);
2810
-		if (($_subscribedOnly && $_getCounters===false) ||
2811
-			($_subscribedOnly == false && $_getCounters===false &&
2809
+		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject, (array)$autoFolderObjects, (array)$folders);
2810
+		if (($_subscribedOnly && $_getCounters === false) ||
2811
+			($_subscribedOnly == false && $_getCounters === false &&
2812 2812
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2813
-			$this->mailPreferences['showAllFoldersInFolderPane']==1))
2813
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1))
2814 2814
 		{
2815
-			Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),$folders2return,$expiration=60*60*1);
2815
+			Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), $folders2return, $expiration = 60 * 60 * 1);
2816 2816
 		}
2817
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderBasicInfo,$expiration=60*60*1);
2818
-		if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') ');
2817
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderBasicInfo, $expiration = 60 * 60 * 1);
2818
+		if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') ');
2819 2819
 		return $folders2return[$this->icServer->ImapServerId];
2820 2820
 	}
2821 2821
 
@@ -2836,21 +2836,21 @@  discard block
 block discarded – undo
2836 2836
 	 *
2837 2837
 	 * @return array arrays of folders
2838 2838
 	 */
2839
-	function getFolderArrays ($_nodePath = null, $_onlyTopLevel = false, $_search= 2, $_subscribedOnly = false, $_getCounter = false)
2839
+	function getFolderArrays($_nodePath = null, $_onlyTopLevel = false, $_search = 2, $_subscribedOnly = false, $_getCounter = false)
2840 2840
 	{
2841 2841
 		// delimiter
2842 2842
 		$delimiter = $this->getHierarchyDelimiter();
2843 2843
 
2844
-		$folders = $nameSpace =  array();
2844
+		$folders = $nameSpace = array();
2845 2845
 		$nameSpaceTmp = $this->_getNameSpaces();
2846
-		foreach($nameSpaceTmp as $k => $singleNameSpace) {
2847
-			$nameSpace[$singleNameSpace['type']]=$singleNameSpace;
2846
+		foreach ($nameSpaceTmp as $k => $singleNameSpace) {
2847
+			$nameSpace[$singleNameSpace['type']] = $singleNameSpace;
2848 2848
 		}
2849 2849
 		unset($nameSpaceTmp);
2850 2850
 
2851 2851
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2852 2852
 		// Get special use folders
2853
-		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders (); // Set self::$specialUseFolders
2853
+		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders(); // Set self::$specialUseFolders
2854 2854
 		// topLevelQueries generally ignore the $_search param. Except for Config::examineNamespace
2855 2855
 		if ($_onlyTopLevel) // top level leaves
2856 2856
 		{
@@ -2861,20 +2861,20 @@  discard block
 block discarded – undo
2861 2861
 			if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
2862 2862
 			if (self::$mailConfig['examineNamespace'])
2863 2863
 			{
2864
-				$prefixes=array();
2864
+				$prefixes = array();
2865 2865
 				if (is_array($nameSpace))
2866 2866
 				{
2867
-					foreach($nameSpace as $k => $singleNameSpace) {
2867
+					foreach ($nameSpace as $k => $singleNameSpace) {
2868 2868
 						$type = $singleNameSpace['type'];
2869 2869
 
2870
-						if(is_array($singleNameSpace) && $singleNameSpace['prefix']){
2870
+						if (is_array($singleNameSpace) && $singleNameSpace['prefix']) {
2871 2871
 							$prefixes[$type] = $singleNameSpace['prefix'];
2872 2872
 							//regard extra care for nameSpacequeries when configured AND respect $_search
2873
-							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search==0?0:2, true);
2873
+							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search == 0 ? 0 : 2, true);
2874 2874
 							if (is_array($result))
2875 2875
 							{
2876 2876
 								ksort($result);
2877
-								$topFolders = array_merge($topFolders,$result);
2877
+								$topFolders = array_merge($topFolders, $result);
2878 2878
 							}
2879 2879
 						}
2880 2880
 					}
@@ -2883,7 +2883,7 @@  discard block
 block discarded – undo
2883 2883
 
2884 2884
 			$autofolders = array();
2885 2885
 
2886
-			foreach(self::$specialUseFolders as $path => $folder)
2886
+			foreach (self::$specialUseFolders as $path => $folder)
2887 2887
 			{
2888 2888
 				if ($this->folderExists($path))
2889 2889
 				{
@@ -2891,9 +2891,9 @@  discard block
 block discarded – undo
2891 2891
 				}
2892 2892
 			}
2893 2893
 			// Check if the special use folders are there, otherwise try to create them
2894
-			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders ($autofolders))
2894
+			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders($autofolders))
2895 2895
 			{
2896
-				return $this->getFolderArrays ($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2896
+				return $this->getFolderArrays($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2897 2897
 			}
2898 2898
 
2899 2899
 			// now process topFolders for next level
@@ -2901,13 +2901,13 @@  discard block
 block discarded – undo
2901 2901
 			{
2902 2902
 				$pattern = "/\\".$delimiter."/";
2903 2903
 				$reference = preg_replace($pattern, '', $node['MAILBOX']);
2904
-				if(!empty($prefixes))
2904
+				if (!empty($prefixes))
2905 2905
 				{
2906 2906
 					$reference = '';
2907
-					$tmpArray = explode($delimiter,$node['MAILBOX']);
2908
-					foreach($tmpArray as $p)
2907
+					$tmpArray = explode($delimiter, $node['MAILBOX']);
2908
+					foreach ($tmpArray as $p)
2909 2909
 					{
2910
-						$reference = empty($reference)?$p:$reference.$delimiter.$p;
2910
+						$reference = empty($reference) ? $p : $reference.$delimiter.$p;
2911 2911
 					}
2912 2912
 				}
2913 2913
 				$mainFolder = $subFolders = array();
@@ -2943,19 +2943,19 @@  discard block
 block discarded – undo
2943 2943
 							$nFolders [$path] = $folder;
2944 2944
 						}
2945 2945
 					}
2946
-					if (is_array($aFolders)) uasort ($aFolders, array($this,'sortByAutofolder'));
2946
+					if (is_array($aFolders)) uasort($aFolders, array($this, 'sortByAutofolder'));
2947 2947
 					//ksort($aFolders);
2948 2948
 
2949 2949
 					// Sort none auto folders base on mailbox name
2950
-					uasort($nFolders,array($this,'sortByMailbox'));
2950
+					uasort($nFolders, array($this, 'sortByMailbox'));
2951 2951
 
2952
-					$subFolders = array_merge($aFolders,$nFolders);
2952
+					$subFolders = array_merge($aFolders, $nFolders);
2953 2953
 				}
2954 2954
 				else
2955 2955
 				{
2956 2956
 					if (is_array($subFolders)) ksort($subFolders);
2957 2957
 				}
2958
-				$folders = array_merge($folders,(array)$mainFolder, (array)$subFolders);
2958
+				$folders = array_merge($folders, (array)$mainFolder, (array)$subFolders);
2959 2959
 			}
2960 2960
 		}
2961 2961
 		elseif ($_nodePath) // single node
@@ -2982,9 +2982,9 @@  discard block
 block discarded – undo
2982 2982
 				$folders = $this->icServer->getMailboxes($path, $_search, true);
2983 2983
 			}
2984 2984
 
2985
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
2985
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
2986 2986
 		}
2987
-		elseif(!$_nodePath) // all
2987
+		elseif (!$_nodePath) // all
2988 2988
 		{
2989 2989
 			if ($_subscribedOnly)
2990 2990
 			{
@@ -3000,101 +3000,101 @@  discard block
 block discarded – undo
3000 3000
 		{
3001 3001
 			// SORTING FOLDERS
3002 3002
 			//self::$debugTimes=true;
3003
-			if (self::$debugTimes) $starttime = microtime (true);
3003
+			if (self::$debugTimes) $starttime = microtime(true);
3004 3004
 			// Merge of all auto folders and specialusefolders
3005 3005
 			$autoFoldersTmp = array_unique((array_merge(self::$autoFolders, array_values(self::$specialUseFolders))));
3006
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
3006
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
3007 3007
 			$tmpFolders = $folders;
3008
-			$inboxFolderObject=$inboxSubFolderObjects=$autoFolderObjects=$typeFolderObject=$mySpecialUseFolders=array();
3009
-			$googleMailFolderObject=$googleAutoFolderObjects=$googleSubFolderObjects=array();
3010
-			$isGoogleMail=false;
3011
-			foreach($autoFoldersTmp as $afk=>$aF)
3008
+			$inboxFolderObject = $inboxSubFolderObjects = $autoFolderObjects = $typeFolderObject = $mySpecialUseFolders = array();
3009
+			$googleMailFolderObject = $googleAutoFolderObjects = $googleSubFolderObjects = array();
3010
+			$isGoogleMail = false;
3011
+			foreach ($autoFoldersTmp as $afk=>$aF)
3012 3012
 			{
3013
-				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF]=$this->getFolderByType($aF,false);
3013
+				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF] = $this->getFolderByType($aF, false);
3014 3014
 				//error_log($afk.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3015 3015
 			}
3016 3016
 			//error_log(array2string($mySpecialUseFolders));
3017 3017
 			foreach ($tmpFolders as $k => $f) {
3018
-				$sorted=false;
3019
-				if (strtoupper(substr($k,0,5))=='INBOX') {
3020
-					if (strtoupper($k)=='INBOX') {
3018
+				$sorted = false;
3019
+				if (strtoupper(substr($k, 0, 5)) == 'INBOX') {
3020
+					if (strtoupper($k) == 'INBOX') {
3021 3021
 						//error_log(__METHOD__.__LINE__.':'.strtoupper(substr($k,0,5)).':'.$k);
3022
-						$inboxFolderObject[$k]=$f;
3022
+						$inboxFolderObject[$k] = $f;
3023 3023
 						unset($folders[$k]);
3024
-						$sorted=true;
3024
+						$sorted = true;
3025 3025
 					} else {
3026
-						$isAutoFolder=false;
3027
-						foreach($autoFoldersTmp as $afk=>$aF)
3026
+						$isAutoFolder = false;
3027
+						foreach ($autoFoldersTmp as $afk=>$aF)
3028 3028
 						{
3029 3029
 							//error_log(__METHOD__.__LINE__.$k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3030
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3031
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3032
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3030
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3031
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3032
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3033 3033
 							{
3034 3034
 								//error_log(__METHOD__.__LINE__.$k.'->'.$mySpecialUseFolders[$aF]);
3035
-								$isAutoFolder=true;
3036
-								$autoFolderObjects[$k]=$f;
3035
+								$isAutoFolder = true;
3036
+								$autoFolderObjects[$k] = $f;
3037 3037
 								break;
3038 3038
 							}
3039 3039
 						}
3040
-						if ($isAutoFolder==false) $inboxSubFolderObjects[$k]=$f;
3040
+						if ($isAutoFolder == false) $inboxSubFolderObjects[$k] = $f;
3041 3041
 						unset($folders[$k]);
3042
-						$sorted=true;
3042
+						$sorted = true;
3043 3043
 					}
3044
-				} elseif (strtoupper(substr($k,0,13))=='[GOOGLE MAIL]') {
3045
-					$isGoogleMail=true;
3046
-					if (strtoupper($k)=='[GOOGLE MAIL]') {
3047
-						$googleMailFolderObject[$k]=$f;
3044
+				} elseif (strtoupper(substr($k, 0, 13)) == '[GOOGLE MAIL]') {
3045
+					$isGoogleMail = true;
3046
+					if (strtoupper($k) == '[GOOGLE MAIL]') {
3047
+						$googleMailFolderObject[$k] = $f;
3048 3048
 						unset($folders[$k]);
3049
-						$sorted=true;
3049
+						$sorted = true;
3050 3050
 					} else {
3051
-						$isAutoFolder=false;
3052
-						foreach($autoFoldersTmp as $afk=>$aF)
3051
+						$isAutoFolder = false;
3052
+						foreach ($autoFoldersTmp as $afk=>$aF)
3053 3053
 						{
3054 3054
 							//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3055
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3056
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3057
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3055
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3056
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3057
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3058 3058
 							{
3059 3059
 								//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3060
-								$isAutoFolder=true;
3061
-								$googleAutoFolderObjects[$k]=$f;
3060
+								$isAutoFolder = true;
3061
+								$googleAutoFolderObjects[$k] = $f;
3062 3062
 								break;
3063 3063
 							}
3064 3064
 						}
3065
-						if ($isAutoFolder==false) $googleSubFolderObjects[$k]=$f;
3065
+						if ($isAutoFolder == false) $googleSubFolderObjects[$k] = $f;
3066 3066
 						unset($folders[$k]);
3067
-						$sorted=true;
3067
+						$sorted = true;
3068 3068
 					}
3069 3069
 				} else {
3070
-					$isAutoFolder=false;
3071
-					foreach($autoFoldersTmp as $afk=>$aF)
3070
+					$isAutoFolder = false;
3071
+					foreach ($autoFoldersTmp as $afk=>$aF)
3072 3072
 					{
3073 3073
 						//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3074
-						if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3075
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3076
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3074
+						if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3075
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3076
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3077 3077
 						{
3078 3078
 							//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3079
-							$isAutoFolder=true;
3080
-							$autoFolderObjects[$k]=$f;
3079
+							$isAutoFolder = true;
3080
+							$autoFolderObjects[$k] = $f;
3081 3081
 							unset($folders[$k]);
3082
-							$sorted=true;
3082
+							$sorted = true;
3083 3083
 							break;
3084 3084
 						}
3085 3085
 					}
3086 3086
 				}
3087 3087
 
3088
-				if ($sorted==false)
3088
+				if ($sorted == false)
3089 3089
 				{
3090
-					foreach(array('others','shared') as $type)
3090
+					foreach (array('others', 'shared') as $type)
3091 3091
 					{
3092
-						if ($nameSpace[$type]['prefix_present']&&$nameSpace[$type]['prefix'])
3092
+						if ($nameSpace[$type]['prefix_present'] && $nameSpace[$type]['prefix'])
3093 3093
 						{
3094
-							if (substr($k,0,strlen($nameSpace[$type]['prefix']))==$nameSpace[$type]['prefix']||
3095
-								substr($k,0,strlen($nameSpace[$type]['prefix'])-strlen($nameSpace[$type]['delimiter']))==substr($nameSpace[$type]['prefix'],0,strlen($nameSpace[$type]['delimiter'])*-1)) {
3094
+							if (substr($k, 0, strlen($nameSpace[$type]['prefix'])) == $nameSpace[$type]['prefix'] ||
3095
+								substr($k, 0, strlen($nameSpace[$type]['prefix']) - strlen($nameSpace[$type]['delimiter'])) == substr($nameSpace[$type]['prefix'], 0, strlen($nameSpace[$type]['delimiter']) * -1)) {
3096 3096
 								//error_log(__METHOD__.__LINE__.':'.substr($k,0,strlen($nameSpace[$type]['prefix'])).':'.$k);
3097
-								$typeFolderObject[$type][$k]=$f;
3097
+								$typeFolderObject[$type][$k] = $f;
3098 3098
 								unset($folders[$k]);
3099 3099
 							}
3100 3100
 						}
@@ -3105,40 +3105,40 @@  discard block
 block discarded – undo
3105 3105
 			// avoid calling sortByAutoFolder as it is not regarding subfolders
3106 3106
 			$autoFolderObjectsTmp = $autoFolderObjects;
3107 3107
 			unset($autoFolderObjects);
3108
-			uasort($autoFolderObjectsTmp, array($this,'sortByMailbox'));
3109
-			foreach($autoFoldersTmp as $afk=>$aF)
3108
+			uasort($autoFolderObjectsTmp, array($this, 'sortByMailbox'));
3109
+			foreach ($autoFoldersTmp as $afk=>$aF)
3110 3110
 			{
3111
-				foreach($autoFolderObjectsTmp as $k => $f)
3111
+				foreach ($autoFolderObjectsTmp as $k => $f)
3112 3112
 				{
3113
-					if($aF && ($mySpecialUseFolders[$aF]==$k ||
3114
-						substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter ||
3115
-						stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false))
3113
+					if ($aF && ($mySpecialUseFolders[$aF] == $k ||
3114
+						substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter ||
3115
+						stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false))
3116 3116
 					{
3117
-						$autoFolderObjects[$k]=$f;
3117
+						$autoFolderObjects[$k] = $f;
3118 3118
 					}
3119 3119
 				}
3120 3120
 			}
3121 3121
 			//error_log(__METHOD__.__LINE__.array2string($autoFolderObjects));
3122 3122
 			if (!$isGoogleMail) {
3123
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$inboxSubFolderObjects,(array)$folders,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3123
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$inboxSubFolderObjects, (array)$folders, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3124 3124
 			} else {
3125 3125
 				// avoid calling sortByAutoFolder as it is not regarding subfolders
3126 3126
 				$gAutoFolderObjectsTmp = $googleAutoFolderObjects;
3127 3127
 				unset($googleAutoFolderObjects);
3128
-				uasort($gAutoFolderObjectsTmp, array($this,'sortByMailbox'));
3129
-				foreach($autoFoldersTmp as $afk=>$aF)
3128
+				uasort($gAutoFolderObjectsTmp, array($this, 'sortByMailbox'));
3129
+				foreach ($autoFoldersTmp as $afk=>$aF)
3130 3130
 				{
3131
-					foreach($gAutoFolderObjectsTmp as $k => $f)
3131
+					foreach ($gAutoFolderObjectsTmp as $k => $f)
3132 3132
 					{
3133
-						if($aF && ($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter))
3133
+						if ($aF && ($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter))
3134 3134
 						{
3135
-							$googleAutoFolderObjects[$k]=$f;
3135
+							$googleAutoFolderObjects[$k] = $f;
3136 3136
 						}
3137 3137
 					}
3138 3138
 				}
3139
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$folders,(array)$googleMailFolderObject,$googleAutoFolderObjects,$googleSubFolderObjects,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3139
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$folders, (array)$googleMailFolderObject, $googleAutoFolderObjects, $googleSubFolderObjects, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3140 3140
 			}
3141
-			if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') Sorting:');
3141
+			if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') Sorting:');
3142 3142
 			//self::$debugTimes=false;
3143 3143
 		}
3144 3144
 		// Get counter information and add them to each fetched folders array
@@ -3160,10 +3160,10 @@  discard block
 block discarded – undo
3160 3160
 	 * @param array $autofolders_exists existing folders, no need to check their existance again
3161 3161
 	 * @return int number of new folders created
3162 3162
 	 */
3163
-	function check_create_autofolders(array $autofolders_exists=array())
3163
+	function check_create_autofolders(array $autofolders_exists = array())
3164 3164
 	{
3165 3165
 		$num_created = 0;
3166
-		foreach(self::$autoFolders as $folder)
3166
+		foreach (self::$autoFolders as $folder)
3167 3167
 		{
3168 3168
 			$created = false;
3169 3169
 			if (!in_array($folder, $autofolders_exists) && $this->_getSpecialUseFolder($folder, true, $created) &&
@@ -3188,7 +3188,7 @@  discard block
 block discarded – undo
3188 3188
 		$rv = false;
3189 3189
 		foreach ($haystack as $k => $v)
3190 3190
 		{
3191
-			foreach($v as &$sv) {if (trim($sv)==trim($needle)) return $k;}
3191
+			foreach ($v as &$sv) {if (trim($sv) == trim($needle)) return $k; }
3192 3192
 		}
3193 3193
 		return $rv;
3194 3194
 	}
@@ -3201,9 +3201,9 @@  discard block
 block discarded – undo
3201 3201
 	 * @param array $b array of folders
3202 3202
 	 * @return int expect values (0, 1 or -1)
3203 3203
 	 */
3204
-	function sortByMailbox($a,$b)
3204
+	function sortByMailbox($a, $b)
3205 3205
 	{
3206
-		return strcasecmp($a['MAILBOX'],$b['MAILBOX']);
3206
+		return strcasecmp($a['MAILBOX'], $b['MAILBOX']);
3207 3207
 	}
3208 3208
 
3209 3209
 	/**
@@ -3213,13 +3213,13 @@  discard block
 block discarded – undo
3213 3213
 	 * @param string $_hDelimiter hierarchy delimiter
3214 3214
 	 * @return array returns an array of data extracted from given node path
3215 3215
 	 */
3216
-	static function pathToFolderData ($_path, $_hDelimiter)
3216
+	static function pathToFolderData($_path, $_hDelimiter)
3217 3217
 	{
3218 3218
 		if (!strpos($_path, self::DELIMITER)) $_path = self::DELIMITER.$_path;
3219 3219
 		list(,$path) = explode(self::DELIMITER, $_path);
3220 3220
 		$path_chain = $parts = explode($_hDelimiter, $path);
3221 3221
 		$name = array_pop($parts);
3222
-		return array (
3222
+		return array(
3223 3223
 			'name' => $name,
3224 3224
 			'mailbox' => $path,
3225 3225
 			'parent' => implode($_hDelimiter, $parts),
@@ -3242,8 +3242,8 @@  discard block
 block discarded – undo
3242 3242
 		// 0, 1 und -1
3243 3243
 		$a = self::pathToFolderData($_a['MAILBOX'], $_a['delimiter']);
3244 3244
 		$b = self::pathToFolderData($_b['MAILBOX'], $_b['delimiter']);
3245
-		$pos1 = array_search(trim($a['name']),self::$autoFolders);
3246
-		$pos2 = array_search(trim($b['name']),self::$autoFolders);
3245
+		$pos1 = array_search(trim($a['name']), self::$autoFolders);
3246
+		$pos2 = array_search(trim($b['name']), self::$autoFolders);
3247 3247
 		if ($pos1 == $pos2) return 0;
3248 3248
 		return ($pos1 < $pos2) ? -1 : 1;
3249 3249
 	}
@@ -3256,10 +3256,10 @@  discard block
 block discarded – undo
3256 3256
 	 * @param object $b array of folderobjects
3257 3257
 	 * @return int expect values (0, 1 or -1)
3258 3258
 	 */
3259
-	function sortByDisplayName($a,$b)
3259
+	function sortByDisplayName($a, $b)
3260 3260
 	{
3261 3261
 		// 0, 1 und -1
3262
-		return strcasecmp($a->displayName,$b->displayName);
3262
+		return strcasecmp($a->displayName, $b->displayName);
3263 3263
 	}
3264 3264
 
3265 3265
 	/**
@@ -3270,11 +3270,11 @@  discard block
 block discarded – undo
3270 3270
 	 * @param object $b array of folderobjects
3271 3271
 	 * @return int expect values (0, 1 or -1)
3272 3272
 	 */
3273
-	function sortByAutoFolderPos($a,$b)
3273
+	function sortByAutoFolderPos($a, $b)
3274 3274
 	{
3275 3275
 		// 0, 1 und -1
3276
-		$pos1 = array_search(trim($a->shortFolderName),self::$autoFolders);
3277
-		$pos2 = array_search(trim($b->shortFolderName),self::$autoFolders);
3276
+		$pos1 = array_search(trim($a->shortFolderName), self::$autoFolders);
3277
+		$pos2 = array_search(trim($b->shortFolderName), self::$autoFolders);
3278 3278
 		if ($pos1 == $pos2) return 0;
3279 3279
 		return ($pos1 < $pos2) ? -1 : 1;
3280 3280
 	}
@@ -3287,7 +3287,7 @@  discard block
 block discarded – undo
3287 3287
 	 * @param boolean $_returnObject return the counters as object rather than an array
3288 3288
 	 * @return mixed false or array of counters array(MESSAGES,UNSEEN,RECENT,UIDNEXT,UIDVALIDITY) or object
3289 3289
 	 */
3290
-	function getMailBoxCounters($folderName,$_returnObject=true)
3290
+	function getMailBoxCounters($folderName, $_returnObject = true)
3291 3291
 	{
3292 3292
 		try
3293 3293
 		{
@@ -3299,9 +3299,9 @@  discard block
 block discarded – undo
3299 3299
 			if (self::$debug) error_log(__METHOD__." returned FolderStatus for Folder $folderName:".$e->getMessage());
3300 3300
 			return false;
3301 3301
 		}
3302
-		if(is_array($folderStatus)) {
3303
-			if ($_returnObject===false) return $folderStatus;
3304
-			$status =  new \stdClass;
3302
+		if (is_array($folderStatus)) {
3303
+			if ($_returnObject === false) return $folderStatus;
3304
+			$status = new \stdClass;
3305 3305
 			$status->messages   = $folderStatus['MESSAGES'];
3306 3306
 			$status->unseen     = $folderStatus['UNSEEN'];
3307 3307
 			$status->recent     = $folderStatus['RECENT'];
@@ -3323,42 +3323,42 @@  discard block
 block discarded – undo
3323 3323
 	 * @param string $reclevel 0, counter to keep track of the current recursionlevel
3324 3324
 	 * @return array of mailboxes
3325 3325
 	 */
3326
-	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel=0)
3326
+	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel = 0)
3327 3327
 	{
3328 3328
 		#echo __METHOD__." retrieve SubFolders for $_mailbox$delimiter <br>";
3329
-		$maxreclevel=25;
3329
+		$maxreclevel = 25;
3330 3330
 		if ($reclevel > $maxreclevel) {
3331
-			error_log( __METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3331
+			error_log(__METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3332 3332
 			return array();
3333 3333
 		}
3334 3334
 		$reclevel++;
3335 3335
 		// clean up double delimiters
3336
-		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$_mailbox);
3336
+		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $_mailbox);
3337 3337
 		//get that mailbox in question
3338
-		$mbx = $this->icServer->getMailboxes($_mailbox,1,true);
3338
+		$mbx = $this->icServer->getMailboxes($_mailbox, 1, true);
3339 3339
 		$mbxkeys = array_keys($mbx);
3340 3340
 		#_debug_array($mbx);
3341 3341
 //error_log(__METHOD__.' ('.__LINE__.') '.' Delimiter:'.array2string($delimiter));
3342 3342
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
3343 3343
 		// Example: Array([INBOX/GaGa] => Array([MAILBOX] => INBOX/GaGa[ATTRIBUTES] => Array([0] => \\unmarked)[delimiter] => /))
3344
-		if (is_array($mbx[$mbxkeys[0]]["ATTRIBUTES"]) && (in_array('\HasChildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Haschildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\haschildren',$mbx[$mbxkeys[0]]["ATTRIBUTES"]))) {
3344
+		if (is_array($mbx[$mbxkeys[0]]["ATTRIBUTES"]) && (in_array('\HasChildren', $mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Haschildren', $mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\haschildren', $mbx[$mbxkeys[0]]["ATTRIBUTES"]))) {
3345 3345
 			// if there are children fetch them
3346 3346
 			//echo $mbx[$mbxkeys[0]]['MAILBOX']."<br>";
3347 3347
 
3348
-			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '':$delimiter),2,false);
3348
+			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '' : $delimiter), 2, false);
3349 3349
 			//$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'],2,false);
3350 3350
 			//_debug_array($buff);
3351 3351
 			$allMailboxes = array();
3352 3352
 			foreach ($buff as $mbxname) {
3353 3353
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbxname));
3354
-				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$mbxname['MAILBOX']);
3354
+				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $mbxname['MAILBOX']);
3355 3355
 				#echo "About to recur in level $reclevel:".$mbxname."<br>";
3356
-				if ( $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix  && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3356
+				if ($mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3357 3357
 				{
3358 3358
 					$allMailboxes = array_merge($allMailboxes, self::getMailBoxesRecursive($mbxname, $delimiter, $prefix, $reclevel));
3359 3359
 				}
3360 3360
 			}
3361
-			if (!(in_array('\NoSelect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Noselect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\noselect',$mbx[$mbxkeys[0]]["ATTRIBUTES"]))) $allMailboxes[] = $mbx[$mbxkeys[0]]['MAILBOX'];
3361
+			if (!(in_array('\NoSelect', $mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\Noselect', $mbx[$mbxkeys[0]]["ATTRIBUTES"]) || in_array('\noselect', $mbx[$mbxkeys[0]]["ATTRIBUTES"]))) $allMailboxes[] = $mbx[$mbxkeys[0]]['MAILBOX'];
3362 3362
 			return $allMailboxes;
3363 3363
 		} else {
3364 3364
 			return array($_mailbox);
@@ -3373,18 +3373,18 @@  discard block
 block discarded – undo
3373 3373
 	 * @param boolean& $created =null on return true: if folder was just created, false if not
3374 3374
 	 * @return mixed string or false
3375 3375
 	 */
3376
-	function _getSpecialUseFolder($_type, $_checkexistance=TRUE, &$created=null)
3376
+	function _getSpecialUseFolder($_type, $_checkexistance = TRUE, &$created = null)
3377 3377
 	{
3378 3378
 		static $types = array(
3379
-			'Drafts'   => array('profileKey'=>'acc_folder_draft','autoFolderName'=>'Drafts'),
3380
-			'Template' => array('profileKey'=>'acc_folder_template','autoFolderName'=>'Templates'),
3381
-			'Trash'    => array('profileKey'=>'acc_folder_trash','autoFolderName'=>'Trash'),
3382
-			'Sent'     => array('profileKey'=>'acc_folder_sent','autoFolderName'=>'Sent'),
3383
-			'Junk'     => array('profileKey'=>'acc_folder_junk','autoFolderName'=>'Junk'),
3384
-			'Outbox'   => array('profileKey'=>'acc_folder_outbox','autoFolderName'=>'Outbox'),
3385
-			'Archive'   => array('profileKey'=>'acc_folder_archive','autoFolderName'=>'Archive'),
3379
+			'Drafts'   => array('profileKey'=>'acc_folder_draft', 'autoFolderName'=>'Drafts'),
3380
+			'Template' => array('profileKey'=>'acc_folder_template', 'autoFolderName'=>'Templates'),
3381
+			'Trash'    => array('profileKey'=>'acc_folder_trash', 'autoFolderName'=>'Trash'),
3382
+			'Sent'     => array('profileKey'=>'acc_folder_sent', 'autoFolderName'=>'Sent'),
3383
+			'Junk'     => array('profileKey'=>'acc_folder_junk', 'autoFolderName'=>'Junk'),
3384
+			'Outbox'   => array('profileKey'=>'acc_folder_outbox', 'autoFolderName'=>'Outbox'),
3385
+			'Archive'   => array('profileKey'=>'acc_folder_archive', 'autoFolderName'=>'Archive'),
3386 3386
 		);
3387
-		if ($_type == 'Templates') $_type = 'Template';	// for some reason self::$autofolders uses 'Templates'!
3387
+		if ($_type == 'Templates') $_type = 'Template'; // for some reason self::$autofolders uses 'Templates'!
3388 3388
 		$created = false;
3389 3389
 		if (!isset($types[$_type]))
3390 3390
 		{
@@ -3406,7 +3406,7 @@  discard block
 block discarded – undo
3406 3406
 		}
3407 3407
 		// do not try to autocreate configured Archive-Folder. Return false if configured folder does not exist
3408 3408
 		if ($_type == 'Archive') {
3409
-			if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3409
+			if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3410 3410
 				return false;
3411 3411
 			} else {
3412 3412
 				return $_folderName;
@@ -3414,38 +3414,38 @@  discard block
 block discarded – undo
3414 3414
 
3415 3415
 		}
3416 3416
 		// does the folder exist??? (is configured/preset, but non-existent)
3417
-		if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3417
+		if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3418 3418
 			try
3419 3419
 			{
3420 3420
 				$error = null;
3421 3421
 				if (($_folderName = $this->createFolder('', $_folderName, $error))) $created = true;
3422 3422
 				if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3423 3423
 			}
3424
-			catch(Exception $e)
3424
+			catch (Exception $e)
3425 3425
 			{
3426 3426
 				error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage().':'.function_backtrace());
3427 3427
 				$_folderName = false;
3428 3428
 			}
3429 3429
 		}
3430 3430
 		// not sure yet if false is the correct behavior on none
3431
-		if ($_folderName =='none') return 'none' ; //false;
3431
+		if ($_folderName == 'none') return 'none'; //false;
3432 3432
 		//no (valid) folder found yet; try specialUseFolders
3433
-		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type,self::$specialUseFolders))) $_folderName = $f;
3433
+		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type, self::$specialUseFolders))) $_folderName = $f;
3434 3434
 		//no specialUseFolder; try some Defaults
3435 3435
 		if (empty($_folderName) && isset($types[$_type]))
3436 3436
 		{
3437 3437
 			$nameSpace = $this->_getNameSpaces();
3438
-			$prefix='';
3438
+			$prefix = '';
3439 3439
 			foreach ($nameSpace as $nSp)
3440 3440
 			{
3441
-				if ($nSp['type']=='personal')
3441
+				if ($nSp['type'] == 'personal')
3442 3442
 				{
3443 3443
 					//error_log(__METHOD__.__LINE__.array2string($nSp));
3444 3444
 					$prefix = $nSp['prefix'];
3445 3445
 					break;
3446 3446
 				}
3447 3447
 			}
3448
-			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'],true))
3448
+			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'], true))
3449 3449
 			{
3450 3450
 				$_folderName = $prefix.$types[$_type]['autoFolderName'];
3451 3451
 			}
@@ -3454,11 +3454,11 @@  discard block
 block discarded – undo
3454 3454
 				try
3455 3455
 				{
3456 3456
 					$error = null;
3457
-					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'],$error);
3457
+					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'], $error);
3458 3458
 					$_folderName = $prefix.$types[$_type]['autoFolderName'];
3459 3459
 					if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3460 3460
 				}
3461
-				catch(Exception $e)
3461
+				catch (Exception $e)
3462 3462
 				{
3463 3463
 					error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage());
3464 3464
 					$_folderName = false;
@@ -3474,7 +3474,7 @@  discard block
 block discarded – undo
3474 3474
 	 * @param boolean $_checkexistance trigger check for existance
3475 3475
 	 * @return mixed string or false
3476 3476
 	 */
3477
-	function getFolderByType($type, $_checkexistance=false)
3477
+	function getFolderByType($type, $_checkexistance = false)
3478 3478
 	{
3479 3479
 		return $this->_getSpecialUseFolder($type, $_checkexistance);
3480 3480
 	}
@@ -3484,7 +3484,7 @@  discard block
 block discarded – undo
3484 3484
 	 * @param boolean $_checkexistance trigger check for existance
3485 3485
 	 * @return mixed string or false
3486 3486
 	 */
3487
-	function getJunkFolder($_checkexistance=TRUE)
3487
+	function getJunkFolder($_checkexistance = TRUE)
3488 3488
 	{
3489 3489
 		return $this->_getSpecialUseFolder('Junk', $_checkexistance);
3490 3490
 	}
@@ -3494,7 +3494,7 @@  discard block
 block discarded – undo
3494 3494
 	 * @param boolean $_checkexistance trigger check for existance
3495 3495
 	 * @return mixed string or false
3496 3496
 	 */
3497
-	function getDraftFolder($_checkexistance=TRUE)
3497
+	function getDraftFolder($_checkexistance = TRUE)
3498 3498
 	{
3499 3499
 		return $this->_getSpecialUseFolder('Drafts', $_checkexistance);
3500 3500
 	}
@@ -3504,7 +3504,7 @@  discard block
 block discarded – undo
3504 3504
 	 * @param boolean $_checkexistance trigger check for existance
3505 3505
 	 * @return mixed string or false
3506 3506
 	 */
3507
-	function getTemplateFolder($_checkexistance=TRUE)
3507
+	function getTemplateFolder($_checkexistance = TRUE)
3508 3508
 	{
3509 3509
 		return $this->_getSpecialUseFolder('Template', $_checkexistance);
3510 3510
 	}
@@ -3514,7 +3514,7 @@  discard block
 block discarded – undo
3514 3514
 	 * @param boolean $_checkexistance trigger check for existance
3515 3515
 	 * @return mixed string or false
3516 3516
 	 */
3517
-	function getTrashFolder($_checkexistance=TRUE)
3517
+	function getTrashFolder($_checkexistance = TRUE)
3518 3518
 	{
3519 3519
 		return $this->_getSpecialUseFolder('Trash', $_checkexistance);
3520 3520
 	}
@@ -3524,7 +3524,7 @@  discard block
 block discarded – undo
3524 3524
 	 * @param boolean $_checkexistance trigger check for existance
3525 3525
 	 * @return mixed string or false
3526 3526
 	 */
3527
-	function getSentFolder($_checkexistance=TRUE)
3527
+	function getSentFolder($_checkexistance = TRUE)
3528 3528
 	{
3529 3529
 		return $this->_getSpecialUseFolder('Sent', $_checkexistance);
3530 3530
 	}
@@ -3534,7 +3534,7 @@  discard block
 block discarded – undo
3534 3534
 	 * @param boolean $_checkexistance trigger check for existance
3535 3535
 	 * @return mixed string or false
3536 3536
 	 */
3537
-	function getOutboxFolder($_checkexistance=TRUE)
3537
+	function getOutboxFolder($_checkexistance = TRUE)
3538 3538
 	{
3539 3539
 		return $this->_getSpecialUseFolder('Outbox', $_checkexistance);
3540 3540
 	}
@@ -3544,7 +3544,7 @@  discard block
 block discarded – undo
3544 3544
 	 * @param boolean $_checkexistance trigger check for existance . We do no autocreation for configured Archive folder
3545 3545
 	 * @return mixed string or false
3546 3546
 	 */
3547
-	function getArchiveFolder($_checkexistance=TRUE)
3547
+	function getArchiveFolder($_checkexistance = TRUE)
3548 3548
 	{
3549 3549
 		return $this->_getSpecialUseFolder('Archive', $_checkexistance);
3550 3550
 	}
@@ -3556,10 +3556,10 @@  discard block
 block discarded – undo
3556 3556
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3557 3557
 	 * @return boolean
3558 3558
 	 */
3559
-	function isSentFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3559
+	function isSentFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3560 3560
 	{
3561 3561
 		$sentFolder = $this->getSentFolder($_checkexistance);
3562
-		if(empty($sentFolder)) {
3562
+		if (empty($sentFolder)) {
3563 3563
 			return false;
3564 3564
 		}
3565 3565
 		// does the folder exist???
@@ -3569,13 +3569,13 @@  discard block
 block discarded – undo
3569 3569
 
3570 3570
 		if ($_exactMatch)
3571 3571
 		{
3572
-			if(false !== stripos($_folderName, $sentFolder)&& strlen($_folderName)==strlen($sentFolder)) {
3572
+			if (false !== stripos($_folderName, $sentFolder) && strlen($_folderName) == strlen($sentFolder)) {
3573 3573
 				return true;
3574 3574
 			} else {
3575 3575
 				return false;
3576 3576
 			}
3577 3577
 		} else {
3578
-			if(false !== stripos($_folderName, $sentFolder)) {
3578
+			if (false !== stripos($_folderName, $sentFolder)) {
3579 3579
 				return true;
3580 3580
 			} else {
3581 3581
 				return false;
@@ -3590,9 +3590,9 @@  discard block
 block discarded – undo
3590 3590
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3591 3591
 	 * @return boolean
3592 3592
 	 */
3593
-	function isOutbox($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3593
+	function isOutbox($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3594 3594
 	{
3595
-		if (stripos($_folderName, 'Outbox')===false) {
3595
+		if (stripos($_folderName, 'Outbox') === false) {
3596 3596
 			return false;
3597 3597
 		}
3598 3598
 		// does the folder exist???
@@ -3600,13 +3600,13 @@  discard block
 block discarded – undo
3600 3600
 			$outboxFolder = $this->getOutboxFolder($_checkexistance);
3601 3601
 			if ($_exactMatch)
3602 3602
 			{
3603
-				if(false !== stripos($_folderName, $outboxFolder)&& strlen($_folderName)==strlen($outboxFolder)) {
3603
+				if (false !== stripos($_folderName, $outboxFolder) && strlen($_folderName) == strlen($outboxFolder)) {
3604 3604
 					return true;
3605 3605
 				} else {
3606 3606
 					return false;
3607 3607
 				}
3608 3608
 			} else {
3609
-				if(false !== stripos($_folderName, $outboxFolder)) {
3609
+				if (false !== stripos($_folderName, $outboxFolder)) {
3610 3610
 					return true;
3611 3611
 				} else {
3612 3612
 					return false;
@@ -3623,26 +3623,26 @@  discard block
 block discarded – undo
3623 3623
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3624 3624
 	 * @return boolean
3625 3625
 	 */
3626
-	function isDraftFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3626
+	function isDraftFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3627 3627
 	{
3628 3628
 		$draftFolder = $this->getDraftFolder($_checkexistance);
3629
-		if(empty($draftFolder)) {
3629
+		if (empty($draftFolder)) {
3630 3630
 			return false;
3631 3631
 		}
3632 3632
 		// does the folder exist???
3633 3633
 		if ($_checkexistance && !$this->folderExists($_folderName)) {
3634 3634
 			return false;
3635 3635
 		}
3636
-		if (is_a($_folderName,"Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3636
+		if (is_a($_folderName, "Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3637 3637
 		if ($_exactMatch)
3638 3638
 		{
3639
-			if(false !== stripos($_folderName, $draftFolder)&& strlen($_folderName)==strlen($draftFolder)) {
3639
+			if (false !== stripos($_folderName, $draftFolder) && strlen($_folderName) == strlen($draftFolder)) {
3640 3640
 				return true;
3641 3641
 			} else {
3642 3642
 				return false;
3643 3643
 			}
3644 3644
 		} else {
3645
-			if(false !== stripos($_folderName, $draftFolder)) {
3645
+			if (false !== stripos($_folderName, $draftFolder)) {
3646 3646
 				return true;
3647 3647
 			} else {
3648 3648
 				return false;
@@ -3657,10 +3657,10 @@  discard block
 block discarded – undo
3657 3657
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3658 3658
 	 * @return boolean
3659 3659
 	 */
3660
-	function isTrashFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3660
+	function isTrashFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3661 3661
 	{
3662 3662
 		$trashFolder = $this->getTrashFolder($_checkexistance);
3663
-		if(empty($trashFolder)) {
3663
+		if (empty($trashFolder)) {
3664 3664
 			return false;
3665 3665
 		}
3666 3666
 		// does the folder exist???
@@ -3670,13 +3670,13 @@  discard block
 block discarded – undo
3670 3670
 
3671 3671
 		if ($_exactMatch)
3672 3672
 		{
3673
-			if(false !== stripos($_folderName, $trashFolder)&& strlen($_folderName)==strlen($trashFolder)) {
3673
+			if (false !== stripos($_folderName, $trashFolder) && strlen($_folderName) == strlen($trashFolder)) {
3674 3674
 				return true;
3675 3675
 			} else {
3676 3676
 				return false;
3677 3677
 			}
3678 3678
 		} else {
3679
-			if(false !== stripos($_folderName, $trashFolder)) {
3679
+			if (false !== stripos($_folderName, $trashFolder)) {
3680 3680
 				return true;
3681 3681
 			} else {
3682 3682
 				return false;
@@ -3691,10 +3691,10 @@  discard block
 block discarded – undo
3691 3691
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3692 3692
 	 * @return boolean
3693 3693
 	 */
3694
-	function isTemplateFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3694
+	function isTemplateFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3695 3695
 	{
3696 3696
 		$templateFolder = $this->getTemplateFolder($_checkexistance);
3697
-		if(empty($templateFolder)) {
3697
+		if (empty($templateFolder)) {
3698 3698
 			return false;
3699 3699
 		}
3700 3700
 		// does the folder exist???
@@ -3703,13 +3703,13 @@  discard block
 block discarded – undo
3703 3703
 		}
3704 3704
 		if ($_exactMatch)
3705 3705
 		{
3706
-			if(false !== stripos($_folderName, $templateFolder)&& strlen($_folderName)==strlen($templateFolder)) {
3706
+			if (false !== stripos($_folderName, $templateFolder) && strlen($_folderName) == strlen($templateFolder)) {
3707 3707
 				return true;
3708 3708
 			} else {
3709 3709
 				return false;
3710 3710
 			}
3711 3711
 		} else {
3712
-			if(false !== stripos($_folderName, $templateFolder)) {
3712
+			if (false !== stripos($_folderName, $templateFolder)) {
3713 3713
 				return true;
3714 3714
 			} else {
3715 3715
 				return false;
@@ -3723,24 +3723,24 @@  discard block
 block discarded – undo
3723 3723
 	 * @param boolean $_forceCheck trigger check for existance on icServer
3724 3724
 	 * @return mixed string or false
3725 3725
 	 */
3726
-	function folderExists($_folder, $_forceCheck=false)
3726
+	function folderExists($_folder, $_forceCheck = false)
3727 3727
 	{
3728 3728
 		static $folderInfo;
3729 3729
 		$forceCheck = $_forceCheck;
3730 3730
 		if (empty($_folder))
3731 3731
 		{
3732 3732
 			// this error is more or less without significance, unless we force the check
3733
-			if ($_forceCheck===true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3733
+			if ($_forceCheck === true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3734 3734
 			return false;
3735 3735
 		}
3736 3736
 		// when check is not enforced , we assume a folder represented as Horde_Imap_Client_Mailbox as existing folder
3737
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")&&$_forceCheck===false) return true;
3738
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")) $_folder =  $_folder->utf8;
3737
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox") && $_forceCheck === false) return true;
3738
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox")) $_folder = $_folder->utf8;
3739 3739
 		// reduce traffic within the Instance per User; Expire every 5 hours
3740 3740
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Called with Folder:'.$_folder.function_backtrace());
3741
-		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),$expiration=60*60*5);
3741
+		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), $expiration = 60 * 60 * 5);
3742 3742
 		//error_log(__METHOD__.' ('.__LINE__.') '.'Cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID.($forceCheck?'(forcedCheck)':'').':'.array2string($folderInfo));
3743
-		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck===false)
3743
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck === false)
3744 3744
 		{
3745 3745
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Using cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID);
3746 3746
 			return $folderInfo[$this->profileID][$_folder];
@@ -3756,7 +3756,7 @@  discard block
 block discarded – undo
3756 3756
 
3757 3757
 		// does the folder exist???
3758 3758
 		//error_log(__METHOD__."->Connected?".$this->icServer->_connected.", ".$_folder.", ".($forceCheck?' forceCheck activated':'dont check on server'));
3759
-		if ( $forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3759
+		if ($forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3760 3760
 			//error_log(__METHOD__."->NotConnected and forceCheck with profile:".$this->profileID);
3761 3761
 			//return false;
3762 3762
 			//try to connect
@@ -3767,18 +3767,18 @@  discard block
 block discarded – undo
3767 3767
 		}
3768 3768
 		catch (\Exception $e)
3769 3769
 		{
3770
-			error_log(__METHOD__.__LINE__.$e->getMessage().($e->details?', '.$e->details:''));
3771
-			self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
3770
+			error_log(__METHOD__.__LINE__.$e->getMessage().($e->details ? ', '.$e->details : ''));
3771
+			self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
3772 3772
 			$folderInfo[$this->profileID][$_folder] = false;
3773 3773
 		}
3774 3774
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Folder Exists:'.$folderInfo[$this->profileID][$_folder].function_backtrace());
3775 3775
 
3776
-		if(!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3776
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3777 3777
 			$folderInfo[$this->profileID][$_folder] !== true)
3778 3778
 		{
3779 3779
 			$folderInfo[$this->profileID][$_folder] = false; // set to false, whatever it was (to have a valid returnvalue for the static return)
3780 3780
 		}
3781
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,$expiration=60*60*5);
3781
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, $expiration = 60 * 60 * 5);
3782 3782
 		return (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) ? $folderInfo[$this->profileID][$_folder] : false);
3783 3783
 	}
3784 3784
 
@@ -3791,14 +3791,14 @@  discard block
 block discarded – undo
3791 3791
 	 */
3792 3792
 	function compressFolder($_folderName = false)
3793 3793
 	{
3794
-		$folderName	= ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3795
-		$deleteOptions	= $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3796
-		$trashFolder	= $this->getTrashFolder();
3794
+		$folderName = ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3795
+		$deleteOptions = $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3796
+		$trashFolder = $this->getTrashFolder();
3797 3797
 
3798 3798
 		$this->icServer->openMailbox($folderName);
3799 3799
 
3800
-		if(strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3801
-			$this->deleteMessages('all',$folderName,'remove_immediately');
3800
+		if (strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3801
+			$this->deleteMessages('all', $folderName, 'remove_immediately');
3802 3802
 		} else {
3803 3803
 			$this->icServer->expunge($folderName);
3804 3804
 		}
@@ -3814,19 +3814,19 @@  discard block
 block discarded – undo
3814 3814
 	 * @return bool true, as we do not handle return values yet
3815 3815
 	 * @throws Exception
3816 3816
 	 */
3817
-	function deleteMessages($_messageUID, $_folder=NULL, $_forceDeleteMethod='no')
3817
+	function deleteMessages($_messageUID, $_folder = NULL, $_forceDeleteMethod = 'no')
3818 3818
 	{
3819 3819
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.array2string($_folder).', '.$_forceDeleteMethod);
3820 3820
 		$oldMailbox = '';
3821 3821
 		if (is_null($_folder) || empty($_folder)) $_folder = $this->sessionData['mailbox'];
3822 3822
 		if (empty($_messageUID))
3823 3823
 		{
3824
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
3824
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
3825 3825
 			return false;
3826 3826
 		}
3827
-		elseif ($_messageUID==='all')
3827
+		elseif ($_messageUID === 'all')
3828 3828
 		{
3829
-			$_messageUID= null;
3829
+			$_messageUID = null;
3830 3830
 		}
3831 3831
 		else
3832 3832
 		{
@@ -3835,32 +3835,32 @@  discard block
 block discarded – undo
3835 3835
 			$uidsToDelete->add($_messageUID);
3836 3836
 		}
3837 3837
 		$deleteOptions = $_forceDeleteMethod; // use forceDeleteMethod if not "no", or unknown method
3838
-		if ($_forceDeleteMethod === 'no' || !in_array($_forceDeleteMethod,array('move_to_trash',"mark_as_deleted","remove_immediately"))) $deleteOptions  = ($this->mailPreferences['deleteOptions']?$this->mailPreferences['deleteOptions']:"mark_as_deleted");
3838
+		if ($_forceDeleteMethod === 'no' || !in_array($_forceDeleteMethod, array('move_to_trash', "mark_as_deleted", "remove_immediately"))) $deleteOptions = ($this->mailPreferences['deleteOptions'] ? $this->mailPreferences['deleteOptions'] : "mark_as_deleted");
3839 3839
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3840 3840
 		$trashFolder    = $this->getTrashFolder();
3841
-		$draftFolder	= $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3841
+		$draftFolder = $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3842 3842
 		$templateFolder = $this->getTemplateFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['templateFolder'];
3843
-		if((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") ||
3843
+		if ((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") ||
3844 3844
 		   (strtolower($_folder) == strtolower($draftFolder))) {
3845 3845
 			$deleteOptions = "remove_immediately";
3846 3846
 		}
3847
-		if($this->icServer->getCurrentMailbox() != $_folder) {
3847
+		if ($this->icServer->getCurrentMailbox() != $_folder) {
3848 3848
 			$oldMailbox = $this->icServer->getCurrentMailbox();
3849 3849
 			$this->icServer->openMailbox($_folder);
3850 3850
 		}
3851 3851
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3852 3852
 		$updateCache = false;
3853
-		switch($deleteOptions) {
3853
+		switch ($deleteOptions) {
3854 3854
 			case "move_to_trash":
3855 3855
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3856 3856
 				$updateCache = true;
3857
-				if(!empty($trashFolder)) {
3857
+				if (!empty($trashFolder)) {
3858 3858
 					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.implode(' : ', $_messageUID));
3859
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ". $this->sessionData['mailbox']);
3859
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ".$this->sessionData['mailbox']);
3860 3860
 					// copy messages
3861 3861
 					try
3862 3862
 					{
3863
-						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete,'move'=>true));
3863
+						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete, 'move'=>true));
3864 3864
 					}
3865 3865
 					catch (\Exception $e)
3866 3866
 					{
@@ -3872,18 +3872,18 @@  discard block
 block discarded – undo
3872 3872
 			case "mark_as_deleted":
3873 3873
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3874 3874
 				// mark messages as deleted
3875
-				if (is_null($_messageUID)) $_messageUID='all';
3876
-				foreach((array)$_messageUID as $key =>$uid)
3875
+				if (is_null($_messageUID)) $_messageUID = 'all';
3876
+				foreach ((array)$_messageUID as $key =>$uid)
3877 3877
 				{
3878 3878
 					//flag messages, that are flagged for deletion as seen too
3879 3879
 					$this->flagMessages('read', $uid, $_folder);
3880 3880
 					$flags = $this->getFlags($uid);
3881 3881
 					$this->flagMessages('delete', $uid, $_folder);
3882 3882
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
3883
-					if (strpos( array2string($flags),'Deleted')!==false) $undelete[] = $uid;
3883
+					if (strpos(array2string($flags), 'Deleted') !== false) $undelete[] = $uid;
3884 3884
 					unset($flags);
3885 3885
 				}
3886
-				foreach((array)$undelete as $key =>$uid)
3886
+				foreach ((array)$undelete as $key =>$uid)
3887 3887
 				{
3888 3888
 					$this->flagMessages('undelete', $uid, $_folder);
3889 3889
 				}
@@ -3892,14 +3892,14 @@  discard block
 block discarded – undo
3892 3892
 			case "remove_immediately":
3893 3893
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3894 3894
 				$updateCache = true;
3895
-				if (is_null($_messageUID)) $_messageUID='all';
3895
+				if (is_null($_messageUID)) $_messageUID = 'all';
3896 3896
 				if (is_object($_messageUID))
3897 3897
 				{
3898 3898
 					$this->flagMessages('delete', $_messageUID, $_folder);
3899 3899
 				}
3900 3900
 				else
3901 3901
 				{
3902
-					foreach((array)$_messageUID as $key =>$uid)
3902
+					foreach ((array)$_messageUID as $key =>$uid)
3903 3903
 					{
3904 3904
 						//flag messages, that are flagged for deletion as seen too
3905 3905
 						$this->flagMessages('delete', $uid, $_folder);
@@ -3909,7 +3909,7 @@  discard block
 block discarded – undo
3909 3909
 				$this->icServer->expunge($_folder);
3910 3910
 				break;
3911 3911
 		}
3912
-		if($oldMailbox != '') {
3912
+		if ($oldMailbox != '') {
3913 3913
 			$this->icServer->openMailbox($oldMailbox);
3914 3914
 		}
3915 3915
 
@@ -3923,7 +3923,7 @@  discard block
 block discarded – undo
3923 3923
 	 *
3924 3924
 	 * @return null/array flags
3925 3925
 	 */
3926
-	function getFlags ($_messageUID) {
3926
+	function getFlags($_messageUID) {
3927 3927
 		try
3928 3928
 		{
3929 3929
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -3936,7 +3936,7 @@  discard block
 block discarded – undo
3936 3936
 				'ids' => $uidsToFetch,
3937 3937
 			));
3938 3938
 			if (is_object($headersNew)) {
3939
-				foreach($headersNew->ids() as $id) {
3939
+				foreach ($headersNew->ids() as $id) {
3940 3940
 					$_headerObject = $headersNew->get($id);
3941 3941
 					$flags = $_headerObject->getFlags();
3942 3942
 				}
@@ -3959,22 +3959,22 @@  discard block
 block discarded – undo
3959 3959
 	 *
3960 3960
 	 * @return null/boolean
3961 3961
 	 */
3962
-	function getNotifyFlags ($_messageUID, $flags=null)
3962
+	function getNotifyFlags($_messageUID, $flags = null)
3963 3963
 	{
3964 3964
 		if (self::$debug) error_log(__METHOD__.$_messageUID.' Flags:'.array2string($flags));
3965 3965
 		try
3966 3966
 		{
3967
-			if($flags===null) $flags =  $this->getFlags($_messageUID);
3967
+			if ($flags === null) $flags = $this->getFlags($_messageUID);
3968 3968
 		}
3969 3969
 		catch (\Exception $e)
3970 3970
 		{
3971 3971
 			return null;
3972 3972
 		}
3973 3973
 
3974
-		if ( stripos( array2string($flags),'MDNSent')!==false)
3974
+		if (stripos(array2string($flags), 'MDNSent') !== false)
3975 3975
 			return true;
3976 3976
 
3977
-		if ( stripos( array2string($flags),'MDNnotSent')!==false)
3977
+		if (stripos(array2string($flags), 'MDNnotSent') !== false)
3978 3978
 			return false;
3979 3979
 
3980 3980
 		return null;
@@ -3991,45 +3991,45 @@  discard block
 block discarded – undo
3991 3991
 	 *
3992 3992
 	 * @return bool true, as we do not handle icserver->setFlags returnValue
3993 3993
 	 */
3994
-	function flagMessages($_flag, $_messageUID,$_folder=NULL)
3994
+	function flagMessages($_flag, $_messageUID, $_folder = NULL)
3995 3995
 	{
3996 3996
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",$_folder /".$this->sessionData['mailbox']);
3997 3997
 		if (empty($_messageUID))
3998 3998
 		{
3999
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
3999
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
4000 4000
 			return false;
4001 4001
 		}
4002
-		$this->icServer->openMailbox(($_folder?$_folder:$this->sessionData['mailbox']));
4002
+		$this->icServer->openMailbox(($_folder ? $_folder : $this->sessionData['mailbox']));
4003 4003
 		$folder = $this->icServer->getCurrentMailbox();
4004
-		if (is_array($_messageUID)&& count($_messageUID)>50)
4004
+		if (is_array($_messageUID) && count($_messageUID) > 50)
4005 4005
 		{
4006
-			$count = $this->getMailBoxCounters($folder,true);
4007
-			if ($count->messages == count($_messageUID)) $_messageUID='all';
4006
+			$count = $this->getMailBoxCounters($folder, true);
4007
+			if ($count->messages == count($_messageUID)) $_messageUID = 'all';
4008 4008
 		}
4009 4009
 
4010
-		if ($_messageUID==='all')
4010
+		if ($_messageUID === 'all')
4011 4011
 		{
4012 4012
 			$messageUIDs = array('all');
4013 4013
 		}
4014 4014
 		else
4015 4015
 		{
4016 4016
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4017
-			$messageUIDs = array_chunk($_messageUID,50,true);
4017
+			$messageUIDs = array_chunk($_messageUID, 50, true);
4018 4018
 		}
4019 4019
 		try
4020 4020
 		{
4021
-			foreach($messageUIDs as &$uids)
4021
+			foreach ($messageUIDs as &$uids)
4022 4022
 			{
4023
-				if ($uids==='all')
4023
+				if ($uids === 'all')
4024 4024
 				{
4025
-					$uidsToModify=null;
4025
+					$uidsToModify = null;
4026 4026
 				}
4027 4027
 				else
4028 4028
 				{
4029 4029
 					$uidsToModify = new Horde_Imap_Client_Ids();
4030 4030
 					$uidsToModify->add($uids);
4031 4031
 				}
4032
-				switch($_flag) {
4032
+				switch ($_flag) {
4033 4033
 					case "delete":
4034 4034
 						$ret = $this->icServer->store($folder, array('add'=>array('\\Deleted'), 'ids'=> $uidsToModify));
4035 4035
 						break;
@@ -4053,7 +4053,7 @@  discard block
 block discarded – undo
4053 4053
 						break;
4054 4054
 					case "unread":
4055 4055
 					case "unseen":
4056
-						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen','\\Answered','$Forwarded'), 'ids'=> $uidsToModify));
4056
+						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen', '\\Answered', '$Forwarded'), 'ids'=> $uidsToModify));
4057 4057
 						break;
4058 4058
 					case "mdnsent":
4059 4059
 						$ret = $this->icServer->store($folder, array('add'=>array('MDNSent'), 'ids'=> $uidsToModify));
@@ -4111,13 +4111,13 @@  discard block
 block discarded – undo
4111 4111
 				}
4112 4112
 			}
4113 4113
 		}
4114
-		catch(Exception $e)
4114
+		catch (Exception $e)
4115 4115
 		{
4116 4116
 			error_log(__METHOD__.__LINE__.' Error, could not flag messages in folder '.$folder.' Reason:'.$e->getMessage());
4117 4117
 		}
4118 4118
 		if ($folder instanceof Horde_Imap_Client_Mailbox) $_folder = $folder->utf8;
4119 4119
 		//error_log(__METHOD__.__LINE__.'#'.$this->icServer->ImapServerId.'#'.array2string($_folder).'#');
4120
-		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder)?$_folder: $this->sessionData['mailbox'])]['uidValidity'] = 0;
4120
+		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder) ? $_folder : $this->sessionData['mailbox'])]['uidValidity'] = 0;
4121 4121
 
4122 4122
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",".($_folder?$_folder:$this->sessionData['mailbox']));
4123 4123
 		return true; // as we do not catch/examine setFlags returnValue
@@ -4138,19 +4138,19 @@  discard block
 block discarded – undo
4138 4138
 	 * @return mixed/bool true,false or new uid
4139 4139
 	 * @throws Exception
4140 4140
 	 */
4141
-	function moveMessages($_foldername, $_messageUID, $deleteAfterMove=true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4141
+	function moveMessages($_foldername, $_messageUID, $deleteAfterMove = true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4142 4142
 	{
4143
-		$source = Mail\Account::read(($_sourceProfileID?$_sourceProfileID:$this->icServer->ImapServerId))->imapServer();
4143
+		$source = Mail\Account::read(($_sourceProfileID ? $_sourceProfileID : $this->icServer->ImapServerId))->imapServer();
4144 4144
 		//$deleteOptions  = $GLOBALS['egw_info']["user"]["preferences"]["mail"]["deleteOptions"];
4145 4145
 		if (empty($_messageUID))
4146 4146
 		{
4147
-			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',',$_messageUID));
4147
+			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',', $_messageUID));
4148 4148
 			return false;
4149 4149
 		}
4150
-		elseif ($_messageUID==='all')
4150
+		elseif ($_messageUID === 'all')
4151 4151
 		{
4152 4152
 			//error_log(__METHOD__." all Message(s): ".implode(',',$_messageUID));
4153
-			$uidsToMove= null;
4153
+			$uidsToMove = null;
4154 4154
 		}
4155 4155
 		else
4156 4156
 		{
@@ -4159,7 +4159,7 @@  discard block
 block discarded – undo
4159 4159
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4160 4160
 			$uidsToMove->add($_messageUID);
4161 4161
 		}
4162
-		$sourceFolder = (!empty($currentFolder)?$currentFolder: $this->sessionData['mailbox']);
4162
+		$sourceFolder = (!empty($currentFolder) ? $currentFolder : $this->sessionData['mailbox']);
4163 4163
 		//error_log(__METHOD__.__LINE__."$_targetProfileID !== ".array2string($source->ImapServerId));
4164 4164
 		if (!is_null($_targetProfileID) && $_targetProfileID !== $source->ImapServerId)
4165 4165
 		{
@@ -4179,19 +4179,19 @@  discard block
 block discarded – undo
4179 4179
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' mailheaders:'.array2string($headersNew));
4180 4180
 
4181 4181
 			if (is_object($headersNew)) {
4182
-				$c=0;
4182
+				$c = 0;
4183 4183
 				$retUid = new Horde_Imap_Client_Ids();
4184 4184
 				// we copy chunks of 5 to avoid too much memory and/or server stress
4185 4185
 				// some servers seem not to allow/support the appendig of multiple messages. so we are down to one
4186
-				foreach($headersNew as &$_headerObject) {
4186
+				foreach ($headersNew as &$_headerObject) {
4187 4187
 					$c++;
4188 4188
 					$flags = $_headerObject->getFlags(); //unseen status seems to be lost when retrieving the full message
4189 4189
 					$date = $_headerObject->getImapDate();
4190
-					$currentDate =  new Horde_Imap_Client_DateTime();
4190
+					$currentDate = new Horde_Imap_Client_DateTime();
4191 4191
 					// if the internal Date of the message equals the current date; try using the header date
4192
-					if ($date==$currentDate)
4192
+					if ($date == $currentDate)
4193 4193
 					{
4194
-						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4194
+						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4195 4195
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#'.$headerForPrio['DATE']);
4196 4196
 						$date = new Horde_Imap_Client_DateTime($headerForPrio['DATE']);
4197 4197
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#');
@@ -4200,20 +4200,20 @@  discard block
 block discarded – undo
4200 4200
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
4201 4201
 					$body = $_headerObject->getFullMsg();
4202 4202
 					$dataNflags[] = array('data'=>$body, 'flags'=>$flags, 'internaldate'=>$date);
4203
-					if ($c==1)
4203
+					if ($c == 1)
4204 4204
 					{
4205 4205
 						$target = Mail\Account::read($_targetProfileID)->imapServer();
4206 4206
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' TargetServer:'.$_targetProfileID.' TargetFolderObject:'.array2string($_foldername));
4207 4207
 						$foldername = $target->getMailbox($_foldername);
4208 4208
 						// make sure the target folder is open and ready
4209 4209
 						$target->openMailbox($foldername);
4210
-						$ret = $target->append($foldername,$dataNflags);
4210
+						$ret = $target->append($foldername, $dataNflags);
4211 4211
 						$retUid->add($ret);
4212 4212
 						unset($dataNflags);
4213 4213
 						// sleep 500 miliseconds; AS some sERVERs seem not to be capable of the load this is
4214 4214
 						// inflicting in them. they "reply" with an unspecific IMAP Error
4215
-						time_nanosleep(0,500000);
4216
-						$c=0;
4215
+						time_nanosleep(0, 500000);
4216
+						$c = 0;
4217 4217
 					}
4218 4218
 				}
4219 4219
 				if (isset($dataNflags))
@@ -4223,7 +4223,7 @@  discard block
 block discarded – undo
4223 4223
 					$foldername = $target->getMailbox($_foldername);
4224 4224
 					// make sure the target folder is open and ready
4225 4225
 					$target->openMailbox($foldername);
4226
-					$ret = $target->append($foldername,$dataNflags);
4226
+					$ret = $target->append($foldername, $dataNflags);
4227 4227
 					$retUid->add($ret);
4228 4228
 					unset($dataNflags);
4229 4229
 				}
@@ -4234,7 +4234,7 @@  discard block
 block discarded – undo
4234 4234
 				{
4235 4235
 					$remember = $this->icServer;
4236 4236
 					$this->icServer = $source;
4237
-					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod='remove_immediately');
4237
+					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod = 'remove_immediately');
4238 4238
 					$this->icServer = $remember;
4239 4239
 				}
4240 4240
 			}
@@ -4243,7 +4243,7 @@  discard block
 block discarded – undo
4243 4243
 		{
4244 4244
 			try
4245 4245
 			{
4246
-				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove,'move'=>$deleteAfterMove));
4246
+				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove, 'move'=>$deleteAfterMove));
4247 4247
 			}
4248 4248
 			catch (exception $e)
4249 4249
 			{
@@ -4263,19 +4263,19 @@  discard block
 block discarded – undo
4263 4263
 	 * @param string $format ='' if none is passed, use user prefs
4264 4264
 	 * @return string returns the date as it is parseable by strtotime, or current timestamp if everything fails
4265 4265
 	 */
4266
-	static function _strtotime($_date='', $format='', $convert2usertime=false)
4266
+	static function _strtotime($_date = '', $format = '', $convert2usertime = false)
4267 4267
 	{
4268 4268
 		try {
4269
-			$date = new DateTime($_date);	// parse date & time including timezone (throws exception, if not parsable)
4270
-			if ($convert2usertime) $date->setUser();	// convert to user-time
4269
+			$date = new DateTime($_date); // parse date & time including timezone (throws exception, if not parsable)
4270
+			if ($convert2usertime) $date->setUser(); // convert to user-time
4271 4271
 			$date2return = $date->format($format);
4272 4272
 		}
4273
-		catch(\Exception $e)
4273
+		catch (\Exception $e)
4274 4274
 		{
4275
-			unset($e);	// not used
4275
+			unset($e); // not used
4276 4276
 
4277 4277
 			// remove last space-separated part and retry
4278
-			$parts = explode(' ',$_date);
4278
+			$parts = explode(' ', $_date);
4279 4279
 			if (count($parts) > 1)
4280 4280
 			{
4281 4281
 				array_pop($parts);
@@ -4296,12 +4296,12 @@  discard block
 block discarded – undo
4296 4296
 	 * @param mixed $_charset false or string -> Target charset, if false Mail displayCharset will be used
4297 4297
 	 * @return string
4298 4298
 	 */
4299
-	static function htmlentities($_string, $_charset=false)
4299
+	static function htmlentities($_string, $_charset = false)
4300 4300
 	{
4301 4301
 		//setting the charset (if not given)
4302
-		if ($_charset===false) $_charset = self::$displayCharset;
4302
+		if ($_charset === false) $_charset = self::$displayCharset;
4303 4303
 		$string = @htmlentities($_string, ENT_QUOTES, $_charset, false);
4304
-		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string,Translation::detect_encoding($_string),$_charset),ENT_QUOTES | ENT_IGNORE,$_charset, false);
4304
+		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string, Translation::detect_encoding($_string), $_charset), ENT_QUOTES|ENT_IGNORE, $_charset, false);
4305 4305
 		return $string;
4306 4306
 	}
4307 4307
 
@@ -4318,21 +4318,21 @@  discard block
 block discarded – undo
4318 4318
 		//$_html = str_replace("\t",' ',$_html);
4319 4319
 		//error_log(__METHOD__.__LINE__.':'.$_html);
4320 4320
 		//repair doubleencoded ampersands, and some stuff htmLawed stumbles upon with balancing switched on
4321
-		$_html = str_replace(array('&amp;amp;','<DIV><BR></DIV>',"<DIV>&nbsp;</DIV>",'<div>&nbsp;</div>','</td></font>','<br><td>','<tr></tr>','<o:p></o:p>','<o:p>','</o:p>'),
4322
-							 array('&amp;',    '<BR>',           '<BR>',             '<BR>',             '</font></td>','<td>',    '',         '',           '',  ''),$_html);
4321
+		$_html = str_replace(array('&amp;amp;', '<DIV><BR></DIV>', "<DIV>&nbsp;</DIV>", '<div>&nbsp;</div>', '</td></font>', '<br><td>', '<tr></tr>', '<o:p></o:p>', '<o:p>', '</o:p>'),
4322
+							 array('&amp;', '<BR>', '<BR>', '<BR>', '</font></td>', '<td>', '', '', '', ''), $_html);
4323 4323
 		//$_html = str_replace(array('&amp;amp;'),array('&amp;'),$_html);
4324
-		if (stripos($_html,'style')!==false) Mail\Html::replaceTagsCompletley($_html,'style'); // clean out empty or pagewide style definitions / left over tags
4325
-		if (stripos($_html,'head')!==false) Mail\Html::replaceTagsCompletley($_html,'head'); // Strip out stuff in head
4324
+		if (stripos($_html, 'style') !== false) Mail\Html::replaceTagsCompletley($_html, 'style'); // clean out empty or pagewide style definitions / left over tags
4325
+		if (stripos($_html, 'head') !== false) Mail\Html::replaceTagsCompletley($_html, 'head'); // Strip out stuff in head
4326 4326
 		//if (stripos($_html,'![if')!==false && stripos($_html,'<![endif]>')!==false) Mail\Html::replaceTagsCompletley($_html,'!\[if','<!\[endif\]>',false); // Strip out stuff in ifs
4327 4327
 		//if (stripos($_html,'!--[if')!==false && stripos($_html,'<![endif]-->')!==false) Mail\Html::replaceTagsCompletley($_html,'!--\[if','<!\[endif\]-->',false); // Strip out stuff in ifs
4328 4328
 		//error_log(__METHOD__.' ('.__LINE__.') '.$_html);
4329 4329
 
4330 4330
 		if (get_magic_quotes_gpc() === 1) $_html = stripslashes($_html);
4331 4331
 		// Strip out doctype in head, as htmlLawed cannot handle it TODO: Consider extracting it and adding it afterwards
4332
-		if (stripos($_html,'!doctype')!==false) Mail\Html::replaceTagsCompletley($_html,'!doctype');
4333
-		if (stripos($_html,'?xml:namespace')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml:namespace','/>',false);
4334
-		if (stripos($_html,'?xml version')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml version','\?>',false);
4335
-		if (strpos($_html,'!CURSOR')!==false) Mail\Html::replaceTagsCompletley($_html,'!CURSOR');
4332
+		if (stripos($_html, '!doctype') !== false) Mail\Html::replaceTagsCompletley($_html, '!doctype');
4333
+		if (stripos($_html, '?xml:namespace') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml:namespace', '/>', false);
4334
+		if (stripos($_html, '?xml version') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml version', '\?>', false);
4335
+		if (strpos($_html, '!CURSOR') !== false) Mail\Html::replaceTagsCompletley($_html, '!CURSOR');
4336 4336
 		// htmLawed filter only the 'body'
4337 4337
 		//preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $_html, $matches);
4338 4338
 		//if ($matches[2])
@@ -4343,16 +4343,16 @@  discard block
 block discarded – undo
4343 4343
 		// purify got switched to htmLawed
4344 4344
 		// some testcode to test purifying / htmlawed
4345 4345
 		//$_html = "<BLOCKQUOTE>hi <div> there </div> kram <br> </blockquote>".$_html;
4346
-		$_html = Html\HtmLawed::purify($_html,self::$htmLawed_config,array(),true);
4346
+		$_html = Html\HtmLawed::purify($_html, self::$htmLawed_config, array(), true);
4347 4347
 		//if ($hasOther) $_html = $matches[1]. $_html. $matches[3];
4348 4348
 		// clean out comments , should not be needed as purify should do the job.
4349 4349
 		$search = array(
4350
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
4351
-			'@<!--[\s\S]*?[ \t\n\r]*-->@',         // Strip multi-line comments including CDATA
4350
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
4351
+			'@<!--[\s\S]*?[ \t\n\r]*-->@', // Strip multi-line comments including CDATA
4352 4352
 		);
4353
-		$_html = preg_replace($search,"",$_html);
4353
+		$_html = preg_replace($search, "", $_html);
4354 4354
 		// remove non printable chars
4355
-		$_html = preg_replace('/([\000-\011])/','',$_html);
4355
+		$_html = preg_replace('/([\000-\011])/', '', $_html);
4356 4356
 		//error_log(__METHOD__.':'.__LINE__.':'.$_html);
4357 4357
 	}
4358 4358
 
@@ -4369,12 +4369,12 @@  discard block
 block discarded – undo
4369 4369
 	function getMimePartCharset($_mimePartObject)
4370 4370
 	{
4371 4371
 		//$charSet = 'iso-8859-1';//self::$displayCharset; //'iso-8859-1'; // self::displayCharset seems to be asmarter fallback than iso-8859-1
4372
-		$CharsetFound=false;
4372
+		$CharsetFound = false;
4373 4373
 		//echo "#".$_mimePartObject->encoding.'#<br>';
4374
-		if(is_array($_mimePartObject->parameters)) {
4375
-			if(isset($_mimePartObject->parameters['CHARSET'])) {
4374
+		if (is_array($_mimePartObject->parameters)) {
4375
+			if (isset($_mimePartObject->parameters['CHARSET'])) {
4376 4376
 				$charSet = $_mimePartObject->parameters['CHARSET'];
4377
-				$CharsetFound=true;
4377
+				$CharsetFound = true;
4378 4378
 			}
4379 4379
 		}
4380 4380
 		// this one is dirty, but until I find something that does the trick of detecting the encoding, ....
@@ -4393,7 +4393,7 @@  discard block
 block discarded – undo
4393 4393
 	function decodeMimePart($_mimeMessage, $_encoding, $_charset = '')
4394 4394
 	{
4395 4395
 		// decode the part
4396
-		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage,true));
4396
+		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage, true));
4397 4397
 		switch (strtoupper($_encoding))
4398 4398
 		{
4399 4399
 			case 'BASE64':
@@ -4428,16 +4428,16 @@  discard block
 block discarded – undo
4428 4428
 	 * @param Horde_Mime_Part& $partCalendar =null on return text/calendar part, if one was contained or false
4429 4429
 	 * @return array containing the desired part
4430 4430
 	 */
4431
-	function getMultipartAlternative($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$partCalendar=null)
4431
+	function getMultipartAlternative($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$partCalendar = null)
4432 4432
 	{
4433 4433
 		// a multipart/alternative has exactly 2 parts (text and html  OR  text and something else)
4434 4434
 		// sometimes there are 3 parts, when there is an ics/ical attached/included-> we want to show that
4435 4435
 		// as attachment AND as abstracted ical information (we use our notification style here).
4436 4436
 		$partText = $partCalendar = $partHTML = null;
4437
-		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__,"LINE"=>__LINE__,"STRUCTURE"=>$_structure));
4437
+		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__, "LINE"=>__LINE__, "STRUCTURE"=>$_structure));
4438 4438
 		//error_log(__METHOD__.' ('.__LINE__.') ');
4439 4439
 		$ignore_first_part = true;
4440
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4440
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4441 4441
 		{
4442 4442
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type"." ignoreFirstPart:".$ignore_first_part);
4443 4443
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4445,15 +4445,15 @@  discard block
 block discarded – undo
4445 4445
 			if ($ignore_first_part)
4446 4446
 			{
4447 4447
 				$ignore_first_part = false;
4448
-				continue;	// ignore multipart/alternative itself
4448
+				continue; // ignore multipart/alternative itself
4449 4449
 			}
4450 4450
 
4451 4451
 			$mimePart = $_structure->getPart($mime_id);
4452 4452
 
4453
-			switch($mimePart->getPrimaryType())
4453
+			switch ($mimePart->getPrimaryType())
4454 4454
 			{
4455 4455
 				case 'text':
4456
-					switch($mimePart->getSubType())
4456
+					switch ($mimePart->getSubType())
4457 4457
 					{
4458 4458
 						case 'plain':
4459 4459
 							if ($mimePart->getBytes() > 0) $partText = $mimePart;
@@ -4470,7 +4470,7 @@  discard block
 block discarded – undo
4470 4470
 					break;
4471 4471
 
4472 4472
 				case 'multipart':
4473
-					switch($mimePart->getSubType())
4473
+					switch ($mimePart->getSubType())
4474 4474
 					{
4475 4475
 						case 'related':
4476 4476
 						case 'mixed':
@@ -4492,13 +4492,13 @@  discard block
 block discarded – undo
4492 4492
 			}
4493 4493
 		}
4494 4494
 
4495
-		switch($_htmlMode)
4495
+		switch ($_htmlMode)
4496 4496
 		{
4497 4497
 			case 'html_only':
4498 4498
 			case 'always_display':
4499 4499
 				if ($partHTML)
4500 4500
 				{
4501
-					switch($partHTML->getSubType())
4501
+					switch ($partHTML->getSubType())
4502 4502
 					{
4503 4503
 						case 'related':
4504 4504
 							return $this->getMultipartRelated($_uid, $partHTML, $_htmlMode, $_preserveSeen);
@@ -4510,7 +4510,7 @@  discard block
 block discarded – undo
4510 4510
 							return $this->getTextPart($_uid, $partHTML, $_htmlMode, $_preserveSeen);
4511 4511
 					}
4512 4512
 				}
4513
-				elseif ($partText && $_htmlMode=='always_display')
4513
+				elseif ($partText && $_htmlMode == 'always_display')
4514 4514
 				{
4515 4515
 					return $this->getTextPart($_uid, $partText, $_htmlMode, $_preserveSeen);
4516 4516
 				}
@@ -4556,7 +4556,7 @@  discard block
 block discarded – undo
4556 4556
 	 * @param array	&$skipParts - passed by reference to have control/knowledge which parts are already fetched
4557 4557
 	 * @return array containing the desired part
4558 4558
 	 */
4559
-	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts=array())
4559
+	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts = array())
4560 4560
 	{
4561 4561
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlMode<br>";
4562 4562
 		$bodyPart = array();
@@ -4565,7 +4565,7 @@  discard block
 block discarded – undo
4565 4565
 		$ignore_first_part = true;
4566 4566
 		//$skipParts = array();
4567 4567
 		//error_log(__METHOD__.__LINE__.array2string($_structure->contentTypeMap()));
4568
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4568
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4569 4569
 		{
4570 4570
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type");
4571 4571
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4573,9 +4573,9 @@  discard block
 block discarded – undo
4573 4573
 			{
4574 4574
 				$ignore_first_part = false;
4575 4575
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED FirstPart $mime_id: $mime_type");
4576
-				continue;	// ignore multipart/mixed itself
4576
+				continue; // ignore multipart/mixed itself
4577 4577
 			}
4578
-			if (array_key_exists($mime_id,$skipParts))
4578
+			if (array_key_exists($mime_id, $skipParts))
4579 4579
 			{
4580 4580
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED $mime_id: $mime_type");
4581 4581
 				continue;
@@ -4583,11 +4583,11 @@  discard block
 block discarded – undo
4583 4583
 
4584 4584
 			$part = $_structure->getPart($mime_id);
4585 4585
 
4586
-			switch($part->getPrimaryType())
4586
+			switch ($part->getPrimaryType())
4587 4587
 			{
4588 4588
 				case 'multipart':
4589 4589
 					if ($part->getDisposition() == 'attachment') continue;
4590
-					switch($part->getSubType())
4590
+					switch ($part->getSubType())
4591 4591
 					{
4592 4592
 						case 'alternative':
4593 4593
 							return array($this->getMultipartAlternative($_uid, $part, $_htmlMode, $_preserveSeen));
@@ -4603,15 +4603,15 @@  discard block
 block discarded – undo
4603 4603
 					}
4604 4604
 					break;
4605 4605
 				case 'application':
4606
-					switch($part->getSubType())
4606
+					switch ($part->getSubType())
4607 4607
 					{
4608 4608
 						case 'pgp-encrypted':
4609
-							if (($part = $_structure->getPart($mime_id+1)) &&
4609
+							if (($part = $_structure->getPart($mime_id + 1)) &&
4610 4610
 								$part->getType() == 'application/octet-stream')
4611 4611
 							{
4612 4612
 								$this->fetchPartContents($_uid, $part);
4613
-								$skipParts[$mime_id]=$mime_type;
4614
-								$skipParts[$mime_id+1]=$part->getType();
4613
+								$skipParts[$mime_id] = $mime_type;
4614
+								$skipParts[$mime_id + 1] = $part->getType();
4615 4615
 								$bodyPart[] = array(
4616 4616
 									'body'		=> $part->getContents(array(
4617 4617
 										'stream' => false,
@@ -4625,15 +4625,15 @@  discard block
 block discarded – undo
4625 4625
 					break;
4626 4626
 
4627 4627
 				case 'text':
4628
-					switch($part->getSubType())
4628
+					switch ($part->getSubType())
4629 4629
 					{
4630 4630
 						case 'plain':
4631 4631
 						case 'html':
4632 4632
 						case 'calendar': // inline ics/ical files
4633
-							if($part->getDisposition() != 'attachment')
4633
+							if ($part->getDisposition() != 'attachment')
4634 4634
 							{
4635 4635
 								$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4636
-								$skipParts[$mime_id]=$mime_type;
4636
+								$skipParts[$mime_id] = $mime_type;
4637 4637
 							}
4638 4638
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$part->type."/".$part->subType.' -> BodyPart:'.array2string($bodyPart[count($bodyPart)-1]));
4639 4639
 							break;
@@ -4642,16 +4642,16 @@  discard block
 block discarded – undo
4642 4642
 
4643 4643
 				case 'message':
4644 4644
 					//skip attachments
4645
-					if($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4645
+					if ($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4646 4646
 					{
4647 4647
 						$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4648
-						$skipParts[$mime_id]=$mime_type;
4648
+						$skipParts[$mime_id] = $mime_type;
4649 4649
 					}
4650 4650
 					// do not descend into attached Messages
4651
-					if($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4651
+					if ($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4652 4652
 					{
4653 4653
 						$skipParts[$mime_id.'.0'] = $mime_type;
4654
-						foreach($part->contentTypeMap() as $sub_id => $sub_type){ $skipParts[$sub_id] = $sub_type;}
4654
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { $skipParts[$sub_id] = $sub_type; }
4655 4655
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$_uid.' Part:'.$mime_id.':'.array2string($skipParts));
4656 4656
 						//break 2;
4657 4657
 					}
@@ -4692,13 +4692,13 @@  discard block
 block discarded – undo
4692 4692
 	 * @param boolean $_tryDecodingServerside = true; wether to try to fetch Data with BINARY instead of BODY
4693 4693
 	 * @return string|resource
4694 4694
 	 */
4695
-	function getBodyPart($_uid, $_partID=null, $_folder=null, $_preserveSeen=false, $_stream=false, &$_encoding=null, $_tryDecodingServerside=true)
4695
+	function getBodyPart($_uid, $_partID = null, $_folder = null, $_preserveSeen = false, $_stream = false, &$_encoding = null, $_tryDecodingServerside = true)
4696 4696
 	{
4697
-		if (self::$debug) error_log( __METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4697
+		if (self::$debug) error_log(__METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4698 4698
 
4699 4699
 		if (empty($_folder))
4700 4700
 		{
4701
-			$_folder = (isset($this->sessionData['mailbox'])&&$this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4701
+			$_folder = (isset($this->sessionData['mailbox']) && $this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4702 4702
 		}
4703 4703
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_folder).'/'.$this->icServer->getCurrentMailbox().'/'. $this->sessionData['mailbox']);
4704 4704
 		// querying contents of body part
@@ -4709,11 +4709,11 @@  discard block
 block discarded – undo
4709 4709
 		$fquery = new Horde_Imap_Client_Fetch_Query();
4710 4710
 		$fetchParams = array(
4711 4711
 			'peek' => $_preserveSeen,
4712
-			'decode' => true,	// try decode on server, does NOT neccessary work
4712
+			'decode' => true, // try decode on server, does NOT neccessary work
4713 4713
 		);
4714
-		if ($_tryDecodingServerside===false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4714
+		if ($_tryDecodingServerside === false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4715 4715
 		{
4716
-			$_tryDecodingServerside=false;
4716
+			$_tryDecodingServerside = false;
4717 4717
 			$fetchParams = array(
4718 4718
 				'peek' => $_preserveSeen,
4719 4719
 			);
@@ -4733,12 +4733,12 @@  discard block
 block discarded – undo
4733 4733
 		}
4734 4734
 		// if we get an empty result, server may have trouble fetching data with UID FETCH $_uid (BINARY.PEEK[$_partID])
4735 4735
 		// thus we trigger a second go with UID FETCH $_uid (BODY.PEEK[$_partID])
4736
-		if (empty($partToReturn)&&$_tryDecodingServerside===true)
4736
+		if (empty($partToReturn) && $_tryDecodingServerside === true)
4737 4737
 		{
4738 4738
 			error_log(__METHOD__.__LINE__.' failed to fetch bodyPart in  BINARY. Try BODY');
4739 4739
 			$partToReturn = $this->getBodyPart($_uid, $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, false);
4740 4740
 		}
4741
-		return ($partToReturn?$partToReturn:null);
4741
+		return ($partToReturn ? $partToReturn : null);
4742 4742
 	}
4743 4743
 
4744 4744
 	/**
@@ -4751,13 +4751,13 @@  discard block
 block discarded – undo
4751 4751
 	 * @param boolean $_stream = false true return a stream, false return string
4752 4752
 	 * @return array containing the desired text part, mimeType and charset
4753 4753
 	 */
4754
-	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode='', $_preserveSeen=false, $_stream=false)
4754
+	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode = '', $_preserveSeen = false, $_stream = false)
4755 4755
 	{
4756 4756
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_uid.':'.array2string($_structure).' '.function_backtrace());
4757 4757
 		$bodyPart = array();
4758
-		if (self::$debug) _debug_array(array($_structure,function_backtrace()));
4758
+		if (self::$debug) _debug_array(array($_structure, function_backtrace()));
4759 4759
 
4760
-		if($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4760
+		if ($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4761 4761
 		{
4762 4762
 			$bodyPart = array(
4763 4763
 				'error'		=> 1,
@@ -4804,10 +4804,10 @@  discard block
 block discarded – undo
4804 4804
 	 * @param Horde_Mime_part& $calendar_part =null on return calendar-part or null, if there is none
4805 4805
 	 * @return array containing the message body, mimeType and charset
4806 4806
 	 */
4807
-	function getMessageBody($_uid, $_htmlOptions='', $_partID=null, Horde_Mime_Part $_structure=null, $_preserveSeen = false, $_folder = '', &$calendar_part=null)
4807
+	function getMessageBody($_uid, $_htmlOptions = '', $_partID = null, Horde_Mime_Part $_structure = null, $_preserveSeen = false, $_folder = '', &$calendar_part = null)
4808 4808
 	{
4809 4809
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlOptions, $_partID<br>";
4810
-		if($_htmlOptions != '') {
4810
+		if ($_htmlOptions != '') {
4811 4811
 			$this->htmlOptions = $_htmlOptions;
4812 4812
 		}
4813 4813
 		if (empty($_folder))
@@ -4828,7 +4828,7 @@  discard block
 block discarded – undo
4828 4828
 			return array(
4829 4829
 				array(
4830 4830
 					'error'		=> 1,
4831
-					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions". 'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4831
+					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions".'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4832 4832
 					'mimeType'	=> 'text/plain',
4833 4833
 					'charSet'	=> self::$displayCharset,
4834 4834
 				)
@@ -4841,7 +4841,7 @@  discard block
 block discarded – undo
4841 4841
 			//_debug_array($_structure->getMimeId()); exit;
4842 4842
 		}
4843 4843
 
4844
-		switch($_structure->getPrimaryType())
4844
+		switch ($_structure->getPrimaryType())
4845 4845
 		{
4846 4846
 			case 'application':
4847 4847
 				return array(
@@ -4853,7 +4853,7 @@  discard block
 block discarded – undo
4853 4853
 				);
4854 4854
 
4855 4855
 			case 'multipart':
4856
-				switch($_structure->getSubType())
4856
+				switch ($_structure->getSubType())
4857 4857
 				{
4858 4858
 					case 'alternative':
4859 4859
 						$bodyParts = array($this->getMultipartAlternative($_uid, $_structure, $this->htmlOptions, $_preserveSeen, $calendar_part));
@@ -4887,7 +4887,7 @@  discard block
 block discarded – undo
4887 4887
 				$bodyPart = array();
4888 4888
 				if ($_structure->getDisposition() != 'attachment')
4889 4889
 				{
4890
-					switch($_structure->getSubType())
4890
+					switch ($_structure->getSubType())
4891 4891
 					{
4892 4892
 						case 'calendar':
4893 4893
 							// this is handeled in getTextPart
@@ -4903,11 +4903,11 @@  discard block
 block discarded – undo
4903 4903
 
4904 4904
 			case 'attachment':
4905 4905
 			case 'message':
4906
-				switch($_structure->getSubType())
4906
+				switch ($_structure->getSubType())
4907 4907
 				{
4908 4908
 					case 'rfc822':
4909 4909
 						$newStructure = $_structure->getParts();
4910
-						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]);}
4910
+						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]); }
4911 4911
 						return self::normalizeBodyParts($this->getMessageBody($_uid, $_htmlOptions, $newStructure[0]->getMimeId(), $newStructure[0], $_preserveSeen, $_folder));
4912 4912
 				}
4913 4913
 				break;
@@ -4935,11 +4935,11 @@  discard block
 block discarded – undo
4935 4935
 	{
4936 4936
 		if (is_array($_bodyParts))
4937 4937
 		{
4938
-			foreach($_bodyParts as $singleBodyPart)
4938
+			foreach ($_bodyParts as $singleBodyPart)
4939 4939
 			{
4940 4940
 				if (!isset($singleBodyPart['body'])) {
4941 4941
 					$buff = self::normalizeBodyParts($singleBodyPart);
4942
-					foreach ((array)$buff as $val) { $body2return[] = $val;}
4942
+					foreach ((array)$buff as $val) { $body2return[] = $val; }
4943 4943
 					continue;
4944 4944
 				}
4945 4945
 				$body2return[] = $singleBodyPart;
@@ -4960,14 +4960,14 @@  discard block
 block discarded – undo
4960 4960
 	 * @param boolean $useTidy  switch to use tidy
4961 4961
 	 * @return string a preformatted string with the mails converted to text
4962 4962
 	 */
4963
-	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false,  $useTidy = true)
4963
+	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false, $useTidy = true)
4964 4964
 	{
4965
-		$message='';
4966
-		for($i=0; $i<count($bodyParts); $i++)
4965
+		$message = '';
4966
+		for ($i = 0; $i < count($bodyParts); $i++)
4967 4967
 		{
4968 4968
 			if (!isset($bodyParts[$i]['body'])) {
4969 4969
 				$bodyParts[$i]['body'] = self::getdisplayableBody($mailClass, $bodyParts[$i], $preserveHTML, $useTidy);
4970
-				$message .= empty($bodyParts[$i]['body'])?'':$bodyParts[$i]['body'];
4970
+				$message .= empty($bodyParts[$i]['body']) ? '' : $bodyParts[$i]['body'];
4971 4971
 				continue;
4972 4972
 			}
4973 4973
 			if (isset($bodyParts[$i]['error'])) continue;
@@ -4992,32 +4992,32 @@  discard block
 block discarded – undo
4992 4992
 				'(R)',
4993 4993
 			);
4994 4994
 
4995
-			if(($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
4995
+			if (($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
4996 4996
 				strtoupper($bodyParts[$i]['charSet']) != 'UTF-8')
4997 4997
 			{
4998
-				$bodyParts[$i]['body'] = preg_replace($sar,$rar,$bodyParts[$i]['body']);
4998
+				$bodyParts[$i]['body'] = preg_replace($sar, $rar, $bodyParts[$i]['body']);
4999 4999
 			}
5000 5000
 
5001
-			if ($bodyParts[$i]['charSet']===false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5001
+			if ($bodyParts[$i]['charSet'] === false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5002 5002
 			// add line breaks to $bodyParts
5003 5003
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
5004
-			$newBody  = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
5004
+			$newBody = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
5005 5005
 			//error_log(__METHOD__.' ('.__LINE__.') '.' MimeType:'.$bodyParts[$i]['mimeType'].'->'.$newBody);
5006 5006
 			$mailClass->activeMimeType = 'text/plain';
5007 5007
 			if ($bodyParts[$i]['mimeType'] == 'text/html') {
5008 5008
 				$mailClass->activeMimeType = $bodyParts[$i]['mimeType'];
5009 5009
 				if (!$preserveHTML)
5010 5010
 				{
5011
-					$alreadyHtmlLawed=false;
5011
+					$alreadyHtmlLawed = false;
5012 5012
 					// as Translation::convert reduces \r\n to \n and purifier eats \n -> peplace it with a single space
5013
-					$newBody = str_replace("\n"," ",$newBody);
5013
+					$newBody = str_replace("\n", " ", $newBody);
5014 5014
 					// convert HTML to text, as we dont want HTML in infologs
5015 5015
 					if ($useTidy && extension_loaded('tidy'))
5016 5016
 					{
5017 5017
 						$tidy = new tidy();
5018
-						$cleaned = $tidy->repairString($newBody, self::$tidy_config,'utf8');
5018
+						$cleaned = $tidy->repairString($newBody, self::$tidy_config, 'utf8');
5019 5019
 						// Found errors. Strip it all so there's some output
5020
-						if($tidy->getStatus() == 2)
5020
+						if ($tidy->getStatus() == 2)
5021 5021
 						{
5022 5022
 							error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$tidy->errorBuffer);
5023 5023
 						}
@@ -5028,7 +5028,7 @@  discard block
 block discarded – undo
5028 5028
 						if (!$preserveHTML)
5029 5029
 						{
5030 5030
 							// filter only the 'body', as we only want that part, if we throw away the html
5031
-							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
5031
+							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
5032 5032
 							if ($matches[2])
5033 5033
 							{
5034 5034
 								$hasOther = true;
@@ -5039,7 +5039,7 @@  discard block
 block discarded – undo
5039 5039
 					else
5040 5040
 					{
5041 5041
 						// htmLawed filter only the 'body'
5042
-						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
5042
+						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
5043 5043
 						if ($matches[2])
5044 5044
 						{
5045 5045
 							$hasOther = true;
@@ -5048,17 +5048,17 @@  discard block
 block discarded – undo
5048 5048
 						$htmLawed = new Html\HtmLawed();
5049 5049
 						// the next line should not be needed, but produces better results on HTML 2 Text conversion,
5050 5050
 						// as we switched off HTMLaweds tidy functionality
5051
-						$newBody = str_replace(array('&amp;amp;','<DIV><BR></DIV>',"<DIV>&nbsp;</DIV>",'<div>&nbsp;</div>'),array('&amp;','<BR>','<BR>','<BR>'),$newBody);
5052
-						$newBody = $htmLawed->run($newBody,self::$htmLawed_config);
5053
-						if ($hasOther && $preserveHTML) $newBody = $matches[1]. $newBody. $matches[3];
5054
-						$alreadyHtmlLawed=true;
5051
+						$newBody = str_replace(array('&amp;amp;', '<DIV><BR></DIV>', "<DIV>&nbsp;</DIV>", '<div>&nbsp;</div>'), array('&amp;', '<BR>', '<BR>', '<BR>'), $newBody);
5052
+						$newBody = $htmLawed->run($newBody, self::$htmLawed_config);
5053
+						if ($hasOther && $preserveHTML) $newBody = $matches[1].$newBody.$matches[3];
5054
+						$alreadyHtmlLawed = true;
5055 5055
 					}
5056 5056
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after purify:'.$newBody);
5057
-					if ($preserveHTML==false) $newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,true,true);
5057
+					if ($preserveHTML == false) $newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, true, true);
5058 5058
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after convertHTMLToText:'.$newBody);
5059
-					if ($preserveHTML==false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
5059
+					if ($preserveHTML == false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
5060 5060
 					/*if (!$alreadyHtmlLawed) */ $mailClass->getCleanHTML($newBody); // remove stuff we regard as unwanted
5061
-					if ($preserveHTML==false) $newBody = str_replace("<br />","\r\n",$newBody);
5061
+					if ($preserveHTML == false) $newBody = str_replace("<br />", "\r\n", $newBody);
5062 5062
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after getClean:'.$newBody);
5063 5063
 				}
5064 5064
 				$message .= $newBody;
@@ -5067,9 +5067,9 @@  discard block
 block discarded – undo
5067 5067
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after specialchars):'.$newBody);
5068 5068
 			//use Mail\Html::convertHTMLToText instead of strip_tags, (even message is plain text) as strip_tags eats away too much
5069 5069
 			//$newBody = strip_tags($newBody); //we need to fix broken tags (or just stuff like "<800 USD/p" )
5070
-			$newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,false,false);
5070
+			$newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, false, false);
5071 5071
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after strip tags):'.$newBody);
5072
-			$newBody = htmlspecialchars_decode($newBody,ENT_QUOTES);
5072
+			$newBody = htmlspecialchars_decode($newBody, ENT_QUOTES);
5073 5073
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body (after hmlspc_decode):'.$newBody);
5074 5074
 			$message .= $newBody;
5075 5075
 			//continue;
@@ -5077,27 +5077,27 @@  discard block
 block discarded – undo
5077 5077
 		return $message;
5078 5078
 	}
5079 5079
 
5080
-	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith=false)
5080
+	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith = false)
5081 5081
 	{
5082 5082
 		$lines = explode("\n", $str);
5083 5083
 		$newStr = '';
5084
-		foreach($lines as $line)
5084
+		foreach ($lines as $line)
5085 5085
 		{
5086 5086
 			// replace tabs by 8 space chars, or any tab only counts one char
5087 5087
 			//$line = str_replace("\t","        ",$line);
5088 5088
 			//$newStr .= wordwrap($line, $cols, $cut);
5089
-			$allowedLength = $cols-strlen($cut);
5089
+			$allowedLength = $cols - strlen($cut);
5090 5090
 			//dont try to break lines with links, chance is we mess up the text is way too big
5091
-			if (strlen($line) > $allowedLength && stripos($line,'href=')===false &&
5092
-				($dontbreaklinesstartingwith==false ||
5091
+			if (strlen($line) > $allowedLength && stripos($line, 'href=') === false &&
5092
+				($dontbreaklinesstartingwith == false ||
5093 5093
 				 ($dontbreaklinesstartingwith &&
5094
-				  strlen($dontbreaklinesstartingwith)>=1 &&
5095
-				  substr($line,0,strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
5094
+				  strlen($dontbreaklinesstartingwith) >= 1 &&
5095
+				  substr($line, 0, strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
5096 5096
 				 )
5097 5097
 				)
5098 5098
 			   )
5099 5099
 			{
5100
-				$s=explode(" ", $line);
5100
+				$s = explode(" ", $line);
5101 5101
 				$line = "";
5102 5102
 				$linecnt = 0;
5103 5103
 				foreach ($s as &$v) {
@@ -5105,22 +5105,22 @@  discard block
 block discarded – undo
5105 5105
 					// only break long words within the wordboundaries,
5106 5106
 					// but it may destroy links, so we check for href and dont do it if we find one
5107 5107
 					// we check for any html within the word, because we do not want to break html by accident
5108
-					if($cnt > $allowedLength && stripos($v,'href=')===false && stripos($v,'onclick=')===false && $cnt == strlen(html_entity_decode($v)))
5108
+					if ($cnt > $allowedLength && stripos($v, 'href=') === false && stripos($v, 'onclick=') === false && $cnt == strlen(html_entity_decode($v)))
5109 5109
 					{
5110
-						$v=wordwrap($v, $allowedLength, $cut, true);
5110
+						$v = wordwrap($v, $allowedLength, $cut, true);
5111 5111
 					}
5112 5112
 					// the rest should be broken at the start of the new word that exceeds the limit
5113
-					if ($linecnt+$cnt > $allowedLength) {
5114
-						$v=$cut.$v;
5113
+					if ($linecnt + $cnt > $allowedLength) {
5114
+						$v = $cut.$v;
5115 5115
 						#$linecnt = 0;
5116
-						$linecnt =strlen($v)-strlen($cut);
5116
+						$linecnt = strlen($v) - strlen($cut);
5117 5117
 					} else {
5118 5118
 						$linecnt += $cnt;
5119 5119
 					}
5120 5120
 					if (strlen($v)) $line .= (strlen($line) ? " " : "").$v;
5121 5121
 				}
5122 5122
 			}
5123
-			$newStr .= $line . "\n";
5123
+			$newStr .= $line."\n";
5124 5124
 		}
5125 5125
 		return $newStr;
5126 5126
 	}
@@ -5135,12 +5135,12 @@  discard block
 block discarded – undo
5135 5135
 	 * @param boolean $_useHeaderInsteadOfEnvelope - force getMessageHeader method to be used for fetching Envelope Information
5136 5136
 	 * @return array the message header
5137 5137
 	 */
5138
-	function getMessageEnvelope($_uid, $_partID = '',$decode=false, $_folder='', $_useHeaderInsteadOfEnvelope=false)
5138
+	function getMessageEnvelope($_uid, $_partID = '', $decode = false, $_folder = '', $_useHeaderInsteadOfEnvelope = false)
5139 5139
 	{
5140 5140
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder".function_backtrace());
5141
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5141
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5142 5142
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder");
5143
-		if((empty($_partID)||$_partID=='null')&&$_useHeaderInsteadOfEnvelope===false) {
5143
+		if ((empty($_partID) || $_partID == 'null') && $_useHeaderInsteadOfEnvelope === false) {
5144 5144
 			$uidsToFetch = new Horde_Imap_Client_Ids();
5145 5145
 			if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5146 5146
 			$uidsToFetch->add($_uid);
@@ -5153,7 +5153,7 @@  discard block
 block discarded – undo
5153 5153
 				'ids' => $uidsToFetch,
5154 5154
 			));
5155 5155
 			if (is_object($headersNew)) {
5156
-				foreach($headersNew as &$_headerObject) {
5156
+				foreach ($headersNew as &$_headerObject) {
5157 5157
 					$env = $_headerObject->getEnvelope();
5158 5158
 					//_debug_array($envFields->singleFields());
5159 5159
 					$singleFields = $envFields->singleFields();
@@ -5168,34 +5168,34 @@  discard block
 block discarded – undo
5168 5168
 							case 'bcc':
5169 5169
 							case 'sender':
5170 5170
 								//error_log(__METHOD__.' ('.__LINE__.') '.$v.'->'.array2string($env->$v->addresses));
5171
-								$envelope[$v]=$env->$v->addresses;
5171
+								$envelope[$v] = $env->$v->addresses;
5172 5172
 								$address = array();
5173 5173
 								if (!is_array($envelope[$v])) break;
5174 5174
 								foreach ($envelope[$v] as $k => $ad)
5175 5175
 								{
5176
-									if (stripos($ad,'@')===false)
5176
+									if (stripos($ad, '@') === false)
5177 5177
 									{
5178
-										$remember=$k;
5178
+										$remember = $k;
5179 5179
 									}
5180 5180
 									else
5181 5181
 									{
5182
-										$address[] = (!is_null($remember)?$envelope[$v][$remember].' ':'').$ad;
5183
-										$remember=null;
5182
+										$address[] = (!is_null($remember) ? $envelope[$v][$remember].' ' : '').$ad;
5183
+										$remember = null;
5184 5184
 									}
5185 5185
 								}
5186 5186
 								$envelope[$v] = $address;
5187 5187
 								break;
5188 5188
 							case 'date':
5189
-								$envelope[$v]=DateTime::to($env->$v);
5189
+								$envelope[$v] = DateTime::to($env->$v);
5190 5190
 								break;
5191 5191
 							default:
5192
-								$envelope[$v]=$env->$v;
5192
+								$envelope[$v] = $env->$v;
5193 5193
 						}
5194 5194
 					}
5195
-					$envelope['size']=$_headerObject->getSize();
5195
+					$envelope['size'] = $_headerObject->getSize();
5196 5196
 				}
5197 5197
 			}
5198
-			$envelope = array_change_key_case($envelope,CASE_UPPER);
5198
+			$envelope = array_change_key_case($envelope, CASE_UPPER);
5199 5199
 			//if ($decode) _debug_array($envelope);
5200 5200
 			//error_log(__METHOD__.' ('.__LINE__.') '.array2string($envelope));
5201 5201
 			if ($decode)
@@ -5203,19 +5203,19 @@  discard block
 block discarded – undo
5203 5203
 				foreach ($envelope as $key => $rvV)
5204 5204
 				{
5205 5205
 					//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5206
-					$envelope[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5206
+					$envelope[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5207 5207
 				}
5208 5208
 			}
5209 5209
 			return $envelope;
5210 5210
 		} else {
5211 5211
 
5212
-			$headers = $this->getMessageHeader($_uid, $_partID, true,true,$_folder);
5212
+			$headers = $this->getMessageHeader($_uid, $_partID, true, true, $_folder);
5213 5213
 
5214 5214
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($headers));
5215 5215
 			//_debug_array($headers);
5216 5216
 			$newData = array(
5217 5217
 				'DATE'		=> $headers['DATE'],
5218
-				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']):$headers['SUBJECT']),
5218
+				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']) : $headers['SUBJECT']),
5219 5219
 				'MESSAGE_ID'	=> $headers['MESSAGE-ID']
5220 5220
 			);
5221 5221
 			if (isset($headers['IN-REPLY-TO'])) $newData['IN-REPLY-TO'] = $headers['IN-REPLY-TO'];
@@ -5226,11 +5226,11 @@  discard block
 block discarded – undo
5226 5226
 			if (isset($headers['SIZE'])) $newData['SIZE'] = $headers['SIZE'];
5227 5227
 			//_debug_array($newData);
5228 5228
 			$recepientList = array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO');
5229
-			foreach($recepientList as $recepientType) {
5230
-				if(isset($headers[$recepientType])) {
5231
-					if ($decode) $headers[$recepientType] =  self::decode_header($headers[$recepientType],true);
5229
+			foreach ($recepientList as $recepientType) {
5230
+				if (isset($headers[$recepientType])) {
5231
+					if ($decode) $headers[$recepientType] = self::decode_header($headers[$recepientType], true);
5232 5232
 					//error_log(__METHOD__.__LINE__." ".$recepientType."->".array2string($headers[$recepientType]));
5233
-					foreach(self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5233
+					foreach (self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5234 5234
 						$addressData = array(
5235 5235
 							'PERSONAL_NAME'		=> $singleAddress->personal ? $singleAddress->personal : 'NIL',
5236 5236
 							'AT_DOMAIN_LIST'	=> $singleAddress->adl ? $singleAddress->adl : 'NIL',
@@ -5238,15 +5238,15 @@  discard block
 block discarded – undo
5238 5238
 							'HOST_NAME'		=> $singleAddress->host ? $singleAddress->host : 'NIL',
5239 5239
 							'EMAIL'			=> $singleAddress->host ? $singleAddress->mailbox.'@'.$singleAddress->host : $singleAddress->mailbox,
5240 5240
 						);
5241
-						if($addressData['PERSONAL_NAME'] != 'NIL') {
5241
+						if ($addressData['PERSONAL_NAME'] != 'NIL') {
5242 5242
 							$addressData['RFC822_EMAIL'] = imap_rfc822_write_address($singleAddress->mailbox, $singleAddress->host, $singleAddress->personal);
5243 5243
 						} else {
5244 5244
 							$addressData['RFC822_EMAIL'] = 'NIL';
5245 5245
 						}
5246
-						$newData[$recepientType][] = ($addressData['RFC822_EMAIL']!='NIL'?$addressData['RFC822_EMAIL']:$addressData['EMAIL']);//$addressData;
5246
+						$newData[$recepientType][] = ($addressData['RFC822_EMAIL'] != 'NIL' ? $addressData['RFC822_EMAIL'] : $addressData['EMAIL']); //$addressData;
5247 5247
 					}
5248 5248
 				} else {
5249
-					if($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5249
+					if ($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5250 5250
 						$newData[$recepientType] = $newData['FROM'];
5251 5251
 					} else {
5252 5252
 						$newData[$recepientType] = array();
@@ -5268,10 +5268,10 @@  discard block
 block discarded – undo
5268 5268
 	 * @param string $_folder folder to work on
5269 5269
 	 * @return array|Horde_Mime_Headers message header as array or object
5270 5270
 	 */
5271
-	function getMessageHeader($_uid, $_partID = '',$decode=false, $preserveUnSeen=false, $_folder='')
5271
+	function getMessageHeader($_uid, $_partID = '', $decode = false, $preserveUnSeen = false, $_folder = '')
5272 5272
 	{
5273 5273
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$_uid.', '.$_partID.', '.$decode.', '.$preserveUnSeen.', '.$_folder);
5274
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5274
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5275 5275
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5276 5276
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5277 5277
 		$uidsToFetch->add($_uid);
@@ -5279,7 +5279,7 @@  discard block
 block discarded – undo
5279 5279
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5280 5280
 		if ($_partID != '')
5281 5281
 		{
5282
-			$fquery->headerText(array('id'=>$_partID,'peek'=>$preserveUnSeen));
5282
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>$preserveUnSeen));
5283 5283
 			$fquery->structure();
5284 5284
 		}
5285 5285
 		else
@@ -5292,18 +5292,18 @@  discard block
 block discarded – undo
5292 5292
 			'ids' => $uidsToFetch,
5293 5293
 		));
5294 5294
 		if (is_object($headersNew)) {
5295
-			foreach($headersNew as $_fetchObject)
5295
+			foreach ($headersNew as $_fetchObject)
5296 5296
 			{
5297
-				$headers = $_fetchObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5297
+				$headers = $_fetchObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5298 5298
 				if ($_partID != '')
5299 5299
 				{
5300 5300
 					$mailStructureObject = $_fetchObject->getStructure();
5301 5301
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5302 5302
 					{
5303
-						if ($mime_id==$_partID)
5303
+						if ($mime_id == $_partID)
5304 5304
 						{
5305 5305
 							//error_log(__METHOD__.' ('.__LINE__.') '."$mime_id == $_partID".array2string($_headerObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray()));
5306
-							$headers = $_fetchObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5306
+							$headers = $_fetchObject->getHeaderText($mime_id, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5307 5307
 							break;
5308 5308
 						}
5309 5309
 					}
@@ -5316,15 +5316,15 @@  discard block
 block discarded – undo
5316 5316
 				if (is_object($headers)) $headers->setUserAgent('EGroupware API '.$GLOBALS['egw_info']['server']['versions']['phpgwapi']);
5317 5317
 				return $headers;
5318 5318
 			}
5319
-			$retValue = is_object($headers) ? $headers->toArray():array();
5319
+			$retValue = is_object($headers) ? $headers->toArray() : array();
5320 5320
 			if ($size) $retValue['size'] = $size;
5321 5321
 		}
5322
-		$retValue = array_change_key_case($retValue,CASE_UPPER);
5322
+		$retValue = array_change_key_case($retValue, CASE_UPPER);
5323 5323
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue));
5324 5324
 		// if SUBJECT is an array, use thelast one, as we assume something with the unfolding for the subject did not work
5325 5325
 		if (is_array($retValue['SUBJECT']))
5326 5326
 		{
5327
-			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT'])-1];
5327
+			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT']) - 1];
5328 5328
 		}
5329 5329
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($decode ? self::decode_header($retValue,true):$retValue));
5330 5330
 		if ($decode)
@@ -5332,7 +5332,7 @@  discard block
 block discarded – undo
5332 5332
 			foreach ($retValue as $key => $rvV)
5333 5333
 			{
5334 5334
 				//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5335
-				$retValue[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5335
+				$retValue[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5336 5336
 			}
5337 5337
 		}
5338 5338
 		return $retValue;
@@ -5349,14 +5349,14 @@  discard block
 block discarded – undo
5349 5349
 	function getMessageRawHeader($_uid, $_partID = '', $_folder = '')
5350 5350
 	{
5351 5351
 		static $rawHeaders;
5352
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5352
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5353 5353
 		//error_log(__METHOD__.' ('.__LINE__.') '." Try Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5354 5354
 
5355
-		if (is_null($rawHeaders)||!is_array($rawHeaders)) $rawHeaders = Cache::getCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
5356
-		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5355
+		if (is_null($rawHeaders) || !is_array($rawHeaders)) $rawHeaders = Cache::getCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
5356
+		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5357 5357
 		{
5358 5358
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5359
-			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5359
+			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5360 5360
 		}
5361 5361
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5362 5362
 		$uid = $_uid;
@@ -5366,7 +5366,7 @@  discard block
 block discarded – undo
5366 5366
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5367 5367
 		if ($_partID != '')
5368 5368
 		{
5369
-			$fquery->headerText(array('id'=>$_partID,'peek'=>true));
5369
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>true));
5370 5370
 			$fquery->structure();
5371 5371
 		}
5372 5372
 		else
@@ -5377,14 +5377,14 @@  discard block
 block discarded – undo
5377 5377
 			'ids' => $uidsToFetch,
5378 5378
 		));
5379 5379
 		if (is_object($headersNew)) {
5380
-			foreach($headersNew as &$_headerObject) {
5380
+			foreach ($headersNew as &$_headerObject) {
5381 5381
 				$retValue = $_headerObject->getHeaderText();
5382 5382
 				if ($_partID != '')
5383 5383
 				{
5384 5384
 					$mailStructureObject = $_headerObject->getStructure();
5385 5385
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5386 5386
 					{
5387
-						if ($mime_id==$_partID)
5387
+						if ($mime_id == $_partID)
5388 5388
 						{
5389 5389
 							$retValue = $_headerObject->getHeaderText($mime_id);
5390 5390
 						}
@@ -5392,8 +5392,8 @@  discard block
 block discarded – undo
5392 5392
 				}
5393 5393
 			}
5394 5394
 		}
5395
-		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]=$retValue;
5396
-		Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']),$rawHeaders,60*60*1);
5395
+		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $retValue;
5396
+		Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']), $rawHeaders, 60 * 60 * 1);
5397 5397
 		return $retValue;
5398 5398
 	}
5399 5399
 
@@ -5406,25 +5406,25 @@  discard block
 block discarded – undo
5406 5406
 	{
5407 5407
 		$style = '';
5408 5408
 		if (empty($_bodyParts)) return "";
5409
-		foreach((array)$_bodyParts as $singleBodyPart) {
5409
+		foreach ((array)$_bodyParts as $singleBodyPart) {
5410 5410
 			if (!isset($singleBodyPart['body'])) {
5411 5411
 				$singleBodyPart['body'] = self::getStyles($singleBodyPart);
5412 5412
 				$style .= $singleBodyPart['body'];
5413 5413
 				continue;
5414 5414
 			}
5415 5415
 
5416
-			if ($singleBodyPart['charSet']===false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5416
+			if ($singleBodyPart['charSet'] === false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5417 5417
 			$singleBodyPart['body'] = Translation::convert(
5418 5418
 				$singleBodyPart['body'],
5419 5419
 				strtolower($singleBodyPart['charSet'])
5420 5420
 			);
5421 5421
 			$ct = 0;
5422
-			$newStyle=array();
5423
-			if (stripos($singleBodyPart['body'],'<style')!==false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5424
-			if ($ct>0)
5422
+			$newStyle = array();
5423
+			if (stripos($singleBodyPart['body'], '<style') !== false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5424
+			if ($ct > 0)
5425 5425
 			{
5426 5426
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$ct.'#'.array2string($newStyle));
5427
-				$style2buffer = implode('',$newStyle[0]);
5427
+				$style2buffer = implode('', $newStyle[0]);
5428 5428
 			}
5429 5429
 			if ($style2buffer && strtoupper(self::$displayCharset) == 'UTF-8')
5430 5430
 			{
@@ -5432,7 +5432,7 @@  discard block
 block discarded – undo
5432 5432
 				$test = json_encode($style2buffer);
5433 5433
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$test.'# ->'.strlen($style2buffer).' Error:'.json_last_error());
5434 5434
 				//if (json_last_error() != JSON_ERROR_NONE && strlen($style2buffer)>0)
5435
-				if ($test=="null" && strlen($style2buffer)>0)
5435
+				if ($test == "null" && strlen($style2buffer) > 0)
5436 5436
 				{
5437 5437
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
5438 5438
 					error_log(__METHOD__.' ('.__LINE__.') '.' Found Invalid sequence for utf-8 in CSS:'.$style2buffer.' Charset Reported:'.$singleBodyPart['charSet'].' Carset Detected:'.Translation::detect_encoding($style2buffer));
@@ -5443,19 +5443,19 @@  discard block
 block discarded – undo
5443 5443
 		}
5444 5444
 		// clean out comments and stuff
5445 5445
 		$search = array(
5446
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
5446
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
5447 5447
 //			'@<!--[\s\S]*?[ \t\n\r]*-->@',   // Strip multi-line comments including CDATA
5448 5448
 //			'@<!--[\s\S]*?[ \t\n\r]*--@',    // Strip broken multi-line comments including CDATA
5449 5449
 		);
5450
-		$style = preg_replace($search,"",$style);
5450
+		$style = preg_replace($search, "", $style);
5451 5451
 
5452 5452
 		// CSS Security
5453 5453
 		// http://code.google.com/p/browsersec/wiki/Part1#Cascading_stylesheets
5454
-		$css = preg_replace('/(javascript|expression|-moz-binding)/i','',$style);
5455
-		if (stripos($css,'script')!==false) Mail\Html::replaceTagsCompletley($css,'script'); // Strip out script that may be included
5454
+		$css = preg_replace('/(javascript|expression|-moz-binding)/i', '', $style);
5455
+		if (stripos($css, 'script') !== false) Mail\Html::replaceTagsCompletley($css, 'script'); // Strip out script that may be included
5456 5456
 		// we need this, as styledefinitions are enclosed with curly brackets; and template stuff tries to replace everything between curly brackets that is having no horizontal whitespace
5457 5457
 		// as the comments as <!-- styledefinition --> in stylesheet are outdated, and ck-editor does not understand it, we remove it
5458
-		$css = str_replace(array(':','<!--','-->'),array(': ','',''),$css);
5458
+		$css = str_replace(array(':', '<!--', '-->'), array(': ', '', ''), $css);
5459 5459
 		//error_log(__METHOD__.' ('.__LINE__.') '.$css);
5460 5460
 		// TODO: we may have to strip urls and maybe comments and ifs
5461 5461
 		return $css;
@@ -5470,16 +5470,16 @@  discard block
 block discarded – undo
5470 5470
 	 * @param boolean $_stream =false true: return a stream, false: return string, stream suppresses any caching
5471 5471
 	 * @return string the message body
5472 5472
 	 */
5473
-	function getMessageRawBody($_uid, $_partID = '', $_folder='', $_stream=false)
5473
+	function getMessageRawBody($_uid, $_partID = '', $_folder = '', $_stream = false)
5474 5474
 	{
5475 5475
 		//TODO: caching einbauen static!
5476 5476
 		static $rawBody;
5477 5477
 		if (is_null($rawBody)) $rawBody = array();
5478
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5479
-		if (!$_stream && isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5478
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5479
+		if (!$_stream && isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5480 5480
 		{
5481 5481
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Body $_uid, $_partID in Folder $_folder");
5482
-			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5482
+			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5483 5483
 		}
5484 5484
 
5485 5485
 		$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -5492,13 +5492,13 @@  discard block
 block discarded – undo
5492 5492
 		if ($_partID != '')
5493 5493
 		{
5494 5494
 			$fquery->structure();
5495
-			$fquery->bodyPart($_partID,array('peek'=>true));
5495
+			$fquery->bodyPart($_partID, array('peek'=>true));
5496 5496
 		}
5497 5497
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5498 5498
 			'ids' => $uidsToFetch,
5499 5499
 		));
5500 5500
 		if (is_object($headersNew)) {
5501
-			foreach($headersNew as &$_headerObject) {
5501
+			foreach ($headersNew as &$_headerObject) {
5502 5502
 				$body = $_headerObject->getFullMsg($_stream);
5503 5503
 				if ($_partID != '')
5504 5504
 				{
@@ -5506,7 +5506,7 @@  discard block
 block discarded – undo
5506 5506
 					//_debug_array($mailStructureObject->contentTypeMap());
5507 5507
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5508 5508
 					{
5509
-						if ($mime_id==$_partID)
5509
+						if ($mime_id == $_partID)
5510 5510
 						{
5511 5511
 							$body = $_headerObject->getBodyPart($mime_id, $_stream);
5512 5512
 						}
@@ -5517,7 +5517,7 @@  discard block
 block discarded – undo
5517 5517
 		//error_log(__METHOD__.' ('.__LINE__.') '."[$this->icServer->ImapServerId][$_folder][$_uid][".(empty($_partID)?'NIL':$_partID)."]");
5518 5518
 		if (!$_stream)
5519 5519
 		{
5520
-			$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)] = $body;
5520
+			$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $body;
5521 5521
 		}
5522 5522
 		return $body;
5523 5523
 	}
@@ -5532,13 +5532,13 @@  discard block
 block discarded – undo
5532 5532
 	 * @param Horde_Imap_Client_Fetch_Query $fquery=null default query just structure
5533 5533
 	 * @return Horde_Mime_Part
5534 5534
 	 */
5535
-	function getStructure($_uid, $_partID=null, $_folder=null, $_preserveSeen=false)
5535
+	function getStructure($_uid, $_partID = null, $_folder = null, $_preserveSeen = false)
5536 5536
 	{
5537
-		if (self::$debug) error_log( __METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5537
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5538 5538
 
5539 5539
 		if (empty($_folder))
5540 5540
 		{
5541
-			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5541
+			$_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5542 5542
 		}
5543 5543
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5544 5544
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
@@ -5556,7 +5556,7 @@  discard block
 block discarded – undo
5556 5556
 				'ids' => $uidsToFetch,
5557 5557
 			))->first();
5558 5558
 
5559
-			return is_object($mail)?$mail->getStructure():null;
5559
+			return is_object($mail) ? $mail->getStructure() : null;
5560 5560
 		}
5561 5561
 		catch (\Exception $e)
5562 5562
 		{
@@ -5579,14 +5579,14 @@  discard block
 block discarded – undo
5579 5579
 	 * @param string $_folder folder to work on
5580 5580
 	 * @return array  an array of information about the attachment: array of array(name, size, mimeType, partID, encoding)
5581 5581
 	 */
5582
-	function getMessageAttachments($_uid, $_partID=null, Horde_Mime_Part $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=false, $resolveTNEF=true, $_folder='')
5582
+	function getMessageAttachments($_uid, $_partID = null, Horde_Mime_Part $_structure = null, $fetchEmbeddedImages = true, $fetchTextCalendar = false, $resolveTNEF = true, $_folder = '')
5583 5583
 	{
5584
-		if (self::$debug) error_log( __METHOD__.":$_uid, $_partID");
5585
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5584
+		if (self::$debug) error_log(__METHOD__.":$_uid, $_partID");
5585
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5586 5586
 		$attachments = array();
5587 5587
 		if (!isset($_structure))
5588 5588
 		{
5589
-			$_structure = $this->getStructure($_uid, $_partID,$_folder,true);
5589
+			$_structure = $this->getStructure($_uid, $_partID, $_folder, true);
5590 5590
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.print_r($_structure->contentTypeMap(),true));
5591 5591
 		}
5592 5592
 		if (!$_structure || !$_structure->contentTypeMap()) return array();
@@ -5594,7 +5594,7 @@  discard block
 block discarded – undo
5594 5594
 		$skipParts = array();
5595 5595
 		$tnefParts = array();
5596 5596
 		$skip = 0;
5597
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
5597
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
5598 5598
 		{
5599 5599
 			// skip multipart/encrypted incl. its two sub-parts, as we show 2. sub-part as body to be decrypted client-side
5600 5600
 			if ($mime_type == 'multipart/encrypted')
@@ -5602,7 +5602,7 @@  discard block
 block discarded – undo
5602 5602
 				$skip = 2;
5603 5603
 				continue;
5604 5604
 			}
5605
-			elseif($skip)
5605
+			elseif ($skip)
5606 5606
 			{
5607 5607
 				$skip--;
5608 5608
 				continue;
@@ -5616,10 +5616,10 @@  discard block
 block discarded – undo
5616 5616
 			$partPrimaryType = $part->getPrimaryType();
5617 5617
 			// we only want to retrieve the attachments of the current mail, not those of possible
5618 5618
 			// attached mails
5619
-			if ($mime_type=='message/rfc822' && $_partID!=$mime_id)
5619
+			if ($mime_type == 'message/rfc822' && $_partID != $mime_id)
5620 5620
 			{
5621 5621
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
5622
-				foreach($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
5622
+				foreach ($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
5623 5623
 			}
5624 5624
 			if (empty($partDisposition) && $partPrimaryType != 'multipart' && $partPrimaryType != 'text')
5625 5625
 			{
@@ -5627,27 +5627,27 @@  discard block
 block discarded – undo
5627 5627
 				// attachment with no link to show the attachment inline.
5628 5628
 				// Considering this: we "list" everything that matches the above criteria
5629 5629
 				// as attachment in order to not loose/miss information on our data
5630
-				$partDisposition='attachment';
5630
+				$partDisposition = 'attachment';
5631 5631
 			}
5632 5632
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($skipParts));
5633
-			if (array_key_exists($mime_id,$skipParts)) continue;
5633
+			if (array_key_exists($mime_id, $skipParts)) continue;
5634 5634
 
5635 5635
 			if ($partDisposition == 'attachment' ||
5636
-				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId()=='') ||
5636
+				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId() == '') ||
5637 5637
 				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType != 'image' && $partPrimaryType != 'text' && $partPrimaryType != 'multipart') ||
5638
-				($mime_type=='image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5638
+				($mime_type == 'image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5639 5639
 				($fetchEmbeddedImages && ($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image') ||
5640 5640
 				($fetchTextCalendar && $partPrimaryType == 'text' && $part->getSubType() == 'calendar'))
5641 5641
 			{
5642 5642
 				// if type is message/rfc822 and _partID is given, and MimeID equals partID
5643 5643
 				// we attempt to fetch "ourselves"
5644
-				if ($_partID==$part->getMimeId() && $part->getPrimaryType()=='message') continue;
5644
+				if ($_partID == $part->getMimeId() && $part->getPrimaryType() == 'message') continue;
5645 5645
 				$attachment = $part->getAllDispositionParameters();
5646 5646
 				$attachment['disposition'] = $part->getDisposition();
5647 5647
 				$attachment['mimeType'] = $mime_type;
5648 5648
 				$attachment['uid'] = $_uid;
5649 5649
 				$attachment['partID'] = $mime_id;
5650
-				if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5650
+				if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5651 5651
 				if ($fetchTextCalendar)
5652 5652
 				{
5653 5653
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part->getAllContentTypeParameters()));
@@ -5657,11 +5657,11 @@  discard block
 block discarded – undo
5657 5657
 				}
5658 5658
 				$attachment['size'] = $part->getBytes();
5659 5659
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5660
-				if (empty($attachment['name'])) $attachment['name'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($mime_type);
5660
+				if (empty($attachment['name'])) $attachment['name'] = (isset($attachment['cid']) && !empty($attachment['cid']) ? $attachment['cid'] : lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($mime_type);
5661 5661
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($attachment));
5662 5662
 				//typical winmail.dat attachment is
5663 5663
 				//Array([size] => 1462762[filename] => winmail.dat[mimeType] => application/ms-tnef[uid] => 100[partID] => 2[name] => winmail.dat)
5664
-				if ($resolveTNEF && ($attachment['mimeType']=='application/ms-tnef' || !strcasecmp($attachment['name'],'winmail.dat')))
5664
+				if ($resolveTNEF && ($attachment['mimeType'] == 'application/ms-tnef' || !strcasecmp($attachment['name'], 'winmail.dat')))
5665 5665
 				{
5666 5666
 					$tnefParts[] = $attachment;
5667 5667
 				}
@@ -5676,31 +5676,31 @@  discard block
 block discarded – undo
5676 5676
 			//error_log(__METHOD__.__LINE__.array2string($tnefParts));
5677 5677
 			foreach ($tnefParts as $k => $tnp)
5678 5678
 			{
5679
-				$tnefResolved=false;
5680
-				$tnef_data = $this->getAttachment($tnp['uid'],$tnp['partID'],$k,false);
5679
+				$tnefResolved = false;
5680
+				$tnef_data = $this->getAttachment($tnp['uid'], $tnp['partID'], $k, false);
5681 5681
 				$myTnef = $this->tnef_decoder($tnef_data['attachment']);
5682 5682
 				//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
5683 5683
 				// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
5684 5684
 				// we need to build Something that meets the needs
5685 5685
 				if ($myTnef)
5686 5686
 				{
5687
-					foreach($myTnef->getParts() as $mime_id => $part)
5687
+					foreach ($myTnef->getParts() as $mime_id => $part)
5688 5688
 					{
5689
-						$tnefResolved=true;
5689
+						$tnefResolved = true;
5690 5690
 						$attachment = $part->getAllDispositionParameters();
5691 5691
 						$attachment['disposition'] = $part->getDisposition();
5692 5692
 						$attachment['mimeType'] = $part->getType();
5693 5693
 						$attachment['uid'] = $tnp['uid'];
5694 5694
 						$attachment['partID'] = $tnp['partID'];
5695 5695
 						$attachment['is_winmail'] = $tnp['uid'].'@'.$tnp['partID'].'@'.$mime_id;
5696
-						if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5696
+						if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5697 5697
 						$attachment['size'] = $part->getBytes();
5698 5698
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5699
-						if (empty($attachment['name'])) $attachment['name'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5699
+						if (empty($attachment['name'])) $attachment['name'] = (isset($attachment['cid']) && !empty($attachment['cid']) ? $attachment['cid'] : lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5700 5700
 						$attachments[] = $attachment;
5701 5701
 					}
5702 5702
 				}
5703
-				if ($tnefResolved===false) $attachments[]=$tnp;
5703
+				if ($tnefResolved === false) $attachments[] = $tnp;
5704 5704
 			}
5705 5705
 		}
5706 5706
 		//error_log(__METHOD__.__LINE__.array2string($attachments));
@@ -5715,9 +5715,9 @@  discard block
 block discarded – undo
5715 5715
 	 * @return boolean|Horde_Mime_part Multipart/Mixed part decoded attachments |
5716 5716
 	 *	return false if there's no attachments or failure
5717 5717
 	 */
5718
-	public function tnef_decoder( $data )
5718
+	public function tnef_decoder($data)
5719 5719
 	{
5720
-		foreach(array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5720
+		foreach (array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5721 5721
 		{
5722 5722
 			if (!class_exists($class))
5723 5723
 			{
@@ -5749,7 +5749,7 @@  discard block
 block discarded – undo
5749 5749
 				$tmp_part->setContents($data['stream']);
5750 5750
 				$tmp_part->setDescription($data['name']);
5751 5751
 
5752
-				$type = $data['type'] . '/' . $data['subtype'];
5752
+				$type = $data['type'].'/'.$data['subtype'];
5753 5753
 				if (in_array($type, array('application/octet-stream', 'application/base64')))
5754 5754
 				{
5755 5755
 					$type = Horde_Mime_Magic::filenameToMIME($data['name']);
@@ -5792,24 +5792,24 @@  discard block
 block discarded – undo
5792 5792
 	 *
5793 5793
 	 * @return array returns an array of all resolved embeded attachments from winmail.dat
5794 5794
 	 */
5795
-	function getTnefAttachments ($_uid, $_partID, $_stream=false)
5795
+	function getTnefAttachments($_uid, $_partID, $_stream = false)
5796 5796
 	{
5797
-		$tnef_data = $this->getAttachment($_uid, $_partID,0,false);
5797
+		$tnef_data = $this->getAttachment($_uid, $_partID, 0, false);
5798 5798
 		$tnef_parts = $this->tnef_decoder($tnef_data['attachment']);
5799 5799
 		$attachments = array();
5800 5800
 		if ($tnef_parts)
5801 5801
 		{
5802
-			foreach($tnef_parts->getParts() as $mime_id => $part)
5802
+			foreach ($tnef_parts->getParts() as $mime_id => $part)
5803 5803
 			{
5804 5804
 
5805 5805
 				$attachment = $part->getAllDispositionParameters();
5806 5806
 				$attachment['mimeType'] = $part->getType();
5807
-				if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5807
+				if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5808 5808
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5809 5809
 				if (empty($attachment['filename']))
5810 5810
 				{
5811
-					$attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?
5812
-						$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5811
+					$attachment['filename'] = (isset($attachment['cid']) && !empty($attachment['cid']) ?
5812
+						$attachment['cid'] : lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5813 5813
 				}
5814 5814
 
5815 5815
 				$attachment['attachment'] = $part->getContents(array('stream'=>$_stream));
@@ -5833,10 +5833,10 @@  discard block
 block discarded – undo
5833 5833
 	 *
5834 5834
 	 * @return array
5835 5835
 	 */
5836
-	function getAttachment($_uid, $_partID, $_winmail_nr=0, $_returnPart=true, $_stream=false, $_folder=null)
5836
+	function getAttachment($_uid, $_partID, $_winmail_nr = 0, $_returnPart = true, $_stream = false, $_folder = null)
5837 5837
 	{
5838 5838
 		//error_log(__METHOD__.__LINE__."Uid:$_uid, PartId:$_partID, WinMailNr:$_winmail_nr, ReturnPart:$_returnPart, Stream:$_stream, Folder:$_folder".function_backtrace());
5839
-		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5839
+		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5840 5840
 
5841 5841
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5842 5842
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
@@ -5849,36 +5849,36 @@  discard block
 block discarded – undo
5849 5849
 			'ids' => $uidsToFetch,
5850 5850
 		));
5851 5851
 		if (is_object($headersNew)) {
5852
-			foreach($headersNew as $id=>$_headerObject) {
5852
+			foreach ($headersNew as $id=>$_headerObject) {
5853 5853
 				$body = $_headerObject->getFullMsg();
5854 5854
 				if ($_partID != '')
5855 5855
 				{
5856 5856
 					$mailStructureObject = $_headerObject->getStructure();
5857 5857
 					$mailStructureObject->contentTypeMap();
5858 5858
 					$part = $mailStructureObject->getPart($_partID);
5859
-					$partDisposition = ($part?$part->getDisposition():'failed');
5860
-					if ($partDisposition=='failed')
5859
+					$partDisposition = ($part ? $part->getDisposition() : 'failed');
5860
+					if ($partDisposition == 'failed')
5861 5861
 					{
5862 5862
 						error_log(__METHOD__.'('.__LINE__.'):'.array2string($_uid).','.$_partID.' ID:'.$id.' HObject:'.array2string($_headerObject).' StructureObject:'.array2string($mailStructureObject->contentTypeMap()).'->'.function_backtrace());
5863 5863
 					}
5864 5864
 					// if $partDisposition is empty, we assume attachment, and hope that the function
5865 5865
 					// itself is only triggered to fetch attachments
5866
-					if (empty($partDisposition)) $partDisposition='attachment';
5867
-					if ($part && ($partDisposition=='attachment' || $partDisposition=='inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
5866
+					if (empty($partDisposition)) $partDisposition = 'attachment';
5867
+					if ($part && ($partDisposition == 'attachment' || $partDisposition == 'inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
5868 5868
 					{
5869 5869
 						//$headerObject=$part->getAllDispositionParameters();//not used anywhere around here
5870 5870
 						$structure_mime = $part->getType();
5871 5871
 						$filename = $part->getName();
5872 5872
 						$charset = $part->getContentTypeParameter('charset');
5873 5873
 						//$structure_bytes = $part->getBytes(); $structure_partID=$part->getMimeId(); error_log(__METHOD__.__LINE__." fetchPartContents(".array2string($_uid).", $structure_partID, $_stream, $_preserveSeen,$structure_mime)" );
5874
-						$this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen=true,$structure_mime);
5874
+						$this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen = true, $structure_mime);
5875 5875
 						if ($_returnPart) return $part;
5876 5876
 					}
5877 5877
 				}
5878 5878
 			}
5879 5879
 		}
5880 5880
 		$ext = MimeMagic::mime2ext($structure_mime);
5881
-		if ($ext && stripos($filename,'.')===false && stripos($filename,$ext)===false) $filename = trim($filename).'.'.$ext;
5881
+		if ($ext && stripos($filename, '.') === false && stripos($filename, $ext) === false) $filename = trim($filename).'.'.$ext;
5882 5882
 		if (!$part)
5883 5883
 		{
5884 5884
 			throw new Exception\WrongParameter("Error: Could not fetch attachment for Uid=".array2string($_uid).", PartId=$_partID, WinMailNr=$_winmail_nr, folder=$_folder");
@@ -5896,20 +5896,20 @@  discard block
 block discarded – undo
5896 5896
 		// try guessing the mimetype, if we get the application/octet-stream
5897 5897
 		if (strtolower($attachmentData['type']) == 'application/octet-stream') $attachmentData['type'] = MimeMagic::filename2mime($attachmentData['filename']);
5898 5898
 		# if the attachment holds a winmail number and is a winmail.dat then we have to handle that.
5899
-		if ( $filename == 'winmail.dat' && $_winmail_nr)
5899
+		if ($filename == 'winmail.dat' && $_winmail_nr)
5900 5900
 		{
5901 5901
 			//by now _uid is of type array
5902
-			$tnefResolved=false;
5903
-			$wantedPart=$_uid[0].'@'.$_partID;
5902
+			$tnefResolved = false;
5903
+			$wantedPart = $_uid[0].'@'.$_partID;
5904 5904
 			$myTnef = $this->tnef_decoder($attachmentData['attachment']);
5905 5905
 			//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
5906 5906
 			// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
5907 5907
 			// we need to build Something that meets the needs
5908 5908
 			if ($myTnef)
5909 5909
 			{
5910
-				foreach($myTnef->getParts() as $mime_id => $part)
5910
+				foreach ($myTnef->getParts() as $mime_id => $part)
5911 5911
 				{
5912
-					$tnefResolved=true;
5912
+					$tnefResolved = true;
5913 5913
 					$attachment = $part->getAllDispositionParameters();
5914 5914
 					$attachment['mimeType'] = $part->getType();
5915 5915
 					//error_log(__METHOD__.__LINE__.'#'.$mime_id.'#'.$filename.'#'.array2string($attachment));
@@ -5917,9 +5917,9 @@  discard block
 block discarded – undo
5917 5917
 					if ($_winmail_nr == $wantedPart.'@'.$mime_id)
5918 5918
 					{
5919 5919
 						//error_log(__METHOD__.__LINE__.'#'.$structure_mime.'#'.$filename.'#'.array2string($attachment));
5920
-						if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5920
+						if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5921 5921
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5922
-						if (empty($attachment['filename'])) $attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5922
+						if (empty($attachment['filename'])) $attachment['filename'] = (isset($attachment['cid']) && !empty($attachment['cid']) ? $attachment['cid'] : lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5923 5923
 						$wmattach = $attachment;
5924 5924
 						$wmattach['attachment'] = $part->getContents(array('stream'=>$_stream));
5925 5925
 
@@ -5929,7 +5929,7 @@  discard block
 block discarded – undo
5929 5929
 			if ($tnefResolved)
5930 5930
 			{
5931 5931
 				$ext = MimeMagic::mime2ext($wmattach['mimeType']);
5932
-				if ($ext && stripos($wmattach['filename'],'.')===false && stripos($wmattach['filename'],$ext)===false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
5932
+				if ($ext && stripos($wmattach['filename'], '.') === false && stripos($wmattach['filename'], $ext) === false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
5933 5933
 				$attachmentData = array(
5934 5934
 					'type'       => $wmattach['mimeType'],
5935 5935
 					'filename'   => $wmattach['filename'],
@@ -5953,21 +5953,21 @@  discard block
 block discarded – undo
5953 5953
 	 *	true:
5954 5954
 	 * @return Horde_Mime_Part
5955 5955
 	 */
5956
-	function getAttachmentByCID($_uid, $_cid, $_part, $_stream=null)
5956
+	function getAttachmentByCID($_uid, $_cid, $_part, $_stream = null)
5957 5957
 	{
5958 5958
 		// some static variables to avoid fetching the same mail multiple times
5959
-		static $uid=null, $part=null, $structure=null;
5959
+		static $uid = null, $part = null, $structure = null;
5960 5960
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_cid, $_part");
5961 5961
 
5962
-		if(empty($_cid)) return false;
5962
+		if (empty($_cid)) return false;
5963 5963
 
5964 5964
 		if ($_uid != $uid || $_part != $part)
5965 5965
 		{
5966
-			$structure = $this->getStructure($uid=$_uid, $part=$_part);
5966
+			$structure = $this->getStructure($uid = $_uid, $part = $_part);
5967 5967
 		}
5968 5968
 		/** @var Horde_Mime_Part */
5969 5969
 		$attachment = null;
5970
-		foreach($structure->contentTypeMap() as $mime_id => $mime_type)
5970
+		foreach ($structure->contentTypeMap() as $mime_id => $mime_type)
5971 5971
 		{
5972 5972
 			$part = $structure->getPart($mime_id);
5973 5973
 
@@ -6019,16 +6019,16 @@  discard block
 block discarded – undo
6019 6019
 	 * @param string  $_mimetype to decide wether to try to fetch part as binary or not
6020 6020
 	 * @return Horde_Mime_Part
6021 6021
 	 */
6022
-	public function fetchPartContents($_uid, Horde_Mime_Part $part=null, $_stream=false, $_preserveSeen=false, $_mimetype=null)
6022
+	public function fetchPartContents($_uid, Horde_Mime_Part $part = null, $_stream = false, $_preserveSeen = false, $_mimetype = null)
6023 6023
 	{
6024
-		if (is_null($part)) return null;//new Horde_Mime_Part;
6024
+		if (is_null($part)) return null; //new Horde_Mime_Part;
6025 6025
 		$encoding = null;
6026 6026
 		$fetchAsBinary = true;
6027
-		if ($_mimetype && strtolower($_mimetype)=='message/rfc822') $fetchAsBinary = false;
6027
+		if ($_mimetype && strtolower($_mimetype) == 'message/rfc822') $fetchAsBinary = false;
6028 6028
 		// we need to set content on structure to decode transfer encoding
6029 6029
 		$part->setContents(
6030 6030
 			$this->getBodyPart($_uid, $part->getMimeId(), null, $_preserveSeen, $_stream, $encoding, $fetchAsBinary),
6031
-			array('encoding' => (!$fetchAsBinary&&!$encoding?'8bit':$encoding)));
6031
+			array('encoding' => (!$fetchAsBinary && !$encoding ? '8bit' : $encoding)));
6032 6032
 
6033 6033
 		return $part;
6034 6034
 	}
@@ -6046,17 +6046,17 @@  discard block
 block discarded – undo
6046 6046
 	 * @return the id of the message appended or exception
6047 6047
 	 * @throws Exception\WrongUserinput
6048 6048
 	 */
6049
-	function appendMessage($_folderName, $_header, $_body, $_flags='\\Recent')
6049
+	function appendMessage($_folderName, $_header, $_body, $_flags = '\\Recent')
6050 6050
 	{
6051 6051
 		if (!is_resource($_header))
6052 6052
 		{
6053
-			if (stripos($_header,'message-id:')===false)
6053
+			if (stripos($_header, 'message-id:') === false)
6054 6054
 			{
6055 6055
 				$_header = 'Message-ID: <'.self::getRandomString().'@localhost>'."\n".$_header;
6056 6056
 			}
6057 6057
 			//error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_header, $_body, $_flags");
6058
-			$_header = ltrim(str_replace("\n","\r\n",$_header));
6059
-			$_header .= str_replace("\n","\r\n",$_body);
6058
+			$_header = ltrim(str_replace("\n", "\r\n", $_header));
6059
+			$_header .= str_replace("\n", "\r\n", $_body);
6060 6060
 		}
6061 6061
 		// the recent flag is the default enforced here ; as we assume the _flags is always set,
6062 6062
 		// we default it to hordes default (Recent) (, other wise we should not pass the parameter
@@ -6074,7 +6074,7 @@  discard block
 block discarded – undo
6074 6074
 			// searched for the message-id then returning the uid found
6075 6075
 			//$dataNflags[] = array('data'=>array(array('t'=>'text','v'=>"$header"."$body")), 'flags'=>array($_flags));
6076 6076
 			$dataNflags[] = array('data' => $_header, 'flags'=>array($_flags));
6077
-			$messageid = $this->icServer->append($_folderName,$dataNflags);
6077
+			$messageid = $this->icServer->append($_folderName, $dataNflags);
6078 6078
 		}
6079 6079
 		catch (\Exception $e)
6080 6080
 		{
@@ -6086,7 +6086,7 @@  discard block
 block discarded – undo
6086 6086
 		//$messageid = true; // for debug reasons only
6087 6087
 		if ($messageid === true || empty($messageid)) // try to figure out the message uid
6088 6088
 		{
6089
-			$list = $this->getHeaders($_folderName, $_startMessage=1, 1, 'INTERNALDATE', true, array(),null, false);
6089
+			$list = $this->getHeaders($_folderName, $_startMessage = 1, 1, 'INTERNALDATE', true, array(), null, false);
6090 6090
 			if ($list)
6091 6091
 			{
6092 6092
 				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' MessageUid:'.$messageid.' but found:'.array2string($list));
@@ -6126,27 +6126,27 @@  discard block
 block discarded – undo
6126 6126
 	 *				'attachments'=>$attachments,
6127 6127
 	 *				'headers'=>$headers,; boolean false on failure
6128 6128
 	 */
6129
-	static function get_mailcontent(&$mailClass,$uid,$partid='',$mailbox='', $preserveHTML = false, $addHeaderSection=true, $includeAttachments=true)
6129
+	static function get_mailcontent(&$mailClass, $uid, $partid = '', $mailbox = '', $preserveHTML = false, $addHeaderSection = true, $includeAttachments = true)
6130 6130
 	{
6131 6131
 			//echo __METHOD__." called for $uid,$partid <br>";
6132
-			$headers = $mailClass->getMessageHeader($uid,$partid,true,false,$mailbox);
6132
+			$headers = $mailClass->getMessageHeader($uid, $partid, true, false, $mailbox);
6133 6133
 			if (empty($headers)) return false;
6134 6134
 			// dont force retrieval of the textpart, let mailClass preferences decide
6135
-			$bodyParts = $mailClass->getMessageBody($uid,($preserveHTML?'always_display':'only_if_no_text'),$partid,null,false,$mailbox);
6135
+			$bodyParts = $mailClass->getMessageBody($uid, ($preserveHTML ? 'always_display' : 'only_if_no_text'), $partid, null, false, $mailbox);
6136 6136
 			// if we do not want HTML but there is no TextRepresentation with the message itself, try converting
6137
-			if ( !$preserveHTML && $bodyParts[0]['mimeType']=='text/html')
6137
+			if (!$preserveHTML && $bodyParts[0]['mimeType'] == 'text/html')
6138 6138
 			{
6139
-				foreach($bodyParts as $i => $part)
6139
+				foreach ($bodyParts as $i => $part)
6140 6140
 				{
6141
-					if ($bodyParts[$i]['mimeType']=='text/html')
6141
+					if ($bodyParts[$i]['mimeType'] == 'text/html')
6142 6142
 					{
6143
-						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'],$bodyParts[$i]['charSet'],true,$stripalltags=true);
6144
-						$bodyParts[$i]['mimeType']='text/plain';
6143
+						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'], $bodyParts[$i]['charSet'], true, $stripalltags = true);
6144
+						$bodyParts[$i]['mimeType'] = 'text/plain';
6145 6145
 					}
6146 6146
 				}
6147 6147
 			}
6148 6148
 			//error_log(array2string($bodyParts));
6149
-			$attachments = $includeAttachments?$mailClass->getMessageAttachments($uid,$partid,null,true,false,true,$mailbox):array();
6149
+			$attachments = $includeAttachments ? $mailClass->getMessageAttachments($uid, $partid, null, true, false, true, $mailbox) : array();
6150 6150
 
6151 6151
 			if ($mailClass->isSentFolder($mailbox)) $mailaddress = $headers['TO'];
6152 6152
 			elseif (isset($headers['FROM'])) $mailaddress = $headers['FROM'];
@@ -6157,7 +6157,7 @@  discard block
 block discarded – undo
6157 6157
 
6158 6158
 			$message = self::getdisplayableBody($mailClass, $bodyParts, $preserveHTML);
6159 6159
 			if ($preserveHTML && $mailClass->activeMimeType == 'text/plain') $message = '<pre>'.$message.'</pre>';
6160
-			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '',$preserveHTML) : '');
6160
+			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '', $preserveHTML) : '');
6161 6161
 			$message = $headdata.$message;
6162 6162
 			//echo __METHOD__.'<br>';
6163 6163
 			//_debug_array($attachments);
@@ -6173,25 +6173,25 @@  discard block
 block discarded – undo
6173 6173
 						//_debug_array($mailClass->getMessageHeader($uid, $attachment['partID']));
6174 6174
 						//_debug_array($mailClass->getMessageBody($uid,'', $attachment['partID']));
6175 6175
 						//_debug_array($mailClass->getMessageAttachments($uid, $attachment['partID']));
6176
-						$mailcontent = self::get_mailcontent($mailClass,$uid,$attachment['partID'],$mailbox);
6177
-						$headdata ='';
6176
+						$mailcontent = self::get_mailcontent($mailClass, $uid, $attachment['partID'], $mailbox);
6177
+						$headdata = '';
6178 6178
 						if ($mailcontent['headers'])
6179 6179
 						{
6180
-							$headdata = self::createHeaderInfoSection($mailcontent['headers'],'',$preserveHTML);
6180
+							$headdata = self::createHeaderInfoSection($mailcontent['headers'], '', $preserveHTML);
6181 6181
 						}
6182 6182
 						if ($mailcontent['message'])
6183 6183
 						{
6184
-							$tempname =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6184
+							$tempname = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6185 6185
 							$attachedMessages[] = array(
6186 6186
 								'type' => 'TEXT/PLAIN',
6187 6187
 								'name' => $mailcontent['subject'].'.txt',
6188 6188
 								'tmp_name' => $tempname,
6189 6189
 							);
6190
-							$tmpfile = fopen($tempname,'w');
6191
-							fwrite($tmpfile,$headdata.$mailcontent['message']);
6190
+							$tmpfile = fopen($tempname, 'w');
6191
+							fwrite($tmpfile, $headdata.$mailcontent['message']);
6192 6192
 							fclose($tmpfile);
6193 6193
 						}
6194
-						foreach($mailcontent['attachments'] as &$tmpval)
6194
+						foreach ($mailcontent['attachments'] as &$tmpval)
6195 6195
 						{
6196 6196
 							$attachedMessages[] = $tmpval;
6197 6197
 						}
@@ -6199,36 +6199,36 @@  discard block
 block discarded – undo
6199 6199
 					}
6200 6200
 					else
6201 6201
 					{
6202
-						$attachments[$num] = array_merge($attachments[$num],$mailClass->getAttachment($uid, $attachment['partID'],0,false,false));
6202
+						$attachments[$num] = array_merge($attachments[$num], $mailClass->getAttachment($uid, $attachment['partID'], 0, false, false));
6203 6203
 
6204
-						if (empty($attachments[$num]['attachment'])&&$attachments[$num]['cid'])
6204
+						if (empty($attachments[$num]['attachment']) && $attachments[$num]['cid'])
6205 6205
 						{
6206
-							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'],true);
6206
+							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'], true);
6207 6207
 							$attachments[$num]['attachment'] = $c->getContents();
6208 6208
 						}
6209 6209
 						// no attempt to convert, if we dont know about the charset
6210
-						if (isset($attachments[$num]['charset'])&&!empty($attachments[$num]['charset'])) {
6210
+						if (isset($attachments[$num]['charset']) && !empty($attachments[$num]['charset'])) {
6211 6211
 							// we do not try guessing the charset, if it is not set
6212 6212
 							//if ($attachments[$num]['charset']===false) $attachments[$num]['charset'] = Translation::detect_encoding($attachments[$num]['attachment']);
6213
-							Translation::convert($attachments[$num]['attachment'],$attachments[$num]['charset']);
6213
+							Translation::convert($attachments[$num]['attachment'], $attachments[$num]['charset']);
6214 6214
 						}
6215
-						if(in_array($attachments[$num]['name'], $file_list))
6215
+						if (in_array($attachments[$num]['name'], $file_list))
6216 6216
 						{
6217 6217
 							$dupe_count[$attachments[$num]['name']]++;
6218
-							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME) .
6219
-								' ('.($dupe_count[$attachments[$num]['name']] + 1).')' . '.' .
6218
+							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME).
6219
+								' ('.($dupe_count[$attachments[$num]['name']] + 1).')'.'.'.
6220 6220
 								pathinfo($attachments[$num]['name'], PATHINFO_EXTENSION);
6221 6221
 						}
6222 6222
 						$attachments[$num]['type'] = $attachments[$num]['mimeType'];
6223
-						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6224
-						$tmpfile = fopen($attachments[$num]['tmp_name'],'w');
6225
-						fwrite($tmpfile,$attachments[$num]['attachment']);
6223
+						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6224
+						$tmpfile = fopen($attachments[$num]['tmp_name'], 'w');
6225
+						fwrite($tmpfile, $attachments[$num]['attachment']);
6226 6226
 						fclose($tmpfile);
6227 6227
 						$file_list[] = $attachments[$num]['name'];
6228 6228
 						unset($attachments[$num]['attachment']);
6229 6229
 					}
6230 6230
 				}
6231
-				if (is_array($attachedMessages)) $attachments = array_merge($attachments,$attachedMessages);
6231
+				if (is_array($attachedMessages)) $attachments = array_merge($attachments, $attachedMessages);
6232 6232
 			}
6233 6233
 			return array(
6234 6234
 					'mailaddress'=>$mailaddress,
@@ -6250,10 +6250,10 @@  discard block
 block discarded – undo
6250 6250
 	{
6251 6251
 		$c = 0;
6252 6252
 		// use the standardIdentity
6253
-		foreach($_identities as $key => $acc) {
6254
-			if ($c==0) $identity = $acc;
6253
+		foreach ($_identities as $key => $acc) {
6254
+			if ($c == 0) $identity = $acc;
6255 6255
 			//error_log(__METHOD__.__LINE__." $key == $_profile_id ");
6256
-			if ($key==$_profile_id) $identity = $acc;
6256
+			if ($key == $_profile_id) $identity = $acc;
6257 6257
 			$c++;
6258 6258
 		}
6259 6259
 		return $identity;
@@ -6265,29 +6265,29 @@  discard block
 block discarded – undo
6265 6265
 	 * @param bool createHTML do it with HTML breaks
6266 6266
 	 * @return string a preformatted string with the information of the header worked into it
6267 6267
 	 */
6268
-	static function createHeaderInfoSection($header,$headline='', $createHTML = false)
6268
+	static function createHeaderInfoSection($header, $headline = '', $createHTML = false)
6269 6269
 	{
6270 6270
 		$headdata = null;
6271 6271
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($header).function_backtrace());
6272
-		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML?"<br />":"\n");
6273
-		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML?"<br />":"\n");
6274
-		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML?"<br />":"\n");
6275
-		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML?"<br />":"\n");
6276
-		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML?"<br />":"\n");
6277
-		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML?"<br />":"\n");
6278
-		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML?"<br />":"\n");
6279
-		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML?"<br />":"\n");
6280
-		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] !='normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML?"<br />":"\n");
6272
+		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML ? "<br />" : "\n");
6273
+		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML ? "<br />" : "\n");
6274
+		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML ? "<br />" : "\n");
6275
+		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML ? "<br />" : "\n");
6276
+		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML ? "<br />" : "\n");
6277
+		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML ? "<br />" : "\n");
6278
+		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML ? "<br />" : "\n");
6279
+		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML ? "<br />" : "\n");
6280
+		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] != 'normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML ? "<br />" : "\n");
6281 6281
 		//if ($mailcontent['headers']['ORGANIZATION']) $headdata .= lang('organization').': '.$mailcontent['headers']['ORGANIZATION']."\
6282 6282
 		if (!empty($headdata))
6283 6283
 		{
6284
-			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML?"<br />":"\n").$headdata;
6285
-			if (empty($headline)) $headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'').$headdata;
6286
-			$headdata .= ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6284
+			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML ? "<br />" : "\n").$headdata;
6285
+			if (empty($headline)) $headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '').$headdata;
6286
+			$headdata .= ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6287 6287
 		}
6288 6288
 		else
6289 6289
 		{
6290
-			$headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6290
+			$headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6291 6291
 		}
6292 6292
 		return $headdata;
6293 6293
 	}
@@ -6300,8 +6300,8 @@  discard block
 block discarded – undo
6300 6300
 	 */
6301 6301
 	static function adaptSubjectForImport($subject)
6302 6302
 	{
6303
-		$subject = str_replace('$$','__',($subject?$subject:lang('(no subject)')));
6304
-		$subject = str_ireplace(array('[FWD]','[',']','{','}','<','>'),array('Fwd:',' ',' ',' ',' ',' ',' '),trim($subject));
6303
+		$subject = str_replace('$$', '__', ($subject ? $subject : lang('(no subject)')));
6304
+		$subject = str_ireplace(array('[FWD]', '[', ']', '{', '}', '<', '>'), array('Fwd:', ' ', ' ', ' ', ' ', ' ', ' '), trim($subject));
6305 6305
 		return $subject;
6306 6306
 	}
6307 6307
 
@@ -6313,15 +6313,15 @@  discard block
 block discarded – undo
6313 6313
 	static function convertAddressArrayToString($rfcAddressArray)
6314 6314
 	{
6315 6315
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($rfcAddressArray));
6316
-		$returnAddr ='';
6316
+		$returnAddr = '';
6317 6317
 		if (is_array($rfcAddressArray))
6318 6318
 		{
6319
-			foreach((array)$rfcAddressArray as $addressData) {
6319
+			foreach ((array)$rfcAddressArray as $addressData) {
6320 6320
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($addressData));
6321
-				if($addressData['MAILBOX_NAME'] == 'NIL') {
6321
+				if ($addressData['MAILBOX_NAME'] == 'NIL') {
6322 6322
 					continue;
6323 6323
 				}
6324
-				if(strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6324
+				if (strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6325 6325
 					continue;
6326 6326
 				}
6327 6327
 				if ($addressData['RFC822_EMAIL'])
@@ -6330,7 +6330,7 @@  discard block
 block discarded – undo
6330 6330
 				}
6331 6331
 				else
6332 6332
 				{
6333
-					$emailaddress = ($addressData['PERSONAL_NAME']?$addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>':$addressData['EMAIL']);
6333
+					$emailaddress = ($addressData['PERSONAL_NAME'] ? $addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>' : $addressData['EMAIL']);
6334 6334
 					$addressObjectA = self::parseAddressList($emailaddress);
6335 6335
 				}
6336 6336
 				$addressObject = $addressObjectA[0];
@@ -6339,10 +6339,10 @@  discard block
 block discarded – undo
6339 6339
 				//$mb =(string)$addressObject->mailbox;
6340 6340
 				//$h = (string)$addressObject->host;
6341 6341
 				//$p = (string)$addressObject->personal;
6342
-				$returnAddr .= (strlen($returnAddr)>0?',':'');
6342
+				$returnAddr .= (strlen($returnAddr) > 0 ? ',' : '');
6343 6343
 				//error_log(__METHOD__.' ('.__LINE__.') '.$p.' <'.$mb.'@'.$h.'>');
6344 6344
 				$buff = imap_rfc822_write_address($addressObject->mailbox, Horde_Idna::decode($addressObject->host), $addressObject->personal);
6345
-				$buff = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$buff);
6345
+				$buff = str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $buff);
6346 6346
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Address: '.$returnAddr);
6347 6347
 				$returnAddr .= $buff;
6348 6348
 			}
@@ -6350,8 +6350,8 @@  discard block
 block discarded – undo
6350 6350
 		else
6351 6351
 		{
6352 6352
 			// do not mess with strings, return them untouched /* ToDo: validate string as Address */
6353
-			$rfcAddressArray = self::decode_header($rfcAddressArray,true);
6354
-			$rfcAddressArray = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$rfcAddressArray);
6353
+			$rfcAddressArray = self::decode_header($rfcAddressArray, true);
6354
+			$rfcAddressArray = str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $rfcAddressArray);
6355 6355
 			if (is_string($rfcAddressArray)) return $rfcAddressArray;
6356 6356
 		}
6357 6357
 		return $returnAddr;
@@ -6365,12 +6365,12 @@  discard block
 block discarded – undo
6365 6365
 	 * @param string &$err error-message on error
6366 6366
 	 * @return string/boolean merged content or false on error
6367 6367
 	 */
6368
-	static function merge($content,$ids,$mimetype='')
6368
+	static function merge($content, $ids, $mimetype = '')
6369 6369
 	{
6370 6370
 		$mergeobj = new Contacts\Merge();
6371 6371
 
6372
-		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ?'text/plain':'text/html');
6373
-		$rv = $mergeobj->merge_string($content,$ids,$err='',$mimetype, array(), self::$displayCharset);
6372
+		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ? 'text/plain' : 'text/html');
6373
+		$rv = $mergeobj->merge_string($content, $ids, $err = '', $mimetype, array(), self::$displayCharset);
6374 6374
 		if (empty($rv) && !empty($content) && !empty($err)) $rv = $content;
6375 6375
 		if (!empty($err) && !empty($content) && !empty($ids)) error_log(__METHOD__.' ('.__LINE__.') '.' Merge failed for Ids:'.array2string($ids).' ContentType:'.$mimetype.' Content:'.$content.' Reason:'.array2string($err));
6376 6376
 		return $rv;
@@ -6412,12 +6412,12 @@  discard block
 block discarded – undo
6412 6412
 		else
6413 6413
 			settype($bytes, 'integer');
6414 6414
 
6415
-		return $bytes . ' ' . $type ;
6415
+		return $bytes.' '.$type;
6416 6416
 	}
6417 6417
 
6418 6418
 	static function detect_qp(&$sting) {
6419 6419
 		$needle = '/(=[0-9][A-F])|(=[A-F][0-9])|(=[A-F][A-F])|(=[0-9][0-9])/';
6420
-		return preg_match("$needle",$string);
6420
+		return preg_match("$needle", $string);
6421 6421
 	}
6422 6422
 
6423 6423
 	/**
@@ -6430,11 +6430,11 @@  discard block
 block discarded – undo
6430 6430
 	 * @param string $_methodNline - Information where the log was taken
6431 6431
 	 * @return void
6432 6432
 	 */
6433
-	static function logRunTimes($_starttime,$_endtime=null,$_message='',$_methodNline='')
6433
+	static function logRunTimes($_starttime, $_endtime = null, $_message = '', $_methodNline = '')
6434 6434
 	{
6435 6435
 		if (is_null($_endtime)) $_endtime = microtime(true);
6436 6436
 		$usagetime = microtime(true) - $_starttime;
6437
-		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime,5).'(s) '.($_message?'Details:'.$_message:''));
6437
+		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime, 5).'(s) '.($_message ? 'Details:'.$_message : ''));
6438 6438
 	}
6439 6439
 
6440 6440
 	/**
@@ -6447,9 +6447,9 @@  discard block
 block discarded – undo
6447 6447
 	 *
6448 6448
 	 * @throws Exception\WrongUserinput
6449 6449
 	 */
6450
-	static function checkFileBasics(&$_formData, $IDtoAddToFileName='', $reqMimeType='message/rfc822')
6450
+	static function checkFileBasics(&$_formData, $IDtoAddToFileName = '', $reqMimeType = 'message/rfc822')
6451 6451
 	{
6452
-		if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6452
+		if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6453 6453
 
6454 6454
 		//error_log(__METHOD__.__FILE__.array2string($_formData).' Id:'.$IDtoAddToFileName.' ReqMimeType:'.$reqMimeType);
6455 6455
 		$importfailed = $tmpFileName = false;
@@ -6459,7 +6459,7 @@  discard block
 block discarded – undo
6459 6459
 			$importfailed = true;
6460 6460
 			$alert_msg .= lang("Empty file %1 ignored.", $_formData['name']);
6461 6461
 		}
6462
-		elseif (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6462
+		elseif (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6463 6463
 			realpath(dirname($_formData['file'])) == realpath($GLOBALS['egw_info']['server']['temp_dir']))
6464 6464
 		{
6465 6465
 			// ensure existance of eGW temp dir
@@ -6467,7 +6467,7 @@  discard block
 block discarded – undo
6467 6467
 			// and different from any other temp file location set in php.ini
6468 6468
 			if (!file_exists($GLOBALS['egw_info']['server']['temp_dir']))
6469 6469
 			{
6470
-				@mkdir($GLOBALS['egw_info']['server']['temp_dir'],0700);
6470
+				@mkdir($GLOBALS['egw_info']['server']['temp_dir'], 0700);
6471 6471
 			}
6472 6472
 
6473 6473
 			// if we were NOT able to create this temp directory, then make an ERROR report
@@ -6494,14 +6494,14 @@  discard block
 block discarded – undo
6494 6494
 			// maybe its application/octet-stream -> this may mean that we could not determine the type
6495 6495
 			// so we check for the suffix too
6496 6496
 			// trust vfs mime-types, trust the mimetype if it contains a method
6497
-			if ((substr($_formData['file'],0,6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'],'method=')===false)
6497
+			if ((substr($_formData['file'], 0, 6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'], 'method=') === false)
6498 6498
 			{
6499
-				$buff = explode('.',$_formData['name']);
6499
+				$buff = explode('.', $_formData['name']);
6500 6500
 				$suffix = '';
6501 6501
 				if (is_array($buff)) $suffix = array_pop($buff); // take the last extension to check with ext2mime
6502 6502
 				if (!empty($suffix)) $sfxMimeType = MimeMagic::ext2mime($suffix);
6503 6503
 				if (!empty($suffix) && !empty($sfxMimeType) &&
6504
-					(strlen(trim($_formData['type']))==0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6504
+					(strlen(trim($_formData['type'])) == 0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6505 6505
 				{
6506 6506
 					error_log(__METHOD__.' ('.__LINE__.') '.' Data:'.array2string($_formData));
6507 6507
 					error_log(__METHOD__.' ('.__LINE__.') '.' Form reported Mimetype:'.$_formData['type'].' but seems to be:'.$sfxMimeType);
@@ -6516,13 +6516,13 @@  discard block
 block discarded – undo
6516 6516
 			if ($reqMimeType)
6517 6517
 			{
6518 6518
 				// so if PHP did not pass any file_type info, then substitute the rfc default value
6519
-				if (substr(strtolower(trim($_formData['type'])),0,strlen($mime_type_default)) != $mime_type_default)
6519
+				if (substr(strtolower(trim($_formData['type'])), 0, strlen($mime_type_default)) != $mime_type_default)
6520 6520
 				{
6521 6521
 					if (!(strtolower(trim($_formData['type'])) == "application/octet-stream" && $sfxMimeType == $reqMimeType))
6522 6522
 					{
6523 6523
 						//error_log("Message rejected, no message/rfc. Is:".$_formData['type']);
6524 6524
 						$importfailed = true;
6525
-						$alert_msg .= lang("File rejected, no %2. Is:%1",$_formData['type'],$reqMimeType);
6525
+						$alert_msg .= lang("File rejected, no %2. Is:%1", $_formData['type'], $reqMimeType);
6526 6526
 					}
6527 6527
 					if ((strtolower(trim($_formData['type'])) != $reqMimeType && $sfxMimeType == $reqMimeType))
6528 6528
 					{
@@ -6531,17 +6531,17 @@  discard block
 block discarded – undo
6531 6531
 				}
6532 6532
 			}
6533 6533
 			// as FreeBSD seems to have problems with the generated temp names we append some more random stuff
6534
-			$randomString = chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90));
6534
+			$randomString = chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90));
6535 6535
 			$tmpFileName = $GLOBALS['egw_info']['user']['account_id'].
6536 6536
 				trim($IDtoAddToFileName).basename($_formData['file']).'_'.$randomString;
6537 6537
 
6538
-			if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs')
6538
+			if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs')
6539 6539
 			{
6540
-				$tmpFileName = $_formData['file'];	// no need to store it somewhere
6540
+				$tmpFileName = $_formData['file']; // no need to store it somewhere
6541 6541
 			}
6542 6542
 			elseif (is_uploaded_file($_formData['file']))
6543 6543
 			{
6544
-				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName);	// requirement for safe_mode!
6544
+				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName); // requirement for safe_mode!
6545 6545
 			}
6546 6546
 			else
6547 6547
 			{
@@ -6550,7 +6550,7 @@  discard block
 block discarded – undo
6550 6550
 		} else {
6551 6551
 			//error_log("Import of message ".$_formData['file']." failes to meet basic restrictions");
6552 6552
 			$importfailed = true;
6553
-			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.",$_formData['name']);
6553
+			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.", $_formData['name']);
6554 6554
 		}
6555 6555
 		if ($importfailed == true)
6556 6556
 		{
@@ -6558,7 +6558,7 @@  discard block
 block discarded – undo
6558 6558
 		}
6559 6559
 		else
6560 6560
 		{
6561
-			if (parse_url($tmpFileName,PHP_URL_SCHEME) == 'vfs')
6561
+			if (parse_url($tmpFileName, PHP_URL_SCHEME) == 'vfs')
6562 6562
 			{
6563 6563
 				Vfs::load_wrapper('vfs');
6564 6564
 			}
@@ -6583,7 +6583,7 @@  discard block
 block discarded – undo
6583 6583
 		$images = null;
6584 6584
 		if (preg_match_all("/(src|background)=\"(.*)\"/Ui", $_html2parse, $images) && isset($images[2]))
6585 6585
 		{
6586
-			foreach($images[2] as $i => $url)
6586
+			foreach ($images[2] as $i => $url)
6587 6587
 			{
6588 6588
 				//$isData = false;
6589 6589
 				$basedir = $data = '';
@@ -6595,20 +6595,20 @@  discard block
 block discarded – undo
6595 6595
 					$filename = basename($url);
6596 6596
 					if (($directory = dirname($url)) == '.') $directory = '';
6597 6597
 					$ext = pathinfo($filename, PATHINFO_EXTENSION);
6598
-					$mimeType  = MimeMagic::ext2mime($ext);
6599
-					if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
6598
+					$mimeType = MimeMagic::ext2mime($ext);
6599
+					if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
6600 6600
 					$myUrl = $directory.$filename;
6601
-					if ($myUrl[0]=='/') // local path -> we only allow path's that are available via http/https (or vfs)
6601
+					if ($myUrl[0] == '/') // local path -> we only allow path's that are available via http/https (or vfs)
6602 6602
 					{
6603
-						$basedir = ($_SERVER['HTTPS']?'https://':'http://'.$_SERVER['HTTP_HOST']);
6603
+						$basedir = ($_SERVER['HTTPS'] ? 'https://' : 'http://'.$_SERVER['HTTP_HOST']);
6604 6604
 					}
6605 6605
 					// use vfs instead of url containing webdav.php
6606 6606
 					// ToDo: we should test if the webdav url is of our own scope, as we cannot handle foreign
6607 6607
 					// webdav.php urls as vfs
6608
-					if (strpos($myUrl,'/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6608
+					if (strpos($myUrl, '/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6609 6609
 					{
6610 6610
 						Vfs::load_wrapper('vfs');
6611
-						list(,$myUrl) = explode('/webdav.php',$myUrl,2);
6611
+						list(,$myUrl) = explode('/webdav.php', $myUrl, 2);
6612 6612
 						$basedir = 'vfs://default';
6613 6613
 						$needTempFile = false;
6614 6614
 					}
@@ -6621,11 +6621,11 @@  discard block
 block discarded – undo
6621 6621
 						// Strips the url and store it into a temp for further procss
6622 6622
 						$tmp_url = html_entity_decode($myUrl);
6623 6623
 
6624
-						parse_str(parse_url($tmp_url, PHP_URL_QUERY),$URI_params);
6624
+						parse_str(parse_url($tmp_url, PHP_URL_QUERY), $URI_params);
6625 6625
 						if ($URI_params['mailbox'] && $URI_params['uid'] && $URI_params['cid'])
6626 6626
 						{
6627 6627
 							$mail_bo->reopen(base64_decode($URI_params['mailbox']));
6628
-							$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']),base64_decode($URI_params['partID']),true);
6628
+							$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']), base64_decode($URI_params['partID']), true);
6629 6629
 							$mail_bo->closeConnection();
6630 6630
 							if ($attachment)
6631 6631
 							{
@@ -6636,32 +6636,32 @@  discard block
 block discarded – undo
6636 6636
 						}
6637 6637
 					}
6638 6638
 
6639
-					if ( strlen($basedir) > 1 && substr($basedir,-1) != '/' && $myUrl[0]!='/') { $basedir .= '/'; }
6640
-					if ($needTempFile && !$attachment && substr($myUrl,0,4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6639
+					if (strlen($basedir) > 1 && substr($basedir, -1) != '/' && $myUrl[0] != '/') { $basedir .= '/'; }
6640
+					if ($needTempFile && !$attachment && substr($myUrl, 0, 4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6641 6641
 				}
6642
-				if (substr($url,0,strlen('data:'))=='data:')
6642
+				if (substr($url, 0, strlen('data:')) == 'data:')
6643 6643
 				{
6644 6644
 					//error_log(__METHOD__.' ('.__LINE__.') '.' -> '.$i.': '.array2string($images[$i]));
6645 6645
 					// we only support base64 encoded data
6646
-					$tmp = substr($url,strlen('data:'));
6647
-					list($mimeType,$data_base64) = explode(';base64,',$tmp);
6646
+					$tmp = substr($url, strlen('data:'));
6647
+					list($mimeType, $data_base64) = explode(';base64,', $tmp);
6648 6648
 					$data = base64_decode($data_base64);
6649 6649
 					// FF currently does NOT add any mime-type
6650 6650
 					if (strtolower(substr($mimeType, 0, 6)) != 'image/')
6651 6651
 					{
6652 6652
 						$mimeType = MimeMagic::analyze_data($data);
6653 6653
 					}
6654
-					list($what,$exactly) = explode('/',$mimeType);
6654
+					list($what, $exactly) = explode('/', $mimeType);
6655 6655
 					$needTempFile = true;
6656
-					$filename = ($what?$what:'data').$imageC++.'.'.$exactly;
6656
+					$filename = ($what ? $what : 'data').$imageC++.'.'.$exactly;
6657 6657
 				}
6658 6658
 				if ($data || $needTempFile === false)
6659 6659
 				{
6660 6660
 					if ($needTempFile)
6661 6661
 					{
6662
-						$attachment_file =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6663
-						$tmpfile = fopen($attachment_file,'w');
6664
-						fwrite($tmpfile,$data);
6662
+						$attachment_file = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6663
+						$tmpfile = fopen($attachment_file, 'w');
6664
+						fwrite($tmpfile, $data);
6665 6665
 						fclose($tmpfile);
6666 6666
 					}
6667 6667
 					else
@@ -6672,7 +6672,7 @@  discard block
 block discarded – undo
6672 6672
 					// (or similar) in all cases (when cut&paste). This may lead to more attached files, in case
6673 6673
 					// we use the same image multiple times, but, if we do this, we should try to detect that
6674 6674
 					// on upload. filename itself is not sufficient to determine the sameness of images
6675
-					$cid = 'cid:' . md5($attachment_file);
6675
+					$cid = 'cid:'.md5($attachment_file);
6676 6676
 					if ($_mailObject->AddEmbeddedImage($attachment_file, substr($cid, 4), urldecode($filename), $mimeType) !== null)
6677 6677
 					{
6678 6678
 						//$_html2parse = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $_html2parse);
@@ -6701,10 +6701,10 @@  discard block
 block discarded – undo
6701 6701
 	 * @param string& $importID ID for the imported message, used by attachments to identify them unambiguously
6702 6702
 	 * @return mixed array of messages with success and failed messages or exception
6703 6703
 	 */
6704
-	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID='')
6704
+	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID = '')
6705 6705
 	{
6706 6706
 		$importfailed = false;
6707
-		$processStats = array('success'=>array(),'failed'=>array());
6707
+		$processStats = array('success'=>array(), 'failed'=>array());
6708 6708
 		if (empty($SendAndMergeTocontacts))
6709 6709
 		{
6710 6710
 			$importfailed = true;
@@ -6745,7 +6745,7 @@  discard block
 block discarded – undo
6745 6745
 				$_folder = $this->getSentFolder();
6746 6746
 			}
6747 6747
 			$delimiter = $this->getHierarchyDelimiter();
6748
-			if($_folder=='INBOX'.$delimiter) $_folder='INBOX';
6748
+			if ($_folder == 'INBOX'.$delimiter) $_folder = 'INBOX';
6749 6749
 			if ($importfailed === false)
6750 6750
 			{
6751 6751
 				$Subject = $mailObject->getHeader('Subject');
@@ -6763,9 +6763,9 @@  discard block
 block discarded – undo
6763 6763
 				{
6764 6764
 					$mailObject->clearReplyTos();
6765 6765
 					$activeMailProfiles = $this->mail->getAccountIdentities($this->profileID);
6766
-					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
6766
+					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
6767 6767
 
6768
-					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']),Mail::generateIdentityString($activeMailProfile,false));
6768
+					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']), Mail::generateIdentityString($activeMailProfile, false));
6769 6769
 				}
6770 6770
 				foreach ($SendAndMergeTocontacts as $k => $val)
6771 6771
 				{
@@ -6779,12 +6779,12 @@  discard block
 block discarded – undo
6779 6779
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6780 6780
 
6781 6781
 						// Parse destinations for placeholders
6782
-						foreach(Mailer::$type2header as $type => $h)
6782
+						foreach (Mailer::$type2header as $type => $h)
6783 6783
 						{
6784 6784
 							//error_log('ID ' . $val . ' ' .$type . ': ' . $mailObject->getHeader(Mailer::$type2header[$type]) . ' -> ' .$bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset));
6785
-							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset);
6786
-							$mailObject->addAddress($merged,'',$type);
6787
-							if($type == 'to')
6785
+							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]), $val, $e, 'text/plain', array(), self::$displayCharset);
6786
+							$mailObject->addAddress($merged, '', $type);
6787
+							if ($type == 'to')
6788 6788
 							{
6789 6789
 								$email = $merged;
6790 6790
 							}
@@ -6797,26 +6797,26 @@  discard block
 block discarded – undo
6797 6797
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ID:'.$val.' Data:'.array2string($contact));
6798 6798
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
6799 6799
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
6800
-							if($email)
6800
+							if ($email)
6801 6801
 							{
6802 6802
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
6803 6803
 							}
6804 6804
 						}
6805 6805
 
6806 6806
 						$activeMailProfiles = $this->getAccountIdentities($this->profileID);
6807
-						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
6807
+						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
6808 6808
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($activeMailProfile));
6809 6809
 						$mailObject->setFrom($activeMailProfile['ident_email'],
6810
-							self::generateIdentityString($activeMailProfile,false));
6810
+							self::generateIdentityString($activeMailProfile, false));
6811 6811
 
6812 6812
 						$mailObject->removeHeader('Message-ID');
6813 6813
 						$mailObject->removeHeader('Date');
6814 6814
 						$mailObject->clearCustomHeaders();
6815 6815
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6816 6816
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6817
-						if($text_body) $text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6817
+						if ($text_body) $text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset), array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6818 6818
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6819
-						if($html_body) $html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6819
+						if ($html_body) $html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset), array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6820 6820
 
6821 6821
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6822 6822
 						// set a higher timeout for big messages
@@ -6825,7 +6825,7 @@  discard block
 block discarded – undo
6825 6825
 						try {
6826 6826
 							$mailObject->send();
6827 6827
 						}
6828
-						catch(Exception $e) {
6828
+						catch (Exception $e) {
6829 6829
 							$sendOK = false;
6830 6830
 							$errorInfo = $e->getMessage();
6831 6831
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($errorInfo));
@@ -6839,41 +6839,41 @@  discard block
 block discarded – undo
6839 6839
 						$mailObject->clearCustomHeaders();
6840 6840
 
6841 6841
 						// Parse destinations for placeholders
6842
-						foreach(Mailer::$type2header as $type => $h)
6842
+						foreach (Mailer::$type2header as $type => $h)
6843 6843
 						{
6844
-							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset);
6844
+							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]), $val, $e, 'text/plain', array(), self::$displayCharset);
6845 6845
 							//error_log($type . ': ' . $mailObject->getHeader(Mailer::$type2header[$type]) . ' -> ' .$merged);
6846
-							$mailObject->addAddress(trim($merged,'"'),'',$type);
6846
+							$mailObject->addAddress(trim($merged, '"'), '', $type);
6847 6847
 						}
6848 6848
 
6849 6849
 						// No addresses from placeholders?  Treat it as just a contact ID
6850
-						if (count($mailObject->getAddresses('to',true)) == 0 &&
6850
+						if (count($mailObject->getAddresses('to', true)) == 0 &&
6851 6851
 							is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val)) // do the merge
6852 6852
 						{
6853 6853
 							$contact = $bo_merge->contacts->read($val);
6854 6854
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($contact));
6855 6855
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
6856 6856
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
6857
-							if($email)
6857
+							if ($email)
6858 6858
 							{
6859 6859
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
6860 6860
 							}
6861 6861
 						}
6862 6862
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6863 6863
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6864
-						if (!empty($Body)) $text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6864
+						if (!empty($Body)) $text_body->setContents($bo_merge->merge_string($Body, $val, $e, 'text/plain', array(), self::$displayCharset), array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6865 6865
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6866
-						if (!empty($AltBody)) $html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset),array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6866
+						if (!empty($AltBody)) $html_body->setContents($bo_merge->merge_string($AltBody, $val, $e, 'text/html', array(), self::$displayCharset), array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
6867 6867
 						$_folder = $this->getDraftFolder();
6868 6868
 					}
6869 6869
 					if ($sendOK || $openAsDraft)
6870 6870
 					{
6871
-						if ($this->folderExists($_folder,true))
6871
+						if ($this->folderExists($_folder, true))
6872 6872
 						{
6873
-						    if($this->isSentFolder($_folder))
6873
+						    if ($this->isSentFolder($_folder))
6874 6874
 							{
6875 6875
 						        $flags = '\\Seen';
6876
-						    } elseif($this->isDraftFolder($_folder)) {
6876
+						    } elseif ($this->isDraftFolder($_folder)) {
6877 6877
 						        $flags = '\\Draft';
6878 6878
 						    } else {
6879 6879
 						        $flags = '';
@@ -6881,7 +6881,7 @@  discard block
 block discarded – undo
6881 6881
 							$savefailed = false;
6882 6882
 							try
6883 6883
 							{
6884
-								$messageUid =$this->appendMessage($_folder,
6884
+								$messageUid = $this->appendMessage($_folder,
6885 6885
 									$mailObject->getRaw(),
6886 6886
 									null,
6887 6887
 									$flags);
@@ -6889,10 +6889,10 @@  discard block
 block discarded – undo
6889 6889
 							catch (\Exception\WrongUserinput $e)
6890 6890
 							{
6891 6891
 								$savefailed = true;
6892
-								$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3",$Subject,$_folder,$e->getMessage());
6892
+								$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3", $Subject, $_folder, $e->getMessage());
6893 6893
 							}
6894 6894
 							// no send, save successful, and message_uid present
6895
-							if ($savefailed===false && $messageUid && is_null($sendOK))
6895
+							if ($savefailed === false && $messageUid && is_null($sendOK))
6896 6896
 							{
6897 6897
 								$importID = $messageUid;
6898 6898
 								$openComposeWindow = true;
@@ -6901,20 +6901,20 @@  discard block
 block discarded – undo
6901 6901
 						else
6902 6902
 						{
6903 6903
 							$savefailed = true;
6904
-							$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.",$Subject,$_folder);
6904
+							$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.", $Subject, $_folder);
6905 6905
 						}
6906 6906
 						if ($sendOK)
6907 6907
 						{
6908
-							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed?' but failed to store to Folder:'.$_folder:'');
6908
+							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed ? ' but failed to store to Folder:'.$_folder : '');
6909 6909
 						}
6910 6910
 						else
6911 6911
 						{
6912
-							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6912
+							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6913 6913
 						}
6914 6914
 					}
6915
-					if (!is_null($sendOK) && $sendOK===false && is_null($openComposeWindow))
6915
+					if (!is_null($sendOK) && $sendOK === false && is_null($openComposeWindow))
6916 6916
 					{
6917
-						$processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6917
+						$processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6918 6918
 					}
6919 6919
 				}
6920 6920
 			}
@@ -6976,13 +6976,13 @@  discard block
 block discarded – undo
6976 6976
 	 * @param boolean $force8bitOnPrimaryPart (default false. force transferEncoding and charset to 8bit/utf8 if we have a textpart as primaryPart)
6977 6977
 	 * @throws Exception\WrongParameter when the required Horde_Mail_Part not found
6978 6978
 	 */
6979
-	function parseRawMessageIntoMailObject(Mailer $mailer, $message, $force8bitOnPrimaryPart=false)
6979
+	function parseRawMessageIntoMailObject(Mailer $mailer, $message, $force8bitOnPrimaryPart = false)
6980 6980
 	{
6981 6981
 		if (is_string($message) || is_resource($message))
6982 6982
 		{
6983 6983
 			$structure = Horde_Mime_Part::parseMessage($message);
6984 6984
 			//error_log(__METHOD__.__LINE__.'#'.$structure->getPrimaryType().'#');
6985
-			if ($force8bitOnPrimaryPart&&$structure->getPrimaryType()=='text')
6985
+			if ($force8bitOnPrimaryPart && $structure->getPrimaryType() == 'text')
6986 6986
 			{
6987 6987
 				$structure->setTransferEncoding('8bit');
6988 6988
 				$structure->setCharset('utf-8');
@@ -6991,19 +6991,18 @@  discard block
 block discarded – undo
6991 6991
 			//error_log(__METHOD__.__LINE__.':'.array2string($structure));
6992 6992
 
6993 6993
 			// unfortunately parseMessage does NOT return parsed headers (we assume header is shorter then 8k)
6994
-			$start = is_string($message) ? substr($message, 0, 8192) :
6995
-				(fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 8192));
6994
+			$start = is_string($message) ? substr($message, 0, 8192) : (fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 8192));
6996 6995
 
6997 6996
 			$length = strpos($start, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
6998
-			if ($length===false) $length = strlen($start);
6999
-			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0,$length));
6997
+			if ($length === false) $length = strlen($start);
6998
+			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0, $length));
7000 6999
 
7001
-			foreach($headers->toArray(array('nowrap' => true)) as $header => $value)
7000
+			foreach ($headers->toArray(array('nowrap' => true)) as $header => $value)
7002 7001
 			{
7003
-				foreach((array)$value as $n => $val)
7002
+				foreach ((array)$value as $n => $val)
7004 7003
 				{
7005 7004
 					$overwrite = !$n;
7006
-					switch($header)
7005
+					switch ($header)
7007 7006
 					{
7008 7007
 						case 'Content-Transfer-Encoding':
7009 7008
 							//as we parse the message and this sets the part with a Content-Transfer-Encoding, we
@@ -7024,7 +7023,7 @@  discard block
 block discarded – undo
7024 7023
 		}
7025 7024
 		else
7026 7025
 		{
7027
-			if (($type = gettype($message)) == 'object') $type = get_class ($message);
7026
+			if (($type = gettype($message)) == 'object') $type = get_class($message);
7028 7027
 			throw new Exception\WrongParameter('Wrong parameter type for message: '.$type);
7029 7028
 		}
7030 7029
 	}
@@ -7038,50 +7037,50 @@  discard block
 block discarded – undo
7038 7037
 	 * @param string $default_domain
7039 7038
 	 * @return Horde_Mail_Rfc822_List iteratable Horde_Mail_Rfc822_Address objects with attributes mailbox, host, personal and valid
7040 7039
 	 */
7041
-	public static function parseAddressList($addresses, $default_domain=null)
7040
+	public static function parseAddressList($addresses, $default_domain = null)
7042 7041
 	{
7043 7042
 		$rfc822 = new Horde_Mail_Rfc822();
7044 7043
 		$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
7045 7044
 		//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count.function_backtrace());
7046
-		if ((empty($ret) || $ret->count()==0)&& is_string($addresses) && strlen($addresses)>0)
7045
+		if ((empty($ret) || $ret->count() == 0) && is_string($addresses) && strlen($addresses) > 0)
7047 7046
 		{
7048 7047
 			$matches = array();
7049
-			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/",$addresses,$matches);
7048
+			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/", $addresses, $matches);
7050 7049
 			//error_log(__METHOD__.__LINE__.array2string($matches));
7051
-			foreach ($matches[0] as &$match) {$match = trim($match,', ');}
7052
-			$addresses = implode(',',$matches[0]);
7050
+			foreach ($matches[0] as &$match) {$match = trim($match, ', '); }
7051
+			$addresses = implode(',', $matches[0]);
7053 7052
 			//error_log(__METHOD__.__LINE__.array2string($addresses));
7054 7053
 			$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
7055 7054
 			//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count);
7056 7055
 		}
7057
-		$previousFailed=false;
7056
+		$previousFailed = false;
7058 7057
 		$ret2 = new Horde_Mail_Rfc822_List();
7059 7058
 		// handle known problems on emailaddresses
7060
-		foreach($ret as $i => $adr)
7059
+		foreach ($ret as $i => $adr)
7061 7060
 		{
7062 7061
 			//mailaddresses enclosed in single quotes like '[email protected]' show up as 'me as mailbox and you.com' as host
7063
-			if ($adr->mailbox && stripos($adr->mailbox,"'")== 0 &&
7064
-					$adr->host && stripos($adr->host,"'")== (strlen($adr->host) -1))
7062
+			if ($adr->mailbox && stripos($adr->mailbox, "'") == 0 &&
7063
+					$adr->host && stripos($adr->host, "'") == (strlen($adr->host) - 1))
7065 7064
 			{
7066
-				$adr->mailbox = str_replace("'","",$adr->mailbox);
7067
-				$adr->host = str_replace("'","",$adr->host);
7065
+				$adr->mailbox = str_replace("'", "", $adr->mailbox);
7066
+				$adr->host = str_replace("'", "", $adr->host);
7068 7067
 			}
7069 7068
 			// no mailbox or host part as 'Xr\xc3\xa4hlyz, User <[email protected]>' is parsed as 2 addresses separated by ','
7070 7069
 			//#'Xr\xc3\xa4hlyz, User <[email protected]>'
7071 7070
 			//#Horde_Mail_Rfc822_List Object([_data:protected] => Array(
7072 7071
 			//[0] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => Xr\xc3\xa4hlyz[_host:protected] => [_personal:protected] => )
7073 7072
 			//[1] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => mailboxpart1.mailboxpart2[_host:protected] => youthost.com[_personal:protected] => User))[_filter:protected] => Array()[_ptr:protected] => )#2#,
7074
-			if (strlen($adr->mailbox)==0||strlen($adr->host)==0)
7073
+			if (strlen($adr->mailbox) == 0 || strlen($adr->host) == 0)
7075 7074
 			{
7076
-				$remember = ($adr->mailbox?$adr->mailbox:($adr->host?$adr->host:''));
7077
-				$previousFailed=true;
7075
+				$remember = ($adr->mailbox ? $adr->mailbox : ($adr->host ? $adr->host : ''));
7076
+				$previousFailed = true;
7078 7077
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
7079 7078
 			}
7080 7079
 			else
7081 7080
 			{
7082
-				if ($previousFailed && $remember) $adr->personal = $remember. ' ' . $adr->personal;
7081
+				if ($previousFailed && $remember) $adr->personal = $remember.' '.$adr->personal;
7083 7082
 				$remember = '';
7084
-				$previousFailed=false;
7083
+				$previousFailed = false;
7085 7084
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
7086 7085
 				$ret2->add($adr);
7087 7086
 			}
@@ -7097,7 +7096,7 @@  discard block
 block discarded – undo
7097 7096
 	 * @param string $_folder
7098 7097
 	 * @return boolean
7099 7098
 	 */
7100
-	function sendMDN($uid,$_folder)
7099
+	function sendMDN($uid, $_folder)
7101 7100
 	{
7102 7101
 		$acc = Mail\Account::read($this->profileID);
7103 7102
 		$identity = Mail\Account::read_identity($acc['ident_id'], true, null, $acc);
@@ -7127,7 +7126,7 @@  discard block
 block discarded – undo
7127 7126
 	 */
7128 7127
 	function addAccount($_hookValues)
7129 7128
 	{
7130
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7129
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7131 7130
 
7132 7131
 	}
7133 7132
 
@@ -7141,7 +7140,7 @@  discard block
 block discarded – undo
7141 7140
 	 */
7142 7141
 	function deleteAccount($_hookValues)
7143 7142
 	{
7144
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7143
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7145 7144
 
7146 7145
 	}
7147 7146
 
@@ -7155,7 +7154,7 @@  discard block
 block discarded – undo
7155 7154
 	 */
7156 7155
 	function updateAccount($_hookValues)
7157 7156
 	{
7158
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7157
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7159 7158
 
7160 7159
 	}
7161 7160
 }
Please login to merge, or discard this patch.
mail/inc/class.mail_zpush.inc.php 2 patches
Spacing   +349 added lines, -350 removed lines patch added patch discarded remove patch
@@ -90,23 +90,23 @@  discard block
 block discarded – undo
90 90
 		$this->backend = $backend;
91 91
 		if (!isset($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']))
92 92
 		{
93
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' Noprefs set: using 0 as default');
93
+			if ($this->debugLevel > 1) error_log(__METHOD__.__LINE__.' Noprefs set: using 0 as default');
94 94
 			// globals preferences add appname varname value
95
-			$GLOBALS['egw']->preferences->add('activesync','mail-ActiveSyncProfileID',0,'user');
95
+			$GLOBALS['egw']->preferences->add('activesync', 'mail-ActiveSyncProfileID', 0, 'user');
96 96
 			// save prefs
97 97
 			$GLOBALS['egw']->preferences->save_repository(true);
98 98
 		}
99
-		if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' ActiveProfileID:'.array2string(self::$profileID));
99
+		if ($this->debugLevel > 1) error_log(__METHOD__.__LINE__.' ActiveProfileID:'.array2string(self::$profileID));
100 100
 
101 101
 		if (is_null(self::$profileID))
102 102
 		{
103
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' self::ProfileID isNUll:'.array2string(self::$profileID));
104
-			self::$profileID =& Api\Cache::getSession('mail','activeSyncProfileID');
105
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' ActiveProfileID (after reading Cache):'.array2string(self::$profileID));
103
+			if ($this->debugLevel > 1) error_log(__METHOD__.__LINE__.' self::ProfileID isNUll:'.array2string(self::$profileID));
104
+			self::$profileID = & Api\Cache::getSession('mail', 'activeSyncProfileID');
105
+			if ($this->debugLevel > 1) error_log(__METHOD__.__LINE__.' ActiveProfileID (after reading Cache):'.array2string(self::$profileID));
106 106
 		}
107 107
 		if (isset($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']))
108 108
 		{
109
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' Pref for ProfileID:'.array2string($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']));
109
+			if ($this->debugLevel > 1) error_log(__METHOD__.__LINE__.' Pref for ProfileID:'.array2string($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']));
110 110
 			if ($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID'] == 'G')
111 111
 			{
112 112
 				self::$profileID = 'G'; // this should trigger the fetch of the first negative profile (or if no negative profile is available the firstb there is)
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
 				self::$profileID = (int)$GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID'];
117 117
 			}
118 118
 		}
119
-		if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' Profile Selected (after reading Prefs):'.array2string(self::$profileID));
119
+		if ($this->debugLevel > 1) error_log(__METHOD__.__LINE__.' Profile Selected (after reading Prefs):'.array2string(self::$profileID));
120 120
 
121 121
 		// verify we are on an existing profile, if not running in setup (settings can not be static according to interface!)
122 122
 		if (!isset($GLOBALS['egw_setup']))
@@ -124,12 +124,12 @@  discard block
 block discarded – undo
124 124
 			try {
125 125
 				Mail\Account::read(self::$profileID);
126 126
 			}
127
-			catch(Exception $e) {
127
+			catch (Exception $e) {
128 128
 				unset($e);
129 129
 				self::$profileID = Mail\Account::get_default_acc_id();
130 130
 			}
131 131
 		}
132
-		if ($this->debugLevel>0) error_log(__METHOD__.'::'.__LINE__.' ProfileSelected:'.self::$profileID);
132
+		if ($this->debugLevel > 0) error_log(__METHOD__.'::'.__LINE__.' ProfileSelected:'.self::$profileID);
133 133
 		//$this->debugLevel=0;
134 134
 	}
135 135
 
@@ -242,13 +242,13 @@  discard block
 block discarded – undo
242 242
 			$this->__construct($this->backend);
243 243
 
244 244
 			try {
245
-				$this->_connect(0,true);
245
+				$this->_connect(0, true);
246 246
 				$this->_disconnect();
247 247
 
248 248
 				if (!$this->_wasteID) $errors[] = lang('No valid %1 folder configured!', '<b>'.lang('trash').'</b>');
249 249
 				if (!$this->_sentID) $errors[] = lang('No valid %1 folder configured!', '<b>'.lang('send').'</b>');
250 250
 			}
251
-			catch(Exception $e) {
251
+			catch (Exception $e) {
252 252
 				$errors[] = lang('Can not open IMAP connection').': '.$e->getMessage();
253 253
 			}
254 254
 			if ($errors)
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	 * @param int $account integer id of account to use
267 267
 	 * @todo support different accounts
268 268
 	 */
269
-	private function _connect($account=0)
269
+	private function _connect($account = 0)
270 270
 	{
271 271
 		if (!$account) $account = self::$profileID ? self::$profileID : 0;
272 272
 		if ($this->mail && $this->account != $account) $this->_disconnect();
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 			$this->account = $account;
280 280
 			// todo: tell mail which account to use
281 281
 			//error_log(__METHOD__.__LINE__.' create object with ProfileID:'.array2string(self::$profileID));
282
-			$this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
282
+			$this->mail = Mail::getInstance(false, self::$profileID, true, false, true);
283 283
 			if (self::$profileID == 0 && isset($this->mail->icServer->ImapServerId) && !empty($this->mail->icServer->ImapServerId)) self::$profileID = $this->mail->icServer->ImapServerId;
284 284
 		}
285 285
 		else
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 			//error_log(__METHOD__.__LINE__." connect with profileID: ".self::$profileID);
288 288
 			if (self::$profileID == 0 && isset($this->mail->icServer->ImapServerId) && !empty($this->mail->icServer->ImapServerId)) self::$profileID = $this->mail->icServer->ImapServerId;
289 289
 		}
290
-		$this->mail->openConnection(self::$profileID,false);
290
+		$this->mail->openConnection(self::$profileID, false);
291 291
 
292 292
 		$this->_wasteID = $this->mail->getTrashFolder(false);
293 293
 		//error_log(__METHOD__.__LINE__.' TrashFolder:'.$this->_wasteID);
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 	 */
303 303
 	private function _disconnect()
304 304
 	{
305
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__);
305
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__);
306 306
 		if ($this->mail) $this->mail->closeConnection();
307 307
 
308 308
 		unset($this->mail);
@@ -318,24 +318,24 @@  discard block
 block discarded – undo
318 318
 	public function GetFolderList()
319 319
 	{
320 320
 		$folderlist = array();
321
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__);
321
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__);
322 322
 		/*foreach($available_accounts as $account)*/ $account = 0;
323 323
 		{
324 324
 			$this->_connect($account);
325
-			if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true,false,$_alwaysGetDefaultFolders=true);
326
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($this->folders));
325
+			if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true, false, $_alwaysGetDefaultFolders = true);
326
+			if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.array2string($this->folders));
327 327
 
328 328
 			foreach ($this->folders as $folder => $folderObj) {
329
-				if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' folder='.$folder);
329
+				if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' folder='.$folder);
330 330
 				$folderlist[] = $f = array(
331
-					'id'     => $this->createID($account,$folder),
331
+					'id'     => $this->createID($account, $folder),
332 332
 					'mod'    => $folderObj->shortDisplayName,
333
-					'parent' => $this->getParentID($account,$folder),
333
+					'parent' => $this->getParentID($account, $folder),
334 334
 				);
335
-				if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."() returning ".array2string($f));
335
+				if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."() returning ".array2string($f));
336 336
 			}
337 337
 		}
338
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."() returning ".array2string($folderlist));
338
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."() returning ".array2string($folderlist));
339 339
 
340 340
 		return $folderlist;
341 341
 	}
@@ -384,83 +384,83 @@  discard block
 block discarded – undo
384 384
 		$ClientSideMeetingRequest = false;
385 385
 		$allowSendingInvitations = 'sendifnocalnotif';
386 386
 		if (isset($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-allowSendingInvitations']) &&
387
-			$GLOBALS['egw_info']['user']['preferences']['activesync']['mail-allowSendingInvitations']=='nosend')
387
+			$GLOBALS['egw_info']['user']['preferences']['activesync']['mail-allowSendingInvitations'] == 'nosend')
388 388
 		{
389 389
 			$allowSendingInvitations = false;
390 390
 		}
391 391
 		elseif (isset($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-allowSendingInvitations']) &&
392
-			$GLOBALS['egw_info']['user']['preferences']['activesync']['mail-allowSendingInvitations']!='nosend')
392
+			$GLOBALS['egw_info']['user']['preferences']['activesync']['mail-allowSendingInvitations'] != 'nosend')
393 393
 		{
394 394
 			$allowSendingInvitations = $GLOBALS['egw_info']['user']['preferences']['activesync']['mail-allowSendingInvitations'];
395 395
 		}
396
-		$smartdata_task = ($smartdata->replyflag?'reply':($smartdata->forwardflag?'forward':'new'));
396
+		$smartdata_task = ($smartdata->replyflag ? 'reply' : ($smartdata->forwardflag ? 'forward' : 'new'));
397 397
 
398
-   		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__ . (isset($smartdata->mime) ? $smartdata->mime : ""). "task: ".(isset($smartdata_task) ? $smartdata_task : "")." itemid: ".(isset($smartdata->source->itemid) ? $smartdata->source->itemid : "")." folder: ".(isset($smartdata->source->folderid) ? $smartdata->source->folderid : ""));
399
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__."): Smartdata = ".array2string($smartdata));
398
+   		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.(isset($smartdata->mime) ? $smartdata->mime : "")."task: ".(isset($smartdata_task) ? $smartdata_task : "")." itemid: ".(isset($smartdata->source->itemid) ? $smartdata->source->itemid : "")." folder: ".(isset($smartdata->source->folderid) ? $smartdata->source->folderid : ""));
399
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__."): Smartdata = ".array2string($smartdata));
400 400
 		//error_log("IMAP-Sendmail: Smartdata = ".array2string($smartdata));
401 401
 
402 402
 		// initialize our Mail
403
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
403
+		if (!isset($this->mail)) $this->mail = Mail::getInstance(false, self::$profileID, true, false, true);
404 404
 		$activeMailProfiles = $this->mail->getAccountIdentities(self::$profileID);
405 405
 		// use the standardIdentity
406
-		$activeMailProfile = Mail::getStandardIdentityForProfile($activeMailProfiles,self::$profileID);
406
+		$activeMailProfile = Mail::getStandardIdentityForProfile($activeMailProfiles, self::$profileID);
407 407
 
408
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.")".' ProfileID:'.self::$profileID.' ActiveMailProfile:'.array2string($activeMailProfile));
408
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.")".' ProfileID:'.self::$profileID.' ActiveMailProfile:'.array2string($activeMailProfile));
409 409
 		// collect identity / signature for later usage, and to determine if we may have to manipulate TransferEncoding and Charset
410 410
 		try
411 411
 		{
412 412
 			$acc = Mail\Account::read($this->mail->icServer->ImapServerId);
413 413
 			//error_log(__METHOD__.__LINE__.array2string($acc));
414
-			$_signature = Mail\Account::read_identity($acc['ident_id'],true);
414
+			$_signature = Mail\Account::read_identity($acc['ident_id'], true);
415 415
 		}
416 416
 		catch (Exception $e)
417 417
 		{
418
-			$_signature=array();
418
+			$_signature = array();
419 419
 		}
420 420
 		$signature = $_signature['ident_signature'];
421 421
 		if ((isset($preferencesArray['disableRulerForSignatureSeparation']) &&
422 422
 			$preferencesArray['disableRulerForSignatureSeparation']) ||
423
-			empty($signature) || trim(Api\Mail\Html::convertHTMLToText($signature)) =='')
423
+			empty($signature) || trim(Api\Mail\Html::convertHTMLToText($signature)) == '')
424 424
 		{
425 425
 			$disableRuler = true;
426 426
 		}
427 427
 		$beforePlain = $beforeHtml = "";
428
-		$beforeHtml = ($disableRuler ?'&nbsp;<br>':'&nbsp;<br><hr style="border:dotted 1px silver; width:90%; border:dotted 1px silver;">');
429
-		$beforePlain = ($disableRuler ?"\r\n\r\n":"\r\n\r\n-- \r\n");
430
-		$sigText = Mail::merge($signature,array($GLOBALS['egw']->accounts->id2name($GLOBALS['egw_info']['user']['account_id'],'person_id')));
431
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Signature to use:'.$sigText);
428
+		$beforeHtml = ($disableRuler ? '&nbsp;<br>' : '&nbsp;<br><hr style="border:dotted 1px silver; width:90%; border:dotted 1px silver;">');
429
+		$beforePlain = ($disableRuler ? "\r\n\r\n" : "\r\n\r\n-- \r\n");
430
+		$sigText = Mail::merge($signature, array($GLOBALS['egw']->accounts->id2name($GLOBALS['egw_info']['user']['account_id'], 'person_id')));
431
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' Signature to use:'.$sigText);
432 432
 		$sigTextHtml = $beforeHtml.$sigText;
433 433
 		$sigTextPlain = $beforePlain.Api\Mail\Html::convertHTMLToText($sigText);
434 434
 
435
-		$force8bit=false;
436
-		if (Api\Translation::detect_encoding($sigTextPlain)!='ascii') $force8bit=true;
435
+		$force8bit = false;
436
+		if (Api\Translation::detect_encoding($sigTextPlain) != 'ascii') $force8bit = true;
437 437
 		// initialize the new Api\Mailer object for sending
438 438
 		$mailObject = new Api\Mailer(self::$profileID);
439
-		$this->mail->parseRawMessageIntoMailObject($mailObject,$smartdata->mime,$force8bit);
439
+		$this->mail->parseRawMessageIntoMailObject($mailObject, $smartdata->mime, $force8bit);
440 440
 		// Horde SMTP Class uses utf-8 by default. as we set charset always to utf-8
441
-		$mailObject->Sender  = $activeMailProfile['ident_email'];
442
-		$mailObject->setFrom($activeMailProfile['ident_email'],Mail::generateIdentityString($activeMailProfile,false));
441
+		$mailObject->Sender = $activeMailProfile['ident_email'];
442
+		$mailObject->setFrom($activeMailProfile['ident_email'], Mail::generateIdentityString($activeMailProfile, false));
443 443
 		$mailObject->addHeader('X-Mailer', 'mail-Activesync');
444 444
 
445 445
 		// prepare addressee list; moved the adding of addresses to the mailobject down
446 446
 		// to
447
-		foreach(Mail::parseAddressList($mailObject->getHeader("To")) as $addressObject) {
447
+		foreach (Mail::parseAddressList($mailObject->getHeader("To")) as $addressObject) {
448 448
 			if (!$addressObject->valid) continue;
449
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") Header Sentmail To: ".array2string($addressObject) );
449
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") Header Sentmail To: ".array2string($addressObject));
450 450
 			//$mailObject->AddAddress($addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : ''),$addressObject->personal);
451 451
 			$toMailAddr[] = imap_rfc822_write_address($addressObject->mailbox, $addressObject->host, $addressObject->personal);
452 452
 		}
453 453
 		// CC
454
-		foreach(Mail::parseAddressList($mailObject->getHeader("Cc")) as $addressObject) {
454
+		foreach (Mail::parseAddressList($mailObject->getHeader("Cc")) as $addressObject) {
455 455
 			if (!$addressObject->valid) continue;
456
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") Header Sentmail CC: ".array2string($addressObject) );
456
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") Header Sentmail CC: ".array2string($addressObject));
457 457
 			//$mailObject->AddCC($addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : ''),$addressObject->personal);
458 458
 			$ccMailAddr[] = imap_rfc822_write_address($addressObject->mailbox, $addressObject->host, $addressObject->personal);
459 459
 		}
460 460
 		// BCC
461
-		foreach($mailObject->getAddresses('bcc') as $addressObject) {
461
+		foreach ($mailObject->getAddresses('bcc') as $addressObject) {
462 462
 			if (!$addressObject->valid) continue;
463
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") Header Sentmail BCC: ".array2string($addressObject) );
463
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") Header Sentmail BCC: ".array2string($addressObject));
464 464
 			//$mailObject->AddBCC($addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : ''),$addressObject->personal);
465 465
 			$bccMailAddr[] = imap_rfc822_write_address($addressObject->mailbox, $addressObject->host, $addressObject->personal);
466 466
 		}
@@ -469,7 +469,7 @@  discard block
 block discarded – undo
469 469
 		$use_orgbody = false;
470 470
 
471 471
 		$k = 'Content-Type';
472
-		$ContentType =$mailObject->getHeader('Content-Type');
472
+		$ContentType = $mailObject->getHeader('Content-Type');
473 473
 		//error_log(__METHOD__.__LINE__." Header Sentmail original Header (filtered): " . $k.  " = ".trim($ContentType));
474 474
 		// if the message is a multipart message, then we should use the sent body
475 475
 		if (preg_match("/multipart/i", $ContentType)) {
@@ -489,43 +489,43 @@  discard block
 block discarded – undo
489 489
 			$k == "Content-Type" && preg_match("/multipart/i", $ContentType))) {
490 490
 			$use_orgbody = true;
491 491
 		}
492
-		$Body =  $AltBody = "";
492
+		$Body = $AltBody = "";
493 493
 		// get body of the transmitted message
494 494
 		// if this is a simple message, no structure at all
495 495
 		if (preg_match("/text/i", $ContentType))
496 496
 		{
497
-			$simpleBodyType = (preg_match("/html/i", $ContentType)?'text/html':'text/plain');
497
+			$simpleBodyType = (preg_match("/html/i", $ContentType) ? 'text/html' : 'text/plain');
498 498
 			$bodyObj = $mailObject->findBody(preg_match("/html/i", $ContentType) ? 'html' : 'plain');
499
-			$body = preg_replace("/(<|&lt;)*(([\w\.,-.,_.,0-9.]+)@([\w\.,-.,_.,0-9.]+))(>|&gt;)*/i","[$2]", $bodyObj ?$bodyObj->getContents() : null);
500
-			if  ($simpleBodyType == "text/plain")
499
+			$body = preg_replace("/(<|&lt;)*(([\w\.,-.,_.,0-9.]+)@([\w\.,-.,_.,0-9.]+))(>|&gt;)*/i", "[$2]", $bodyObj ? $bodyObj->getContents() : null);
500
+			if ($simpleBodyType == "text/plain")
501 501
 			{
502 502
 				$Body = $body;
503 503
 				$AltBody = "<pre>".nl2br($body)."</pre>";
504
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched Body as :". $simpleBodyType.'=> Created AltBody');
504
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") fetched Body as :".$simpleBodyType.'=> Created AltBody');
505 505
 			}
506 506
 			else
507 507
 			{
508 508
 				$AltBody = $body;
509
-				$Body =  trim(Api\Mail\Html::convertHTMLToText($body));
510
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched Body as :". $simpleBodyType.'=> Created Body');
509
+				$Body = trim(Api\Mail\Html::convertHTMLToText($body));
510
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") fetched Body as :".$simpleBodyType.'=> Created Body');
511 511
 			}
512 512
 		}
513 513
 		else
514 514
 		{
515 515
 			// if this is a structured message
516 516
 			// prefer plain over html
517
-			$Body = preg_replace("/(<|&lt;)*(([\w\.,-.,_.,0-9.]+)@([\w\.,-.,_.,0-9.]+))(>|&gt;)*/i","[$2]",
517
+			$Body = preg_replace("/(<|&lt;)*(([\w\.,-.,_.,0-9.]+)@([\w\.,-.,_.,0-9.]+))(>|&gt;)*/i", "[$2]",
518 518
 				($text_body = $mailObject->findBody('plain')) ? $text_body->getContents() : null);
519
-			$AltBody = preg_replace("/(<|&lt;)*(([\w\.,-.,_.,0-9.]+)@([\w\.,-.,_.,0-9.]+))(>|&gt;)*/i","[$2]",
519
+			$AltBody = preg_replace("/(<|&lt;)*(([\w\.,-.,_.,0-9.]+)@([\w\.,-.,_.,0-9.]+))(>|&gt;)*/i", "[$2]",
520 520
 				($html_body = $mailObject->findBody('html')) ? $html_body->getContents() : null);
521 521
 		}
522
-		if ($this->debugLevel>1 && $Body) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched Body as with MessageContentType:". $ContentType.'=>'.$Body);
523
-		if ($this->debugLevel>1 && $AltBody) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched AltBody as with MessageContentType:". $ContentType.'=>'.$AltBody);
522
+		if ($this->debugLevel > 1 && $Body) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") fetched Body as with MessageContentType:".$ContentType.'=>'.$Body);
523
+		if ($this->debugLevel > 1 && $AltBody) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") fetched AltBody as with MessageContentType:".$ContentType.'=>'.$AltBody);
524 524
 		//error_log(__METHOD__.__LINE__.array2string($mailObject));
525 525
 		// if this is a multipart message with a boundary, we must use the original body
526 526
 		//if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' mailObject after Inital Parse:'.array2string($mailObject));
527 527
         if ($use_orgbody) {
528
-    	    ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") use_orgbody = true ContentType:".$ContentType);
528
+    	    ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") use_orgbody = true ContentType:".$ContentType);
529 529
  			// if it is a ClientSideMeetingRequest, we report it as send at all times
530 530
 			if (($cal_body = $mailObject->findBody('calendar')) &&
531 531
 				($cSMRMethod = $cal_body->getContentTypeParameter('method')))
@@ -534,21 +534,21 @@  discard block
 block discarded – undo
534 534
 				{
535 535
 					$organizer = calendar_ical::getIcalOrganizer($cal_body->getContents());
536 536
 				}
537
-				if ($this->debugLevel) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") we have a Client Side Meeting Request from organizer=$organizer");
537
+				if ($this->debugLevel) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") we have a Client Side Meeting Request from organizer=$organizer");
538 538
 				$ClientSideMeetingRequest = true;
539 539
 			}
540 540
         }
541 541
 		// now handle the addressee list
542 542
 		$toCount = 0;
543 543
 		//error_log(__METHOD__.__LINE__.array2string($toMailAddr));
544
-		foreach((array)$toMailAddr as $address) {
545
-			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
546
-				$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
544
+		foreach ((array)$toMailAddr as $address) {
545
+			foreach (Mail::parseAddressList((get_magic_quotes_gpc() ? stripslashes($address) : $address)) as $addressObject) {
546
+				$emailAddress = $addressObject->mailbox.($addressObject->host ? '@'.$addressObject->host : '');
547 547
 				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' &&
548 548
 					calendar_boupdate::email_update_requested($emailAddress, isset($cSMRMethod) ? $cSMRMethod : 'REQUEST',
549 549
 						$organizer && !strcasecmp($emailAddress, $organizer) ? 'CHAIR' : ''))
550 550
 				{
551
-					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") skiping mail to organizer '$organizer', as it will be send by calendar app");
551
+					ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") skiping mail to organizer '$organizer', as it will be send by calendar app");
552 552
 					continue;
553 553
 				}
554 554
 				$mailObject->AddAddress($emailAddress, $addressObject->personal);
@@ -556,29 +556,29 @@  discard block
 block discarded – undo
556 556
 			}
557 557
 		}
558 558
 		$ccCount = 0;
559
-		foreach((array)$ccMailAddr as $address) {
560
-			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
561
-				$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
559
+		foreach ((array)$ccMailAddr as $address) {
560
+			foreach (Mail::parseAddressList((get_magic_quotes_gpc() ? stripslashes($address) : $address)) as $addressObject) {
561
+				$emailAddress = $addressObject->mailbox.($addressObject->host ? '@'.$addressObject->host : '');
562 562
 				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' && calendar_boupdate::email_update_requested($emailAddress)) continue;
563 563
 				$mailObject->AddCC($emailAddress, $addressObject->personal);
564 564
 				$ccCount++;
565 565
 			}
566 566
 		}
567 567
 		$bccCount = 0;
568
-		foreach((array)$bccMailAddr as $address) {
569
-			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
570
-				$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
568
+		foreach ((array)$bccMailAddr as $address) {
569
+			foreach (Mail::parseAddressList((get_magic_quotes_gpc() ? stripslashes($address) : $address)) as $addressObject) {
570
+				$emailAddress = $addressObject->mailbox.($addressObject->host ? '@'.$addressObject->host : '');
571 571
 				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' && calendar_boupdate::email_update_requested($emailAddress)) continue;
572 572
 				$mailObject->AddBCC($emailAddress, $addressObject->personal);
573 573
 				$bccCount++;
574 574
 			}
575 575
 		}
576 576
 		// typical organizer reply will end here with nothing send --> return true, because we suppressed the send above
577
-		if ($toCount+$ccCount+$bccCount == 0)
577
+		if ($toCount + $ccCount + $bccCount == 0)
578 578
 		{
579 579
 			return $ClientSideMeetingRequest && $allowSendingInvitations === 'sendifnocalnotif' && $organizer ? true : 0; // noone to send mail to
580 580
 		}
581
-		if ($ClientSideMeetingRequest === true && $allowSendingInvitations===false) return true;
581
+		if ($ClientSideMeetingRequest === true && $allowSendingInvitations === false) return true;
582 582
 		// as we use our mailer (horde mailer) it is detecting / setting the mimetype by itself while creating the mail
583 583
 /*
584 584
 		if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' retrieved Body:'.$body);
@@ -595,26 +595,26 @@  discard block
 block discarded – undo
595 595
 		{
596 596
 			// now get on, and fetch the original mail
597 597
 			$uid = $smartdata->source->itemid;
598
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") IMAP Smartreply is called with FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
598
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") IMAP Smartreply is called with FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
599 599
 			$this->splitID($smartdata->source->folderid, $account, $folder);
600 600
 
601 601
 			$this->mail->reopen($folder);
602 602
 			$bodyStruct = $this->mail->getMessageBody($uid, 'html_only');
603
-			$bodyBUFFHtml = $this->mail->getdisplayableBody($this->mail,$bodyStruct,true,false);
604
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
605
-		    if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html')) {
603
+			$bodyBUFFHtml = $this->mail->getdisplayableBody($this->mail, $bodyStruct, true, false);
604
+			if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
605
+		    if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType'] == 'text/html')) {
606 606
 				// may be html
607
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
607
+				if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
608 608
 				$AltBody = $AltBody."</br>".$bodyBUFFHtml.$sigTextHtml;
609 609
 				$isreply = true;
610 610
 			}
611 611
 			// plain text Message part
612
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain, fetch text:');
612
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") MIME Body".' Type:plain, fetch text:');
613 613
 			// if the new part of the message is html, we must preserve it, and handle that the original mail is text/plain
614
-			$bodyStruct = $this->mail->getMessageBody($uid,'never_display');//'never_display');
615
-			$bodyBUFF = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
616
-			if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/plain')) {
617
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
614
+			$bodyStruct = $this->mail->getMessageBody($uid, 'never_display'); //'never_display');
615
+			$bodyBUFF = $this->mail->getdisplayableBody($this->mail, $bodyStruct, false, false);
616
+			if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType'] == 'text/plain')) {
617
+				if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
618 618
 				$Body = $Body."\r\n".$bodyBUFF.$sigTextPlain;
619 619
 				$isreply = true;
620 620
 			}
@@ -622,12 +622,12 @@  discard block
 block discarded – undo
622 622
 			{
623 623
 				$isreply = true;
624 624
 				$AltBody = $AltBody."</br><pre>".nl2br($bodyBUFF).'</pre>'.$sigTextHtml;
625
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." no Api\Html Body found use modified plaintext body for txt/html: ".$AltBody);
625
+				if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." no Api\Html Body found use modified plaintext body for txt/html: ".$AltBody);
626 626
 			}
627 627
 		}
628 628
 
629 629
 		// how to forward and other prefs
630
-		$preferencesArray =& $GLOBALS['egw_info']['user']['preferences']['mail'];
630
+		$preferencesArray = & $GLOBALS['egw_info']['user']['preferences']['mail'];
631 631
 
632 632
 		// forward -------------------------------------------------------------------------
633 633
 		if ($smartdata_task == 'forward' && isset($smartdata->source->itemid) &&
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 		{
638 638
 			//force the default for the forwarding -> asmail
639 639
 			if (is_array($preferencesArray)) {
640
-				if (!array_key_exists('message_forwarding',$preferencesArray)
640
+				if (!array_key_exists('message_forwarding', $preferencesArray)
641 641
 					|| !isset($preferencesArray['message_forwarding'])
642 642
 					|| empty($preferencesArray['message_forwarding'])) $preferencesArray['message_forwarding'] = 'asmail';
643 643
 			} else {
@@ -645,18 +645,18 @@  discard block
 block discarded – undo
645 645
 			}
646 646
 			// construct the uid of the message out of the itemid - seems to be the uid, no construction needed
647 647
 			$uid = $smartdata->source->itemid;
648
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.")IMAP Smartfordward is called with FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
648
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.")IMAP Smartfordward is called with FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
649 649
 			$this->splitID($smartdata->source->folderid, $account, $folder);
650 650
 
651 651
 			$this->mail->reopen($folder);
652 652
             // receive entire mail (header + body)
653 653
 			// get message headers for specified message
654
-			$headers	= $this->mail->getMessageEnvelope($uid, $_partID, true, $folder);
654
+			$headers = $this->mail->getMessageEnvelope($uid, $_partID, true, $folder);
655 655
 			// build a new mime message, forward entire old mail as file
656 656
 			if ($preferencesArray['message_forwarding'] == 'asmail')
657 657
 			{
658
-				$rawHeader      = $this->mail->getMessageRawHeader($smartdata->source->itemid, $_partID,$folder);
659
-				$rawBody        = $this->mail->getMessageRawBody($smartdata->source->itemid, $_partID,$folder);
658
+				$rawHeader      = $this->mail->getMessageRawHeader($smartdata->source->itemid, $_partID, $folder);
659
+				$rawBody        = $this->mail->getMessageRawBody($smartdata->source->itemid, $_partID, $folder);
660 660
 				$mailObject->AddStringAttachment($rawHeader.$rawBody, $headers['SUBJECT'].'.eml', 'message/rfc822');
661 661
 				$AltBody = $AltBody."</br>".lang("See Attachments for Content of the Orignial Mail").$sigTextHtml;
662 662
 				$Body = $Body."\r\n".lang("See Attachments for Content of the Orignial Mail").$sigTextPlain;
@@ -666,50 +666,50 @@  discard block
 block discarded – undo
666 666
 			{
667 667
 				// now get on, and fetch the original mail
668 668
 				$uid = $smartdata->source->itemid;
669
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") IMAP Smartreply is called with FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
669
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") IMAP Smartreply is called with FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
670 670
 				$this->splitID($smartdata->source->folderid, $account, $folder);
671 671
 
672 672
 				$this->mail->reopen($folder);
673 673
 				$bodyStruct = $this->mail->getMessageBody($uid, 'html_only');
674
-				$bodyBUFFHtml = $this->mail->getdisplayableBody($this->mail,$bodyStruct,true,false);
675
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
676
-				if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html')) {
674
+				$bodyBUFFHtml = $this->mail->getdisplayableBody($this->mail, $bodyStruct, true, false);
675
+				if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
676
+				if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType'] == 'text/html')) {
677 677
 					// may be html
678
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
678
+					if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
679 679
 					$AltBody = $AltBody."</br>".$bodyBUFFHtml.$sigTextHtml;
680 680
 					$isforward = true;
681 681
 				}
682 682
 				// plain text Message part
683
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain, fetch text:');
683
+				if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") MIME Body".' Type:plain, fetch text:');
684 684
 				// if the new part of the message is html, we must preserve it, and handle that the original mail is text/plain
685
-				$bodyStruct = $this->mail->getMessageBody($uid,'never_display');//'never_display');
686
-				$bodyBUFF = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
687
-				if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/plain')) {
688
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
685
+				$bodyStruct = $this->mail->getMessageBody($uid, 'never_display'); //'never_display');
686
+				$bodyBUFF = $this->mail->getdisplayableBody($this->mail, $bodyStruct, false, false);
687
+				if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType'] == 'text/plain')) {
688
+					if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
689 689
 					$Body = $Body."\r\n".$bodyBUFF.$sigTextPlain;
690 690
 					$isforward = true;
691 691
 				}
692 692
 				if (!empty($bodyBUFF) && empty($bodyBUFFHtml) && !empty($AltBody))
693 693
 				{
694 694
 					$AltBody = $AltBody."</br><pre>".nl2br($bodyBUFF).'</pre>'.$sigTextHtml;
695
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." no html Body found use modified plaintext body for txt/html: ".$AltBody);
695
+					if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." no html Body found use modified plaintext body for txt/html: ".$AltBody);
696 696
 					$isforward = true;
697 697
 				}
698 698
 				// get all the attachments and add them too.
699 699
 				// start handle Attachments
700 700
 				//												$_uid, $_partID=null, Horde_Mime_Part $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=false, $resolveTNEF=true, $_folderName=''
701
-				$attachments = $this->mail->getMessageAttachments($uid, null,          null,								true,						false,				 true			, $folder);
701
+				$attachments = $this->mail->getMessageAttachments($uid, null, null, true, false, true, $folder);
702 702
 				$attachmentNames = false;
703
-				if (is_array($attachments) && count($attachments)>0)
703
+				if (is_array($attachments) && count($attachments) > 0)
704 704
 				{
705
-					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' gather Attachments for BodyCreation of/for MessageID:'.$uid.' found:'.count($attachments));
706
-					foreach((array)$attachments as $key => $attachment)
705
+					ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' gather Attachments for BodyCreation of/for MessageID:'.$uid.' found:'.count($attachments));
706
+					foreach ((array)$attachments as $key => $attachment)
707 707
 					{
708
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attachment));
708
+						if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attachment));
709 709
 						$attachmentNames .= $attachment['name']."\n";
710
-						$attachmentData	= $this->mail->getAttachment($uid, $attachment['partID'],0,false,false,$folder);
710
+						$attachmentData = $this->mail->getAttachment($uid, $attachment['partID'], 0, false, false, $folder);
711 711
 						/*$x =*/ $mailObject->AddStringAttachment($attachmentData['attachment'], $attachment['name'], $attachment['mimeType']);
712
-						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' added part with number:'.$x);
712
+						ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' added part with number:'.$x);
713 713
 					}
714 714
 				}
715 715
 			}
@@ -724,38 +724,38 @@  discard block
 block discarded – undo
724 724
 		// now set the body
725 725
 		if ($AltBody && ($html_body = $mailObject->findBody('html')))
726 726
 		{
727
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> '.$AltBody);
727
+			if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' -> '.$AltBody);
728 728
 			//error_log(__METHOD__.__LINE__.' html:'.$AltBody);
729
-			$html_body->setContents($AltBody,array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
729
+			$html_body->setContents($AltBody, array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
730 730
 		}
731 731
 		if ($Body && ($text_body = $mailObject->findBody('plain')))
732 732
 		{
733
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> '.$Body);
733
+			if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' -> '.$Body);
734 734
 			//error_log(__METHOD__.__LINE__.' text:'.$Body);
735
-			$text_body->setContents($Body,array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
735
+			$text_body->setContents($Body, array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
736 736
 		}
737 737
 		//advanced debugging
738 738
 		// Horde SMTP Class uses utf-8 by default.
739 739
         //ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SendMail: parsed message: ". print_r($message,1));
740
-		if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__."): MailObject:".array2string($mailObject));
740
+		if ($this->debugLevel > 2) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__."): MailObject:".array2string($mailObject));
741 741
 
742 742
 		// set a higher timeout for big messages
743 743
 		@set_time_limit(120);
744
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> '.' about to send ....');
744
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' -> '.' about to send ....');
745 745
 		// send
746 746
 		$send = true;
747 747
 		try {
748 748
 			$mailObject->Send();
749 749
 		}
750
-		catch(Exception $e) {
751
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") The email could not be sent. Last-SMTP-error: ". $e->getMessage());
750
+		catch (Exception $e) {
751
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") The email could not be sent. Last-SMTP-error: ".$e->getMessage());
752 752
 			$send = false;
753 753
 		}
754 754
 
755
-		if (( $smartdata_task == 'reply' || $smartdata_task == 'forward') && $send == true)
755
+		if (($smartdata_task == 'reply' || $smartdata_task == 'forward') && $send == true)
756 756
 		{
757 757
 			$uid = $smartdata->source->itemid;
758
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' tASK:'.$smartdata_task." FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
758
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' tASK:'.$smartdata_task." FolderID:".$smartdata->source->folderid.' and ItemID:'.$smartdata->source->itemid);
759 759
 			$this->splitID($smartdata->source->folderid, $account, $folder);
760 760
 			//error_log(__METHOD__.__LINE__.' Folder:'.$folder.' Uid:'.$uid);
761 761
 			$this->mail->reopen($folder);
@@ -763,90 +763,90 @@  discard block
 block discarded – undo
763 763
 			// unless your templatefolder is a subfolder of your draftfolder, and the message is in there
764 764
 			if ($this->mail->isDraftFolder($folder) && !$this->mail->isTemplateFolder($folder))
765 765
 			{
766
-				$this->mail->deleteMessages(array($uid),$folder);
766
+				$this->mail->deleteMessages(array($uid), $folder);
767 767
 			} else {
768
-				$this->mail->flagMessages("answered", array($uid),$folder);
769
-				if ($smartdata_task== "forward")
768
+				$this->mail->flagMessages("answered", array($uid), $folder);
769
+				if ($smartdata_task == "forward")
770 770
 				{
771
-					$this->mail->flagMessages("forwarded", array($uid),$folder);
771
+					$this->mail->flagMessages("forwarded", array($uid), $folder);
772 772
 				}
773 773
 			}
774 774
 		}
775 775
 
776
-		$asf = ($send ? true:false); // initalize accordingly
777
-		if (/*($smartdata->saveinsent==1 || !isset($smartdata->saveinsent)) && */  $send==true && $this->mail->mailPreferences['sendOptions'] != 'send_only')
776
+		$asf = ($send ? true : false); // initalize accordingly
777
+		if (/*($smartdata->saveinsent==1 || !isset($smartdata->saveinsent)) && */  $send == true && $this->mail->mailPreferences['sendOptions'] != 'send_only')
778 778
 		{
779 779
 			$asf = false;
780 780
 			$sentFolder = $this->mail->getSentFolder();
781 781
 			if ($this->_sentID) {
782 782
 				$folderArray[] = $this->_sentID;
783 783
 			}
784
-			else if(isset($sentFolder) && $sentFolder != 'none')
784
+			else if (isset($sentFolder) && $sentFolder != 'none')
785 785
 			{
786 786
 				$folderArray[] = $sentFolder;
787 787
 			}
788 788
 			// No Sent folder set, try defaults
789 789
 			else
790 790
 			{
791
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") IMAP-SendMail: No Sent mailbox set");
791
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__.") IMAP-SendMail: No Sent mailbox set");
792 792
 				// we dont try guessing
793 793
 				$asf = true;
794 794
 			}
795 795
 			if (count($folderArray) > 0) {
796
-				foreach((array)$bccMailAddr as $address) {
797
-					foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
798
-						$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
796
+				foreach ((array)$bccMailAddr as $address) {
797
+					foreach (Mail::parseAddressList((get_magic_quotes_gpc() ? stripslashes($address) : $address)) as $addressObject) {
798
+						$emailAddress = $addressObject->mailbox.($addressObject->host ? '@'.$addressObject->host : '');
799 799
 						$mailAddr[] = array($emailAddress, $addressObject->personal);
800 800
 					}
801 801
 				}
802 802
 				//$BCCmail='';
803
-				if (count($mailAddr)>0) $mailObject->forceBccHeader();
803
+				if (count($mailAddr) > 0) $mailObject->forceBccHeader();
804 804
 				//$BCCmail = $mailObject->AddrAppend("Bcc",$mailAddr);
805
-				foreach($folderArray as $folderName) {
806
-					if($this->mail->isSentFolder($folderName)) {
805
+				foreach ($folderArray as $folderName) {
806
+					if ($this->mail->isSentFolder($folderName)) {
807 807
 						$flags = '\\Seen';
808
-					} elseif($this->mail->isDraftFolder($folderName)) {
808
+					} elseif ($this->mail->isDraftFolder($folderName)) {
809 809
 						$flags = '\\Draft';
810 810
 					} else {
811 811
 						$flags = '';
812 812
 					}
813 813
 					$asf = true;
814 814
 					//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.'->'.array2string($this->mail->icServer));
815
-					$this->mail->openConnection(self::$profileID,false);
815
+					$this->mail->openConnection(self::$profileID, false);
816 816
 					if ($this->mail->folderExists($folderName)) {
817 817
 						try
818 818
 						{
819
-							$this->mail->appendMessage($folderName,$mailObject->getRaw(), null,
819
+							$this->mail->appendMessage($folderName, $mailObject->getRaw(), null,
820 820
 									$flags);
821 821
 						}
822 822
 						catch (Api\Exception\WrongUserinput $e)
823 823
 						{
824 824
 							//$asf = false;
825
-							ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.'->'.lang("Import of message %1 failed. Could not save message to folder %2 due to: %3",$mailObject->getHeader('Subject'),$folderName,$e->getMessage()));
825
+							ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.'->'.lang("Import of message %1 failed. Could not save message to folder %2 due to: %3", $mailObject->getHeader('Subject'), $folderName, $e->getMessage()));
826 826
 						}
827 827
 					}
828 828
 					else
829 829
 					{
830 830
 						//$asf = false;
831
-						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.'->'.lang("Import of message %1 failed. Destination Folder %2 does not exist.",$mailObject->getHeader('Subject'),$folderName));
831
+						ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.'->'.lang("Import of message %1 failed. Destination Folder %2 does not exist.", $mailObject->getHeader('Subject'), $folderName));
832 832
 					}
833
-			        ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__."): Outgoing mail saved in configured 'Sent' folder '".$folderName."': ". (($asf)?"success":"failed"));
833
+			        ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(".__LINE__."): Outgoing mail saved in configured 'Sent' folder '".$folderName."': ".(($asf) ? "success" : "failed"));
834 834
 				}
835 835
 				//$this->mail->closeConnection();
836 836
 			}
837 837
 		}
838 838
 
839
-		$this->debugLevel=0;
839
+		$this->debugLevel = 0;
840 840
 
841 841
 		if ($send && $asf)
842 842
 		{
843
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> send successfully');
843
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' -> send successfully');
844 844
 			return true;
845 845
 		}
846 846
 		else
847 847
 		{
848
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." returning ".($ClientSideMeetingRequest ? true : 120)." (MailSubmissionFailed)".($ClientSideMeetingRequest ?" is ClientSideMeetingRequest (we ignore the failure)":""));
849
-			return ($ClientSideMeetingRequest ? true : 120);   //MAIL Submission failed, see MS-ASCMD
848
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." returning ".($ClientSideMeetingRequest ? true : 120)." (MailSubmissionFailed)".($ClientSideMeetingRequest ? " is ClientSideMeetingRequest (we ignore the failure)" : ""));
849
+			return ($ClientSideMeetingRequest ? true : 120); //MAIL Submission failed, see MS-ASCMD
850 850
 		}
851 851
 	}
852 852
 
@@ -864,43 +864,43 @@  discard block
 block discarded – undo
864 864
 	public function GetMessage($folderid, $id, $contentparameters)
865 865
 	{
866 866
 		//$this->debugLevel=4;
867
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' FolderID:'.$folderid.' ID:'.$id.' ContentParams='.array2string($contentparameters));
867
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' FolderID:'.$folderid.' ID:'.$id.' ContentParams='.array2string($contentparameters));
868 868
 		$truncsize = Utils::GetTruncSize($contentparameters->GetTruncation());
869 869
 		$mimesupport = $contentparameters->GetMimeSupport();
870
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."() truncsize=$truncsize, mimeSupport=".array2string($mimesupport));
870
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."() truncsize=$truncsize, mimeSupport=".array2string($mimesupport));
871 871
 		$bodypreference = $contentparameters->GetBodyPreference(); /* fmbiete's contribution r1528, ZP-320 */
872 872
 
873 873
 		// fix for z-push bug returning additional bodypreference type 4, even if only 1 is requested and mimessupport = 0
874 874
 		if (!$mimesupport && ($key = array_search('4', $bodypreference))) unset($bodypreference[$key]);
875 875
 
876 876
 		//$this->debugLevel=4;
877
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
878
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' FolderID:'.$folderid.' ID:'.$id.' TruncSize:'.$truncsize.' Bodypreference: '.array2string($bodypreference));
877
+		if (!isset($this->mail)) $this->mail = Mail::getInstance(false, self::$profileID, true, false, true);
878
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' FolderID:'.$folderid.' ID:'.$id.' TruncSize:'.$truncsize.' Bodypreference: '.array2string($bodypreference));
879 879
 		$account = $_folderName = $xid = null;
880
-		$this->splitID($folderid,$account,$_folderName,$xid);
880
+		$this->splitID($folderid, $account, $_folderName, $xid);
881 881
 		$this->mail->reopen($_folderName);
882
-		$messages = $this->fetchMessages($folderid, NULL, $id, true);	// true: return all headers
882
+		$messages = $this->fetchMessages($folderid, NULL, $id, true); // true: return all headers
883 883
 		$headers = $messages[$id];
884
-		if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($headers));
884
+		if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.array2string($headers));
885 885
 		// StatMessage should reopen the folder in question, so we dont need folderids in the following statements.
886 886
 		if ($headers)
887 887
 		{
888
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." Message $id with stat ".array2string($headers));
888
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." Message $id with stat ".array2string($headers));
889 889
 			// initialize the object
890 890
 			$output = new SyncMail();
891 891
 			//$rawHeaders = $this->mail->getMessageRawHeader($id);
892 892
 			// simple style
893 893
 			// start AS12 Stuff (bodypreference === false) case = old behaviour
894
-			if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__. ' for message with ID:'.$id.' with headers:'.array2string($headers));
894
+			if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' for message with ID:'.$id.' with headers:'.array2string($headers));
895 895
 
896 896
 			if ($bodypreference === false) {
897
-				$bodyStruct = $this->mail->getMessageBody($id, 'only_if_no_text', '', null, true,$_folderName);
898
-				$raw_body = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
897
+				$bodyStruct = $this->mail->getMessageBody($id, 'only_if_no_text', '', null, true, $_folderName);
898
+				$raw_body = $this->mail->getdisplayableBody($this->mail, $bodyStruct, false, false);
899 899
 				//$body = html_entity_decode($body,ENT_QUOTES,$this->mail->detect_encoding($body));
900
-				if (stripos($raw_body,'<style')!==false) $body = preg_replace("/<style.*?<\/style>/is", "", $raw_body); // in case there is only a html part
900
+				if (stripos($raw_body, '<style') !== false) $body = preg_replace("/<style.*?<\/style>/is", "", $raw_body); // in case there is only a html part
901 901
 				// remove all other html
902 902
 				$body = strip_tags($raw_body);
903
-				if(strlen($body) > $truncsize) {
903
+				if (strlen($body) > $truncsize) {
904 904
 					$body = Utils::Utf8_truncate($body, $truncsize);
905 905
 					$output->bodytruncated = 1;
906 906
 				}
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
 			else // style with bodypreferences
915 915
 			{
916 916
 				//Select body type preference
917
-				$bpReturnType = 1;//SYNC_BODYPREFERENCE_PLAIN;
917
+				$bpReturnType = 1; //SYNC_BODYPREFERENCE_PLAIN;
918 918
 				if ($bodypreference !== false) {
919 919
 					// bodypreference can occur multiple times
920 920
 					// usually we would use Utils::GetBodyPreferenceBestMatch($bodypreference);
@@ -928,12 +928,12 @@  discard block
 block discarded – undo
928 928
 					}
929 929
 */
930 930
 				}
931
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." getBodyPreferenceBestMatch: ".array2string($bpReturnType));
931
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." getBodyPreferenceBestMatch: ".array2string($bpReturnType));
932 932
 				// set the protocoll class
933 933
 				$output->asbody = new SyncBaseBody();
934 934
 
935 935
 				// return full mime-message without any (charset) conversation directly as stream
936
-				if ($bpReturnType==SYNC_BODYPREFERENCE_MIME)
936
+				if ($bpReturnType == SYNC_BODYPREFERENCE_MIME)
937 937
 				{
938 938
 					//SYNC_BODYPREFERENCE_MIME
939 939
 					$output->asbody->type = SYNC_BODYPREFERENCE_MIME;
@@ -942,58 +942,58 @@  discard block
 block discarded – undo
942 942
 					fseek($stream, 0, SEEK_SET);
943 943
 					$output->asbody->data = $stream;
944 944
 					$output->asbody->estimatedDataSize = $fstat['size'];
945
-					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." bodypreference 4=SYNC_BODYPREFERENCE_MIME=full mime message requested, size=$fstat[size]");
945
+					ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." bodypreference 4=SYNC_BODYPREFERENCE_MIME=full mime message requested, size=$fstat[size]");
946 946
 				}
947 947
 				else
948 948
 				{
949 949
 					// fetch the body (try to gather data only once)
950
-					$css ='';
951
-					$bodyStruct = $this->mail->getMessageBody($id, 'html_only', '', null, true,$_folderName);
952
-					if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only Struct:'.array2string($bodyStruct));
953
-					$body = $this->mail->getdisplayableBody($this->mail,$bodyStruct,true,false);
954
-					if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$body);
955
-					if ($body != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html')) {
950
+					$css = '';
951
+					$bodyStruct = $this->mail->getMessageBody($id, 'html_only', '', null, true, $_folderName);
952
+					if ($this->debugLevel > 2) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' html_only Struct:'.array2string($bodyStruct));
953
+					$body = $this->mail->getdisplayableBody($this->mail, $bodyStruct, true, false);
954
+					if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' html_only:'.$body);
955
+					if ($body != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType'] == 'text/html')) {
956 956
 						// may be html
957
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:html (fetched with html_only)');
957
+						if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:html (fetched with html_only)');
958 958
 						$css = $this->mail->getStyles($bodyStruct);
959
-						$output->nativebodytype=2;
959
+						$output->nativebodytype = 2;
960 960
 					} else {
961 961
 						// plain text Message
962
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:plain, fetch text (HTML, if no text available)');
963
-						$output->nativebodytype=1;
964
-						$bodyStruct = $this->mail->getMessageBody($id,'never_display', '', null, true,$_folderName); //'only_if_no_text');
965
-						if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' plain text Struct:'.array2string($bodyStruct));
966
-						$body = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
967
-						if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' never display html(plain text only):'.$body);
962
+						if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:plain, fetch text (HTML, if no text available)');
963
+						$output->nativebodytype = 1;
964
+						$bodyStruct = $this->mail->getMessageBody($id, 'never_display', '', null, true, $_folderName); //'only_if_no_text');
965
+						if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' plain text Struct:'.array2string($bodyStruct));
966
+						$body = $this->mail->getdisplayableBody($this->mail, $bodyStruct, false, false);
967
+						if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' never display html(plain text only):'.$body);
968 968
 					}
969 969
 					// whatever format decode (using the correct encoding)
970
-					if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__."MIME Body".' Type:'.($output->nativebodytype==2?' html ':' plain ').$body);
970
+					if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__."MIME Body".' Type:'.($output->nativebodytype == 2 ? ' html ' : ' plain ').$body);
971 971
 					//$body = html_entity_decode($body,ENT_QUOTES,$this->mail->detect_encoding($body));
972 972
 					// prepare plaintextbody
973
-					$plainBody='';
973
+					$plainBody = '';
974 974
 					if ($output->nativebodytype == 2)
975 975
 					{
976
-						$bodyStructplain = $this->mail->getMessageBody($id,'never_display', '', null, true,$_folderName); //'only_if_no_text');
977
-						if(isset($bodyStructplain[0])&&isset($bodyStructplain[0]['error'])&&$bodyStructplain[0]['error']==1)
976
+						$bodyStructplain = $this->mail->getMessageBody($id, 'never_display', '', null, true, $_folderName); //'only_if_no_text');
977
+						if (isset($bodyStructplain[0]) && isset($bodyStructplain[0]['error']) && $bodyStructplain[0]['error'] == 1)
978 978
 						{
979 979
 							$plainBody = Api\Mail\Html::convertHTMLToText($body); // always display with preserved HTML
980 980
 						}
981 981
 						else
982 982
 						{
983
-							$plainBody = $this->mail->getdisplayableBody($this->mail,$bodyStructplain,false,false);
983
+							$plainBody = $this->mail->getdisplayableBody($this->mail, $bodyStructplain, false, false);
984 984
 						}
985 985
 					}
986 986
 					//if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".$body);
987
-					$plainBody = preg_replace("/<style.*?<\/style>/is", "", (strlen($plainBody)?$plainBody:$body));
987
+					$plainBody = preg_replace("/<style.*?<\/style>/is", "", (strlen($plainBody) ? $plainBody : $body));
988 988
 					// remove all other html
989
-					$plainBody = preg_replace("/<br.*>/is","\r\n",$plainBody);
989
+					$plainBody = preg_replace("/<br.*>/is", "\r\n", $plainBody);
990 990
 					$plainBody = strip_tags($plainBody);
991
-					if ($this->debugLevel>3 && $output->nativebodytype==1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Plain Text:'.$plainBody);
991
+					if ($this->debugLevel > 3 && $output->nativebodytype == 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' Plain Text:'.$plainBody);
992 992
 					//$body = str_replace("\n","\r\n", str_replace("\r","",$body)); // do we need that?
993 993
 
994
-					if ($bpReturnType==2) //SYNC_BODYPREFERENCE_HTML
994
+					if ($bpReturnType == 2) //SYNC_BODYPREFERENCE_HTML
995 995
 					{
996
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "HTML Body with requested pref 2");
996
+						if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, "HTML Body with requested pref 2");
997 997
 						// Send HTML if requested and native type was html
998 998
 						$output->asbody->type = 2;
999 999
 						$htmlbody = '<html>'.
@@ -1003,23 +1003,23 @@  discard block
 block discarded – undo
1003 1003
 							$css.
1004 1004
 							'</head>'.
1005 1005
 							'<body>';
1006
-						if ($output->nativebodytype==2)
1006
+						if ($output->nativebodytype == 2)
1007 1007
 						{
1008
-							if ($css) Api\Mail\Html::replaceTagsCompletley($body,'style');
1008
+							if ($css) Api\Mail\Html::replaceTagsCompletley($body, 'style');
1009 1009
 							// as we fetch html, and body is HTML, we may not need to handle this
1010 1010
 							$htmlbody .= $body;
1011 1011
 						}
1012 1012
 						else
1013 1013
 						{
1014 1014
 							// html requested but got only plaintext, so fake html
1015
-							$htmlbody .= str_replace("\n","<BR>",str_replace("\r","<BR>", str_replace("\r\n","<BR>",$plainBody)));
1015
+							$htmlbody .= str_replace("\n", "<BR>", str_replace("\r", "<BR>", str_replace("\r\n", "<BR>", $plainBody)));
1016 1016
 						}
1017 1017
 						$htmlbody .= '</body>'.
1018 1018
 								'</html>';
1019 1019
 
1020
-						if(isset($truncsize) && strlen($htmlbody) > $truncsize)
1020
+						if (isset($truncsize) && strlen($htmlbody) > $truncsize)
1021 1021
 						{
1022
-							$htmlbody = Utils::Utf8_truncate($htmlbody,$truncsize);
1022
+							$htmlbody = Utils::Utf8_truncate($htmlbody, $truncsize);
1023 1023
 							$output->asbody->truncated = 1;
1024 1024
 						}
1025 1025
 						// output->nativebodytype is used as marker that the original message was of type ... but is now converted to, as type 2 is requested.
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
 					else
1031 1031
 					{
1032 1032
 						// Send Plaintext as Fallback or if original body is plainttext
1033
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "Plaintext Body:".$plainBody);
1033
+						if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, "Plaintext Body:".$plainBody);
1034 1034
 						/* we use plainBody (set above) instead
1035 1035
 						$bodyStruct = $this->mail->getMessageBody($id,'only_if_no_text'); //'never_display');
1036 1036
 						$plain = $this->mail->getdisplayableBody($this->mail,$bodyStruct);
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 						*/
1041 1041
 						$output->asbody->type = 1;
1042 1042
 						$output->nativebodytype = 1;
1043
-						if(isset($truncsize) &&
1043
+						if (isset($truncsize) &&
1044 1044
 							strlen($plainBody) > $truncsize)
1045 1045
 						{
1046 1046
 							$plainBody = Utils::Utf8_truncate($plainBody, $truncsize);
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
 				}
1060 1060
 			}
1061 1061
 			// end AS12 Stuff
1062
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' gather Header info:'.$headers['subject'].' from:'.$headers['date']);
1062
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' gather Header info:'.$headers['subject'].' from:'.$headers['date']);
1063 1063
 			$output->read = $headers["flags"];
1064 1064
 
1065 1065
 			$output->flag = new SyncMailFlags();
@@ -1079,9 +1079,8 @@  discard block
 block discarded – undo
1079 1079
 				$output->lastverexecuted = AS_FORWARD;
1080 1080
 			}
1081 1081
 			$output->subject = $headers['subject'];
1082
-			$output->importance = $headers['priority'] > 3 ? 0 :
1083
-				($headers['priority'] < 3 ? 2 : 1) ;
1084
-			$output->datereceived = $this->mail->_strtotime($headers['date'],'ts',true);
1082
+			$output->importance = $headers['priority'] > 3 ? 0 : ($headers['priority'] < 3 ? 2 : 1);
1083
+			$output->datereceived = $this->mail->_strtotime($headers['date'], 'ts', true);
1085 1084
 			$output->to = $headers['to_address'];
1086 1085
 			if ($headers['to']) $output->displayto = $headers['to_address']; //$headers['FETCHED_HEADER']['to_name']
1087 1086
 			$output->from = $headers['sender_address'];
@@ -1089,8 +1088,8 @@  discard block
 block discarded – undo
1089 1088
 			if (isset($headers['reply_to_address']) && $headers['reply_to_address']) $output->reply_to = $headers['reply_to_address'];
1090 1089
 
1091 1090
 			$output->messageclass = "IPM.Note";
1092
-			if (stripos($headers['mimetype'],'multipart')!== false &&
1093
-				stripos($headers['mimetype'],'signed')!== false)
1091
+			if (stripos($headers['mimetype'], 'multipart') !== false &&
1092
+				stripos($headers['mimetype'], 'signed') !== false)
1094 1093
 			{
1095 1094
 				$output->messageclass = "IPM.Note.SMIME.MultipartSigned";
1096 1095
 			}
@@ -1099,20 +1098,20 @@  discard block
 block discarded – undo
1099 1098
 			}
1100 1099
 
1101 1100
 			// start handle Attachments (include text/calendar multipart alternative)
1102
-			$attachments = $this->mail->getMessageAttachments($id, $_partID='', $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=true, true, $_folderName);
1101
+			$attachments = $this->mail->getMessageAttachments($id, $_partID = '', $_structure = null, $fetchEmbeddedImages = true, $fetchTextCalendar = true, true, $_folderName);
1103 1102
 			// Attachments should not needed for MIME messages, so skip this part if bpReturnType==4
1104
-			if (/*$bpReturnType != SYNC_BODYPREFERENCE_MIME &&*/ is_array($attachments) && count($attachments)>0)
1103
+			if (/*$bpReturnType != SYNC_BODYPREFERENCE_MIME &&*/ is_array($attachments) && count($attachments) > 0)
1105 1104
 			{
1106
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' gather Attachments for MessageID:'.$id.' found:'.count($attachments));
1105
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' gather Attachments for MessageID:'.$id.' found:'.count($attachments));
1107 1106
 				//error_log(__METHOD__.__LINE__.array2string($attachments));
1108 1107
 				foreach ($attachments as $key => $attach)
1109 1108
 				{
1110
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attach));
1109
+					if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attach));
1111 1110
 
1112 1111
 					// pass meeting requests to calendar plugin
1113 1112
 					if (strtolower($attach['mimeType']) == 'text/calendar' && strtolower($attach['method']) == 'request' &&
1114 1113
 						isset($GLOBALS['egw_info']['user']['apps']['calendar']) &&
1115
-						($attachment = $this->mail->getAttachment($id, $attach['partID'],0,false,false,$_folderName)) &&
1114
+						($attachment = $this->mail->getAttachment($id, $attach['partID'], 0, false, false, $_folderName)) &&
1116 1115
 						($output->meetingrequest = calendar_zpush::meetingRequest($attachment['attachment'])))
1117 1116
 					{
1118 1117
 						//overwrite the globalobjId from calendar object, as: if you delete the mail, that is
@@ -1122,7 +1121,7 @@  discard block
 block discarded – undo
1122 1121
 						$output->messageclass = "IPM.Schedule.Meeting.Request";
1123 1122
 						//$output->messageclass = "IPM.Schedule.Meeting";
1124 1123
 						unset($attachment);
1125
-						continue;	// do NOT add attachment as attachment
1124
+						continue; // do NOT add attachment as attachment
1126 1125
 					}
1127 1126
 					if (Request::GetProtocolVersion() >= 12.0) {
1128 1127
 						$attachment = new SyncBaseAttachment();
@@ -1130,33 +1129,33 @@  discard block
 block discarded – undo
1130 1129
 							$output->asattachments = array();
1131 1130
 						$attachment->estimatedDataSize = $attach['size'];
1132 1131
 						$attachment->method = 1;
1133
-						$attachment->filereference = $folderid . ":" . $id . ":" . $attach['partID'];
1132
+						$attachment->filereference = $folderid.":".$id.":".$attach['partID'];
1134 1133
 					} else {
1135 1134
 						$attachment = new SyncAttachment();
1136 1135
 						if (!isset($output->attachments) || !is_array($output->attachments))
1137 1136
 							$output->attachments = array();
1138 1137
 						$attachment->attsize = $attach['size'];
1139 1138
 						$attachment->attmethod = 1;
1140
-						$attachment->attname = $folderid . ":" . $id . ":" . $attach['partID'];//$key;
1139
+						$attachment->attname = $folderid.":".$id.":".$attach['partID']; //$key;
1141 1140
 					}
1142 1141
 
1143 1142
 					$attachment->displayname = $attach['name'];
1144 1143
 					//error_log(__METHOD__.__LINE__.'->'.$folderid . ":" . $id . ":" . $attach['partID']);
1145 1144
 
1146
-					$attachment->attoid = "";//isset($part->headers['content-id']) ? trim($part->headers['content-id']) : "";
1145
+					$attachment->attoid = ""; //isset($part->headers['content-id']) ? trim($part->headers['content-id']) : "";
1147 1146
 					//$attachment->isinline=0; // if not inline, do not use isinline
1148
-					if (!empty($attach['cid']) && $attach['cid'] <> 'NIL' )
1147
+					if (!empty($attach['cid']) && $attach['cid'] <> 'NIL')
1149 1148
 					{
1150 1149
 						if ($bpReturnType != 4 && $attach['disposition'] == 'inline')
1151 1150
 						{
1152 1151
 							$attachment->isinline = true;
1153 1152
 						}
1154 1153
 						if (Request::GetProtocolVersion() >= 12.0) {
1155
-							$attachment->method=1;
1156
-							$attachment->contentid= str_replace(array("<",">"), "",$attach['cid']);
1154
+							$attachment->method = 1;
1155
+							$attachment->contentid = str_replace(array("<", ">"), "", $attach['cid']);
1157 1156
 						} else {
1158
-							$attachment->attmethod=6;
1159
-							$attachment->attoid = str_replace(array("<",">"), "",$attach['cid']);
1157
+							$attachment->attmethod = 6;
1158
+							$attachment->attoid = str_replace(array("<", ">"), "", $attach['cid']);
1160 1159
 						}
1161 1160
 						//	ZLog::Write(LOGLEVEL_DEBUG, "'".$part->headers['content-id']."'  ".$attachment->contentid);
1162 1161
 						$attachment->contenttype = trim($attach['mimeType']);
@@ -1177,7 +1176,7 @@  discard block
 block discarded – undo
1177 1176
             // Language Code Page ID: http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756%28v=vs.85%29.aspx
1178 1177
             $output->internetcpid = INTERNET_CPID_UTF8;
1179 1178
 
1180
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($output));
1179
+			if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.array2string($output));
1181 1180
 //$this->debugLevel=0;
1182 1181
 			return $output;
1183 1182
 		}
@@ -1200,30 +1199,30 @@  discard block
 block discarded – undo
1200 1199
 	{
1201 1200
 		if (!class_exists('calendar_zpush'))
1202 1201
 		{
1203
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(...) no EGroupware calendar installed!");
1202
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."(...) no EGroupware calendar installed!");
1204 1203
 			return null;
1205 1204
 		}
1206 1205
 		if (!($stat = $this->StatMessage($folderid, $requestid)))
1207 1206
 		{
1208
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($requestid, '$folderid', $response) returning FALSE (can NOT stat message)");
1207
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."($requestid, '$folderid', $response) returning FALSE (can NOT stat message)");
1209 1208
 			return false;
1210 1209
 		}
1211 1210
 		$ret = false;
1212
-		foreach($this->mail->getMessageAttachments($requestid, $_partID='', $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=true) as $key => $attach)
1211
+		foreach ($this->mail->getMessageAttachments($requestid, $_partID = '', $_structure = null, $fetchEmbeddedImages = true, $fetchTextCalendar = true) as $key => $attach)
1213 1212
 		{
1214 1213
 			if (strtolower($attach['mimeType']) == 'text/calendar' && strtolower($attach['method']) == 'request' &&
1215
-				($attachment = $this->mail->getAttachment($requestid, $attach['partID'],0,false)))
1214
+				($attachment = $this->mail->getAttachment($requestid, $attach['partID'], 0, false)))
1216 1215
 			{
1217
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($requestid, '$folderid', $response) iCal found, calling now backend->MeetingResponse('$attachment[attachment]')");
1216
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."($requestid, '$folderid', $response) iCal found, calling now backend->MeetingResponse('$attachment[attachment]')");
1218 1217
 
1219 1218
 				// calling backend again with iCal attachment, to let calendar add the event
1220 1219
 				$ret = $this->backend->MeetingResponse($attachment['attachment'],
1221
-					$this->backend->createID('calendar',$GLOBALS['egw_info']['user']['account_id']),
1220
+					$this->backend->createID('calendar', $GLOBALS['egw_info']['user']['account_id']),
1222 1221
 					$response);
1223 1222
 				break;
1224 1223
 			}
1225 1224
 		}
1226
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($requestid, '$folderid', $response) returning ".array2string($ret));
1225
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."($requestid, '$folderid', $response) returning ".array2string($ret));
1227 1226
 		return $ret;
1228 1227
 	}
1229 1228
 
@@ -1237,9 +1236,9 @@  discard block
 block discarded – undo
1237 1236
      * @param string $attname - should contain (folder)id
1238 1237
 	 * @return SyncItemOperationsAttachment-object
1239 1238
 	 */
1240
-	function GetAttachmentData($fid,$attname) {
1241
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": $fid (attname: '$attname')");
1242
-		return $this->_GetAttachmentData($fid,$attname);
1239
+	function GetAttachmentData($fid, $attname) {
1240
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.": $fid (attname: '$attname')");
1241
+		return $this->_GetAttachmentData($fid, $attname);
1243 1242
 	}
1244 1243
 
1245 1244
 	/**
@@ -1252,9 +1251,9 @@  discard block
 block discarded – undo
1252 1251
      * @param string $attname - should contain (folder)id
1253 1252
 	 * @return SyncItemOperationsAttachment-object
1254 1253
 	 */
1255
-	function ItemOperationsGetAttachmentData($fid,$attname) {
1256
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": $fid (attname: '$attname')");
1257
-		return $this->_GetAttachmentData($fid,$attname);
1254
+	function ItemOperationsGetAttachmentData($fid, $attname) {
1255
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.": $fid (attname: '$attname')");
1256
+		return $this->_GetAttachmentData($fid, $attname);
1258 1257
 	}
1259 1258
 
1260 1259
 	/**
@@ -1266,23 +1265,23 @@  discard block
 block discarded – undo
1266 1265
      * @param string $attname - should contain (folder)id
1267 1266
 	 * @return SyncItemOperationsAttachment-object
1268 1267
 	 */
1269
-	private function _GetAttachmentData($fid,$attname)
1268
+	private function _GetAttachmentData($fid, $attname)
1270 1269
 	{
1271
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": $fid (attname: '$attname')".function_backtrace());
1270
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.": $fid (attname: '$attname')".function_backtrace());
1272 1271
 		//error_log(__METHOD__.__LINE__." Fid: $fid (attname: '$attname')");
1273 1272
 		list($folderid, $id, $part) = explode(":", $attname);
1274 1273
 
1275 1274
 		$this->splitID($folderid, $account, $folder);
1276 1275
 
1277
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1276
+		if (!isset($this->mail)) $this->mail = Mail::getInstance(false, self::$profileID, true, false, true);
1278 1277
 
1279 1278
 		$this->mail->reopen($folder);
1280
-		$attachment = $this->mail->getAttachment($id,$part,0,false,true,$folder);
1279
+		$attachment = $this->mail->getAttachment($id, $part, 0, false, true, $folder);
1281 1280
 		$SIOattachment = new SyncItemOperationsAttachment();
1282
-		fseek($attachment['attachment'], 0, SEEK_SET);	// z-push requires stream seeked to start
1281
+		fseek($attachment['attachment'], 0, SEEK_SET); // z-push requires stream seeked to start
1283 1282
 		$SIOattachment->data = $attachment['attachment'];
1284 1283
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": $fid (attname: '$attname') Data:".$attachment['attachment']);
1285
-		if (isset($attachment['type']) )
1284
+		if (isset($attachment['type']))
1286 1285
 			$SIOattachment->contenttype = $attachment['type'];
1287 1286
 
1288 1287
 		unset($attachment);
@@ -1325,17 +1324,17 @@  discard block
 block discarded – undo
1325 1324
 	 */
1326 1325
 	function ChangeMessage($folderid, $id, $message, $contentParameters)
1327 1326
 	{
1328
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." $folderid, $id,".array2string($message).",".array2string($contentParameters));
1327
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." $folderid, $id,".array2string($message).",".array2string($contentParameters));
1329 1328
 		//unset($folderid, $id, $message, $contentParameters);
1330 1329
 		$account = $folder = null;
1331 1330
 		$this->splitID($folderid, $account, $folder);
1332 1331
 		if (isset($message->flag)) {
1333 1332
 			if (isset($message->flag->flagstatus) && $message->flag->flagstatus == 2) {
1334
-				$rv = $this->mail->flagMessages((($message->flag->flagstatus == 2) ? "flagged" : "unflagged"), $id,$folder);
1335
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." -> set ".array2string($id).' in Folder '.$folder." as " . (($message->flag->flagstatus == 2) ? "flagged" : "unflagged") . "-->". $rv);
1333
+				$rv = $this->mail->flagMessages((($message->flag->flagstatus == 2) ? "flagged" : "unflagged"), $id, $folder);
1334
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." -> set ".array2string($id).' in Folder '.$folder." as ".(($message->flag->flagstatus == 2) ? "flagged" : "unflagged")."-->".$rv);
1336 1335
 			} else {
1337
-				$rv = $this->mail->flagMessages("unflagged", $id,$folder);
1338
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." -> set ".array2string($id).' in Folder '.$folder." as " . "unflagged" . "-->". $rv);
1336
+				$rv = $this->mail->flagMessages("unflagged", $id, $folder);
1337
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." -> set ".array2string($id).' in Folder '.$folder." as "."unflagged"."-->".$rv);
1339 1338
 			}
1340 1339
 		}
1341 1340
 		return $this->StatMessage($folderid, $id);
@@ -1357,23 +1356,23 @@  discard block
 block discarded – undo
1357 1356
 	 */
1358 1357
 	public function MoveMessage($folderid, $id, $newfolderid, $contentParameters)
1359 1358
 	{
1360
-		unset($contentParameters);	// not used, but required by function signature
1359
+		unset($contentParameters); // not used, but required by function signature
1361 1360
 		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-MoveMessage: (sfid: '$folderid'  id: '$id'  dfid: '$newfolderid' )");
1362 1361
 		$account = $srcFolder = $destFolder = null;
1363 1362
 		$this->splitID($folderid, $account, $srcFolder);
1364 1363
 		$this->splitID($newfolderid, $account, $destFolder);
1365 1364
 		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-MoveMessage: (SourceFolder: '$srcFolder'  id: '$id'  DestFolder: '$destFolder' )");
1366
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1365
+		if (!isset($this->mail)) $this->mail = Mail::getInstance(false, self::$profileID, true, false, true);
1367 1366
 		$this->mail->reopen($destFolder);
1368 1367
 		$status = $this->mail->getFolderStatus($destFolder);
1369 1368
 		$uidNext = $status['uidnext'];
1370 1369
 		$this->mail->reopen($srcFolder);
1371 1370
 
1372 1371
 		// move message
1373
-		$rv = $this->mail->moveMessages($destFolder,(array)$id,true,$srcFolder,true);
1374
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.": New Status of $destFolder :".array2string($status).", ReturnValOf moveMessage".array2string($rv)); // this may be true, so try using the nextUID value by examine
1372
+		$rv = $this->mail->moveMessages($destFolder, (array)$id, true, $srcFolder, true);
1373
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.": New Status of $destFolder :".array2string($status).", ReturnValOf moveMessage".array2string($rv)); // this may be true, so try using the nextUID value by examine
1375 1374
 		// return the new id "as string"
1376
-		return ($rv===true ? $uidNext : $rv[$id]) . "";
1375
+		return ($rv === true ? $uidNext : $rv[$id])."";
1377 1376
 	}
1378 1377
 
1379 1378
 	/**
@@ -1381,7 +1380,7 @@  discard block
 block discarded – undo
1381 1380
 	 *
1382 1381
 	 *  @param int $cutoffdate =null timestamp with cutoffdate, default 12 weeks
1383 1382
 	 */
1384
-	public function GetMessageList($folderid, $cutoffdate=NULL)
1383
+	public function GetMessageList($folderid, $cutoffdate = NULL)
1385 1384
 	{
1386 1385
 		if ($cutoffdate > 0)
1387 1386
 		{
@@ -1394,8 +1393,8 @@  discard block
 block discarded – undo
1394 1393
 			{
1395 1394
 				$maximumSyncRangeInDays = $GLOBALS['egw_info']['user']['preferences']['activesync']['mail-maximumSyncRange'];
1396 1395
 			}
1397
-			$cutoffdate = (is_numeric($maximumSyncRangeInDays) ? Api\DateTime::to('now','ts')-(3600*24*$maximumSyncRangeInDays):null);
1398
-			if (is_numeric($maximumSyncRangeInDays)) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' Client set no truncationdate. Using '.$maximumSyncRangeInDays.' days.'.date("d-M-Y", $cutoffdate));
1396
+			$cutoffdate = (is_numeric($maximumSyncRangeInDays) ? Api\DateTime::to('now', 'ts') - (3600 * 24 * $maximumSyncRangeInDays) : null);
1397
+			if (is_numeric($maximumSyncRangeInDays)) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.' Client set no truncationdate. Using '.$maximumSyncRangeInDays.' days.'.date("d-M-Y", $cutoffdate));
1399 1398
 		}
1400 1399
 		return $this->fetchMessages($folderid, $cutoffdate);
1401 1400
 	}
@@ -1413,11 +1412,11 @@  discard block
 block discarded – undo
1413 1412
 	 * @param boolean $return_all_headers =false true: additinal contain all headers eg. "subject"
1414 1413
 	 * @return array uid => array StatMessage($folderid, $_id)
1415 1414
 	 */
1416
-	private function fetchMessages($folderid, $cutoffdate=NULL, $_id=NULL, $return_all_headers=false)
1415
+	private function fetchMessages($folderid, $cutoffdate = NULL, $_id = NULL, $return_all_headers = false)
1417 1416
 	{
1418 1417
 		static $headers = array();
1419 1418
 
1420
-		if ($this->debugLevel>1) $gstarttime = microtime (true);
1419
+		if ($this->debugLevel > 1) $gstarttime = microtime(true);
1421 1420
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__);
1422 1421
 		$rv_messages = array();
1423 1422
 		// if the message is still available within the class, we use it instead of fetching it again
@@ -1428,64 +1427,64 @@  discard block
 block discarded – undo
1428 1427
 		}
1429 1428
 		else
1430 1429
 		{
1431
-			$headers = array();	// clear cache to not use too much memory
1430
+			$headers = array(); // clear cache to not use too much memory
1432 1431
 
1433
-			if ($this->debugLevel>1) $starttime = microtime (true);
1432
+			if ($this->debugLevel > 1) $starttime = microtime(true);
1434 1433
 			$this->_connect($this->account);
1435
-			if ($this->debugLevel>1)
1434
+			if ($this->debugLevel > 1)
1436 1435
 			{
1437 1436
 				$endtime = microtime(true) - $starttime;
1438
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__. " connect took : ".$endtime.' for account:'.$this->account);
1437
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." connect took : ".$endtime.' for account:'.$this->account);
1439 1438
 			}
1440 1439
 			$messagelist = $_filter = array();
1441 1440
 			// if not connected, any further action must fail
1442
-			if (!empty($cutoffdate)) $_filter = array('status'=>array('UNDELETED'),'range'=>"SINCE",'date'=> date("d-M-Y", $cutoffdate));
1443
-			if ($this->debugLevel>1) $starttime = microtime (true);
1441
+			if (!empty($cutoffdate)) $_filter = array('status'=>array('UNDELETED'), 'range'=>"SINCE", 'date'=> date("d-M-Y", $cutoffdate));
1442
+			if ($this->debugLevel > 1) $starttime = microtime(true);
1444 1443
 			$account = $_folderName = $id = null;
1445
-			$this->splitID($folderid,$account,$_folderName,$id);
1446
-			if ($this->debugLevel>1)
1444
+			$this->splitID($folderid, $account, $_folderName, $id);
1445
+			if ($this->debugLevel > 1)
1447 1446
 			{
1448 1447
 				$endtime = microtime(true) - $starttime;
1449
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__. " splitID took : ".$endtime.' for FolderID:'.$folderid);
1448
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." splitID took : ".$endtime.' for FolderID:'.$folderid);
1450 1449
 			}
1451
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_id).'/'.$id);
1452
-			if ($this->debugLevel>1) $starttime = microtime (true);
1453
-			$_numberOfMessages = (empty($cutoffdate)?250:99999);
1454
-			$rv_messages = $this->mail->getHeaders($_folderName, $_startMessage=1, $_numberOfMessages, $_sort=0, $_reverse=false, $_filter, $_id);
1455
-			if ($this->debugLevel>1)
1450
+			if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_id).'/'.$id);
1451
+			if ($this->debugLevel > 1) $starttime = microtime(true);
1452
+			$_numberOfMessages = (empty($cutoffdate) ? 250 : 99999);
1453
+			$rv_messages = $this->mail->getHeaders($_folderName, $_startMessage = 1, $_numberOfMessages, $_sort = 0, $_reverse = false, $_filter, $_id);
1454
+			if ($this->debugLevel > 1)
1456 1455
 			{
1457 1456
 				$endtime = microtime(true) - $starttime;
1458
-				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__. " getHeaders call took : ".$endtime.' for FolderID:'.$_folderName);
1457
+				ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." getHeaders call took : ".$endtime.' for FolderID:'.$_folderName);
1459 1458
 			}
1460 1459
 		}
1461
-		if ($_id == NULL && $this->debugLevel>1)  ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." found :". count($rv_messages['header']));
1460
+		if ($_id == NULL && $this->debugLevel > 1)  ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." found :".count($rv_messages['header']));
1462 1461
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Result:'.array2string($rv_messages));
1463 1462
 		$messagelist = array();
1464
-		if (!isset($rv_messages['header'])||empty($rv_messages['header'])) return $messagelist;
1463
+		if (!isset($rv_messages['header']) || empty($rv_messages['header'])) return $messagelist;
1465 1464
 		//if ($_returnModHash) $messageFolderHash = array();
1466 1465
 		foreach ((array)$rv_messages['header'] as $k => $vars)
1467 1466
 		{
1468
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' ID to process:'.$vars['uid'].' Subject:'.$vars['subject']);
1467
+			if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' ID to process:'.$vars['uid'].' Subject:'.$vars['subject']);
1469 1468
 			$headers[$vars['uid']] = $vars;
1470
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' MailID:'.$k.'->'.array2string($vars));
1469
+			if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' MailID:'.$k.'->'.array2string($vars));
1471 1470
 			if (!empty($vars['deleted'])) continue; // cut of deleted messages
1472 1471
 			if ($cutoffdate && $vars['date'] < $cutoffdate) continue; // message is out of range for cutoffdate, ignore it
1473
-			if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' ID to report:'.$vars['uid'].' Subject:'.$vars['subject']);
1472
+			if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' ID to report:'.$vars['uid'].' Subject:'.$vars['subject']);
1474 1473
 			$mess = $return_all_headers ? $vars : array();
1475 1474
 			$mess["mod"] = self::doFlagsMod($vars).$vars['date'];
1476 1475
 			$mess["id"] = $vars['uid'];
1477 1476
 			// 'seen' aka 'read' is the only flag we want to know about
1478 1477
 			$mess["flags"] = 0;
1479 1478
 			// outlook supports additional flags, set them to 0
1480
-			if($vars["seen"]) $mess["flags"] = 1;
1481
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($mess));
1479
+			if ($vars["seen"]) $mess["flags"] = 1;
1480
+			if ($this->debugLevel > 3) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.array2string($mess));
1482 1481
 			$messagelist[$vars['uid']] = $mess;
1483 1482
 			unset($mess);
1484 1483
 		}
1485
-		if ($this->debugLevel>1)
1484
+		if ($this->debugLevel > 1)
1486 1485
 		{
1487 1486
 			$endtime = microtime(true) - $gstarttime;
1488
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__. " total time used : ".$endtime.' for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_id).'/'.$id);
1487
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__." total time used : ".$endtime.' for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_id).'/'.$id);
1489 1488
 		}
1490 1489
 		return $messagelist;
1491 1490
 	}
@@ -1536,32 +1535,32 @@  discard block
 block discarded – undo
1536 1535
 	public function getSearchResultsMailbox($_searchquery)
1537 1536
 	{
1538 1537
 		//$this->debugLevel=1;
1539
-		$searchquery=$_searchquery->GetDataArray();
1538
+		$searchquery = $_searchquery->GetDataArray();
1540 1539
 		if (!is_array($searchquery)) return array();
1541
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($searchquery));
1540
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.array2string($searchquery));
1542 1541
 
1543 1542
 		if (isset($searchquery['searchrebuildresults'])) {
1544 1543
 			$rebuildresults = $searchquery['searchrebuildresults'];
1545 1544
 		} else {
1546 1545
 			$rebuildresults = false;
1547 1546
 		}
1548
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,  'RebuildResults ['.$rebuildresults.']' );
1547
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, 'RebuildResults ['.$rebuildresults.']');
1549 1548
 
1550 1549
 		if (isset($searchquery['deeptraversal'])) {
1551 1550
 			$deeptraversal = $searchquery['deeptraversal'];
1552 1551
 		} else {
1553 1552
 			$deeptraversal = false;
1554 1553
 		}
1555
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,  'DeepTraversal ['.$deeptraversal.']' );
1554
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, 'DeepTraversal ['.$deeptraversal.']');
1556 1555
 
1557 1556
 		if (isset($searchquery['searchrange'])) {
1558
-			$range = explode("-",$_searchquery->GetSearchRange());
1559
-			$start =$range[0] + 1;
1557
+			$range = explode("-", $_searchquery->GetSearchRange());
1558
+			$start = $range[0] + 1;
1560 1559
 			$limit = $range[1] - $range[0] + 1;
1561 1560
 		} else {
1562 1561
 			$range = false;
1563 1562
 		}
1564
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,  'Range ['.print_r($range, true).']' );
1563
+		if ($this->debugLevel > 0) ZLog::Write(LOGLEVEL_DEBUG, 'Range ['.print_r($range, true).']');
1565 1564
 
1566 1565
 		//foreach($searchquery['query'] as $k => $value) {
1567 1566
 		//	$query = $value;
@@ -1584,15 +1583,15 @@  discard block
 block discarded – undo
1584 1583
 		}
1585 1584
 		if (!$folderid)
1586 1585
 		{
1587
-			$_folderName = ($this->mail->sessionData['mailbox']?$this->mail->sessionData['mailbox']:'INBOX');
1588
-			$folderid = $this->createID($account=0,$_folderName);
1586
+			$_folderName = ($this->mail->sessionData['mailbox'] ? $this->mail->sessionData['mailbox'] : 'INBOX');
1587
+			$folderid = $this->createID($account = 0, $_folderName);
1589 1588
 		}
1590
-		$rv = $this->splitID($folderid,$account,$_folderName,$id);
1591
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' ProfileID:'.self::$profileID.' FolderID:'.$folderid.' Foldername:'.$_folderName);
1589
+		$rv = $this->splitID($folderid, $account, $_folderName, $id);
1590
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' ProfileID:'.self::$profileID.' FolderID:'.$folderid.' Foldername:'.$_folderName);
1592 1591
 		$this->_connect($account);
1593 1592
 		// this should not be needed ???
1594
-		Mail::$supportsORinQuery[self::$profileID]=true; // trigger quicksearch (if possible)
1595
-		$_filter = array('type'=> (Mail::$supportsORinQuery[self::$profileID]?'quick':'subject'),
1593
+		Mail::$supportsORinQuery[self::$profileID] = true; // trigger quicksearch (if possible)
1594
+		$_filter = array('type'=> (Mail::$supportsORinQuery[self::$profileID] ? 'quick' : 'subject'),
1596 1595
 						 'string'=> $searchText,
1597 1596
 						 'status'=>'any'
1598 1597
 						);
@@ -1607,22 +1606,22 @@  discard block
 block discarded – undo
1607 1606
 		 * 		[searchvalueless] => 2015-07-14T15:11:00.000Z , BEFORE
1608 1607
 		 */
1609 1608
 			$_filter['range'] = "BETWEEN";
1610
-			list($sincedate,$crap) = explode('T',$searchquery['searchvaluegreater']);
1611
-			list($beforedate,$crap) = explode('T',$searchquery['searchvalueless']);
1612
-			$_filter['before'] = date("d-M-Y", Api\DateTime::to($beforedate,'ts'));
1613
-			$_filter['since'] = date("d-M-Y", Api\DateTime::to($sincedate,'ts'));
1609
+			list($sincedate, $crap) = explode('T', $searchquery['searchvaluegreater']);
1610
+			list($beforedate, $crap) = explode('T', $searchquery['searchvalueless']);
1611
+			$_filter['before'] = date("d-M-Y", Api\DateTime::to($beforedate, 'ts'));
1612
+			$_filter['since'] = date("d-M-Y", Api\DateTime::to($sincedate, 'ts'));
1614 1613
 		}
1615 1614
 		//$_filter[] = array('type'=>"SINCE",'string'=> date("d-M-Y", $cutoffdate));
1616
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter));
1617
-		$rv_messages = $this->mail->getHeaders($_folderName, $_startMessage=($range?$start:1), $_numberOfMessages=($limit?$limit:9999999), $_sort=0, $_reverse=false, $_filter, $_id=NULL);
1615
+		if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter));
1616
+		$rv_messages = $this->mail->getHeaders($_folderName, $_startMessage = ($range ? $start : 1), $_numberOfMessages = ($limit ? $limit : 9999999), $_sort = 0, $_reverse = false, $_filter, $_id = NULL);
1618 1617
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($rv_messages));
1619
-		$list=array();
1618
+		$list = array();
1620 1619
 
1621 1620
 		$cnt = count($rv_messages['header']);
1622 1621
 		//$list['status'] = 1;
1623 1622
 		$list['searchtotal'] = $cnt;
1624 1623
 		$list["range"] = $_searchquery->GetSearchRange();
1625
-		foreach((array)$rv_messages['header'] as $i => $vars)
1624
+		foreach ((array)$rv_messages['header'] as $i => $vars)
1626 1625
 		{
1627 1626
 			$list[] = array(
1628 1627
 				"class" => "Email",
@@ -1642,20 +1641,20 @@  discard block
 block discarded – undo
1642 1641
 	 * @param string $folder
1643 1642
 	 * @return string
1644 1643
 	 */
1645
-	private function getParentID($account,$folder)
1644
+	private function getParentID($account, $folder)
1646 1645
 	{
1647 1646
 		$this->_connect($account);
1648
-		if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true,false);
1647
+		if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true, false);
1649 1648
 
1650 1649
 		$mailFolder = $this->folders[$folder];
1651 1650
 		if (!isset($mailFolder)) return false;
1652
-		$delimiter = (isset($mailFolder->delimiter)?$mailFolder->delimiter:$this->mail->getHierarchyDelimiter());
1653
-		$parent = explode($delimiter,$folder);
1651
+		$delimiter = (isset($mailFolder->delimiter) ? $mailFolder->delimiter : $this->mail->getHierarchyDelimiter());
1652
+		$parent = explode($delimiter, $folder);
1654 1653
 		array_pop($parent);
1655
-		$parent = implode($delimiter,$parent);
1654
+		$parent = implode($delimiter, $parent);
1656 1655
 
1657 1656
 		$id = $parent && $this->folders[$parent] ? $this->createID($account, $parent) : '0';
1658
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."('$folder') --> parent=$parent --> $id");
1657
+		if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."('$folder') --> parent=$parent --> $id");
1659 1658
 		return $id;
1660 1659
 	}
1661 1660
 
@@ -1675,48 +1674,48 @@  discard block
 block discarded – undo
1675 1674
 			$account = $folder = null;
1676 1675
 			$this->splitID($id, $account, $folder);
1677 1676
 		}
1678
-		catch(Exception $e) {
1679
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' failed for '.$e->getMessage());
1680
-			return $folderObj=false;
1677
+		catch (Exception $e) {
1678
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' failed for '.$e->getMessage());
1679
+			return $folderObj = false;
1681 1680
 		}
1682 1681
 		$this->_connect($account);
1683
-		if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true,false);
1682
+		if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true, false);
1684 1683
 
1685 1684
 		$mailFolder = $this->folders[$folder];
1686
-		if (!isset($mailFolder)) return $folderObj=false;
1685
+		if (!isset($mailFolder)) return $folderObj = false;
1687 1686
 
1688 1687
 		$folderObj = new SyncFolder();
1689 1688
 		$folderObj->serverid = $id;
1690
-		$folderObj->parentid = $this->getParentID($account,$folder);
1689
+		$folderObj->parentid = $this->getParentID($account, $folder);
1691 1690
 		$folderObj->displayname = $mailFolder->shortDisplayName;
1692
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." ID: $id, Account:$account, Folder:$folder");
1691
+		if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." ID: $id, Account:$account, Folder:$folder");
1693 1692
 		// get folder-type
1694
-		foreach($this->folders as $inbox => $mailFolder) break;
1693
+		foreach ($this->folders as $inbox => $mailFolder) break;
1695 1694
 		if ($folder == $inbox)
1696 1695
 		{
1697 1696
 			$folderObj->type = SYNC_FOLDER_TYPE_INBOX;
1698 1697
 		}
1699
-		elseif($this->mail->isDraftFolder($folder, false, true))
1698
+		elseif ($this->mail->isDraftFolder($folder, false, true))
1700 1699
 		{
1701 1700
 			//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' isDraft');
1702 1701
 			$folderObj->type = SYNC_FOLDER_TYPE_DRAFTS;
1703 1702
 			$folderObj->parentid = 0; // required by devices
1704 1703
 		}
1705
-		elseif($this->mail->isTrashFolder($folder, false, true))
1704
+		elseif ($this->mail->isTrashFolder($folder, false, true))
1706 1705
 		{
1707 1706
 			$folderObj->type = SYNC_FOLDER_TYPE_WASTEBASKET;
1708 1707
 			$this->_wasteID = $folder;
1709 1708
 			//error_log(__METHOD__.__LINE__.' TrashFolder:'.$this->_wasteID);
1710 1709
 			$folderObj->parentid = 0; // required by devices
1711 1710
 		}
1712
-		elseif($this->mail->isSentFolder($folder, false, true))
1711
+		elseif ($this->mail->isSentFolder($folder, false, true))
1713 1712
 		{
1714 1713
 			$folderObj->type = SYNC_FOLDER_TYPE_SENTMAIL;
1715 1714
 			$folderObj->parentid = 0; // required by devices
1716 1715
 			$this->_sentID = $folder;
1717 1716
 			//error_log(__METHOD__.__LINE__.' SentFolder:'.$this->_sentID);
1718 1717
 		}
1719
-		elseif($this->mail->isOutbox($folder, false, true))
1718
+		elseif ($this->mail->isOutbox($folder, false, true))
1720 1719
 		{
1721 1720
 			//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' isOutbox');
1722 1721
 			$folderObj->type = SYNC_FOLDER_TYPE_OUTBOX;
@@ -1728,7 +1727,7 @@  discard block
 block discarded – undo
1728 1727
 			$folderObj->type = SYNC_FOLDER_TYPE_USER_MAIL;
1729 1728
 		}
1730 1729
 
1731
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($id) --> $folder --> type=$folderObj->type, parentID=$folderObj->parentid, displayname=$folderObj->displayname");
1730
+		if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."($id) --> $folder --> type=$folderObj->type, parentID=$folderObj->parentid, displayname=$folderObj->displayname");
1732 1731
 		return $folderObj;
1733 1732
 	}
1734 1733
 
@@ -1776,18 +1775,18 @@  discard block
 block discarded – undo
1776 1775
 
1777 1776
 		if ($type != 'mail') return false;
1778 1777
 
1779
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1778
+		if (!isset($this->mail)) $this->mail = Mail::getInstance(false, self::$profileID, true, false, true);
1780 1779
 
1781 1780
         $this->mail->reopen($folder);
1782 1781
 
1783
-		if (!($status = $this->mail->getFolderStatus($folder,$ignoreStatusCache=true)))
1782
+		if (!($status = $this->mail->getFolderStatus($folder, $ignoreStatusCache = true)))
1784 1783
 		{
1785
-            ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": could not stat folder $folder ");
1784
+            ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.": could not stat folder $folder ");
1786 1785
             return false;
1787 1786
         }
1788
-		$syncstate = "M:". $status['messages'] ."-R:". $status['recent'] ."-U:". $status['unseen']."-NUID:".$status['uidnext']."-UIDV:".$status['uidvalidity'];
1787
+		$syncstate = "M:".$status['messages']."-R:".$status['recent']."-U:".$status['unseen']."-NUID:".$status['uidnext']."-UIDV:".$status['uidvalidity'];
1789 1788
 
1790
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($folderid, ...) $folder ($account) returning ".array2string($syncstate));
1789
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."($folderid, ...) $folder ($account) returning ".array2string($syncstate));
1791 1790
 		return array();
1792 1791
 	}
1793 1792
 
@@ -1800,8 +1799,8 @@  discard block
 block discarded – undo
1800 1799
 	function GetWasteBasket()
1801 1800
 	{
1802 1801
 		$this->_connect($this->account);
1803
-		$id = $this->createID($account=0, $this->_wasteID);
1804
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__."() account=$this->account returned $id for folder $this->_wasteID");
1802
+		$id = $this->createID($account = 0, $this->_wasteID);
1803
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__."() account=$this->account returned $id for folder $this->_wasteID");
1805 1804
 		return $id;
1806 1805
 	}
1807 1806
 
@@ -1822,7 +1821,7 @@  discard block
 block discarded – undo
1822 1821
      */
1823 1822
     public function DeleteMessage($folderid, $id, $contentParameters)
1824 1823
 	{
1825
-		unset($contentParameters);	// not used, but required by function signature
1824
+		unset($contentParameters); // not used, but required by function signature
1826 1825
 		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-DeleteMessage: (fid: '$folderid'  id: '$id' )");
1827 1826
 		/*
1828 1827
 		$this->imap_reopenFolder($folderid);
@@ -1833,7 +1832,7 @@  discard block
 block discarded – undo
1833 1832
 		// we may have to split folderid
1834 1833
 		$account = $folder = null;
1835 1834
 		$this->splitID($folderid, $account, $folder);
1836
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' '.$folderid.'->'.$folder);
1835
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__.' '.$folderid.'->'.$folder);
1837 1836
 		$_messageUID = (array)$id;
1838 1837
 
1839 1838
 		$this->_connect($this->account);
@@ -1845,9 +1844,9 @@  discard block
 block discarded – undo
1845 1844
 		catch (Api\Exception $e)
1846 1845
 		{
1847 1846
 			$error = $e->getMessage();
1848
-			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." $_messageUID, $folder ->".$error);
1847
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.__LINE__." $_messageUID, $folder ->".$error);
1849 1848
 			// if the server thinks the message does not exist report deletion as success
1850
-			if (stripos($error,'[NONEXISTENT]')!==false) return true;
1849
+			if (stripos($error, '[NONEXISTENT]') !== false) return true;
1851 1850
 			return false;
1852 1851
 		}
1853 1852
 
@@ -1881,15 +1880,15 @@  discard block
 block discarded – undo
1881 1880
      */
1882 1881
     public function SetReadFlag($folderid, $id, $flags, $contentParameters)
1883 1882
 	{
1884
-		unset($contentParameters);	// not used, but required by function signature
1883
+		unset($contentParameters); // not used, but required by function signature
1885 1884
 		// ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SetReadFlag: (fid: '$folderid'  id: '$id'  flags: '$flags' )");
1886 1885
 		$account = $folder = null;
1887 1886
 		$this->splitID($folderid, $account, $folder);
1888 1887
 
1889 1888
 		$_messageUID = (array)$id;
1890 1889
 		$this->_connect($this->account);
1891
-		$rv = $this->mail->flagMessages((($flags) ? "read" : "unread"), $_messageUID,$folder);
1892
-		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SetReadFlag -> set ".array2string($_messageUID).' in Folder '.$folder." as " . (($flags) ? "read" : "unread") . "-->". $rv);
1890
+		$rv = $this->mail->flagMessages((($flags) ? "read" : "unread"), $_messageUID, $folder);
1891
+		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SetReadFlag -> set ".array2string($_messageUID).' in Folder '.$folder." as ".(($flags) ? "read" : "unread")."-->".$rv);
1893 1892
 
1894 1893
 		return $rv;
1895 1894
 	}
@@ -1907,7 +1906,7 @@  discard block
 block discarded – undo
1907 1906
 	 */
1908 1907
 	public function ChangeFolder($id, $oldid, $displayname, $type)
1909 1908
 	{
1910
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."('$id', '$oldid', '$displayname', $type)");
1909
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."('$id', '$oldid', '$displayname', $type)");
1911 1910
 		$account = $parent_id = null;
1912 1911
 		$this->splitID($id, $account, $parentFolder, $app);
1913 1912
 
@@ -1924,17 +1923,17 @@  discard block
 block discarded – undo
1924 1923
 			$this->splitID($oldid, $account, $oldFolder, $app);
1925 1924
 			$old_hash = $this->folder2hash($account, $oldFolder);
1926 1925
 		}
1927
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.":{$action}Folder('$id'=>($parentFolder ($parent_id)), '$oldid'".($oldid?"=>($oldFolder ($old_hash))":'').", '$displayname', $type)");
1926
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.":{$action}Folder('$id'=>($parentFolder ($parent_id)), '$oldid'".($oldid ? "=>($oldFolder ($old_hash))" : '').", '$displayname', $type)");
1928 1927
 		$this->_connect($this->account);
1929 1928
 		try
1930 1929
 		{
1931
-			if ($action=='rename')
1930
+			if ($action == 'rename')
1932 1931
 			{
1933 1932
 				$newFolderName = $this->mail->renameFolder($oldFolder, $parentFolder, $displayname);
1934 1933
 			}
1935
-			elseif ($action=='create')
1934
+			elseif ($action == 'create')
1936 1935
 			{
1937
-				$error=null;
1936
+				$error = null;
1938 1937
 				$newFolderName = $this->mail->createFolder($parentFolder, $displayname, $error);
1939 1938
 			}
1940 1939
 		}
@@ -1946,7 +1945,7 @@  discard block
 block discarded – undo
1946 1945
 		$newHash = $this->rename_folder_hash($account, $old_hash, $newFolderName);
1947 1946
 		$newID = $this->createID($account, $newHash);
1948 1947
 
1949
-		ZLog::Write(LOGLEVEL_DEBUG,":{$action}Folder('$id'=>($parentFolder), '$oldid'".($oldid?"=>($oldFolder)":'').", '$displayname' => $newFolderName (ID:$newID))");
1948
+		ZLog::Write(LOGLEVEL_DEBUG, ":{$action}Folder('$id'=>($parentFolder), '$oldid'".($oldid ? "=>($oldFolder)" : '').", '$displayname' => $newFolderName (ID:$newID))");
1950 1949
 		return $this->StatFolder($newID);
1951 1950
 	}
1952 1951
 
@@ -1959,13 +1958,13 @@  discard block
 block discarded – undo
1959 1958
 	 * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
1960 1959
 	 * @return boolean true or false on error
1961 1960
 	 */
1962
-	public function DeleteFolder($id, $parentid=false)
1961
+	public function DeleteFolder($id, $parentid = false)
1963 1962
 	{
1964 1963
 		$account = $parent_id = $app = null;
1965 1964
 		$this->splitID($id, $account, $folder, $app);
1966 1965
 		$old_hash = $this->folder2hash($account, $folder);
1967 1966
 		if ($parentid) $this->splitID($parentid, $account, $parentfolder, $app);
1968
-		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."( '$id (-> $folder)','$parentid ".($parentid?'(->'.$parentfolder.')':'')."') called!");
1967
+		ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."( '$id (-> $folder)','$parentid ".($parentid ? '(->'.$parentfolder.')' : '')."') called!");
1969 1968
 		$ret = $this->mail->deleteFolder($folder);
1970 1969
 		if ($ret) $newHash = $this->rename_folder_hash($account, $old_hash, "##Dele#edFolder#$folder##");
1971 1970
 		return $ret;
@@ -1987,8 +1986,8 @@  discard block
 block discarded – undo
1987 1986
 		$this->_connect($this->account);
1988 1987
 		$account = $folder = null;
1989 1988
 		$this->splitID($folderid, $account, $folder);
1990
-		$rv = $this->mail->flagMessages((($flags->flagstatus == 2) ? "flagged" : "unflagged"), $_messageUID,$folder);
1991
-		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SetFlaggedFlag -> set ".array2string($_messageUID).' in Folder '.$folder." as " . (($flags->flagstatus == 2) ? "flagged" : "unflagged") . "-->". $rv);
1989
+		$rv = $this->mail->flagMessages((($flags->flagstatus == 2) ? "flagged" : "unflagged"), $_messageUID, $folder);
1990
+		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SetFlaggedFlag -> set ".array2string($_messageUID).' in Folder '.$folder." as ".(($flags->flagstatus == 2) ? "flagged" : "unflagged")."-->".$rv);
1992 1991
 
1993 1992
 		return $rv;
1994 1993
 	}
@@ -2002,17 +2001,17 @@  discard block
 block discarded – undo
2002 2001
 	 * @return string
2003 2002
 	 * @throws Api\Exception\WrongParameter
2004 2003
 	 */
2005
-	private function createID($account,$folder,$id=0)
2004
+	private function createID($account, $folder, $id = 0)
2006 2005
 	{
2007 2006
 		if (!is_numeric($folder))
2008 2007
 		{
2009 2008
 			// convert string $folder in numeric id
2010
-			$folder = $this->folder2hash($account,$f=$folder);
2009
+			$folder = $this->folder2hash($account, $f = $folder);
2011 2010
 		}
2012 2011
 
2013 2012
 		$str = $this->backend->createID($account, $folder, $id);
2014 2013
 
2015
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($account,'$f',$id) type=$account, folder=$folder --> '$str'");
2014
+		if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."($account,'$f',$id) type=$account, folder=$folder --> '$str'");
2016 2015
 
2017 2016
 		return $str;
2018 2017
 	}
@@ -2026,14 +2025,14 @@  discard block
 block discarded – undo
2026 2025
 	 * @param int &$appid=null (for mail=mail is to be expected)
2027 2026
 	 * @throws Api\Exception\WrongParameter
2028 2027
 	 */
2029
-	private function splitID($str,&$account,&$folder,&$appid=null)
2028
+	private function splitID($str, &$account, &$folder, &$appid = null)
2030 2029
 	{
2031 2030
 		$this->backend->splitID($str, $account, $folder, $appid);
2032 2031
 
2033 2032
 		// convert numeric folder-id back to folder name
2034
-		$folder = $this->hash2folder($account,$f=$folder);
2033
+		$folder = $this->hash2folder($account, $f = $folder);
2035 2034
 
2036
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."('$str','$account','$folder',$appid)");
2035
+		if ($this->debugLevel > 1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__."('$str','$account','$folder',$appid)");
2037 2036
 	}
2038 2037
 
2039 2038
 	/**
@@ -2050,9 +2049,9 @@  discard block
 block discarded – undo
2050 2049
 	 * @param string $folder
2051 2050
 	 * @return int
2052 2051
 	 */
2053
-	private function folder2hash($account,$folder)
2052
+	private function folder2hash($account, $folder)
2054 2053
 	{
2055
-		if(!isset($this->folderHashes)) $this->readFolderHashes();
2054
+		if (!isset($this->folderHashes)) $this->readFolderHashes();
2056 2055
 
2057 2056
 		if (($index = array_search($folder, (array)$this->folderHashes[$account])) === false)
2058 2057
 		{
@@ -2073,9 +2072,9 @@  discard block
 block discarded – undo
2073 2072
 	 * @param int $index
2074 2073
 	 * @return string NULL if not used so far
2075 2074
 	 */
2076
-	private function hash2folder($account,$index)
2075
+	private function hash2folder($account, $index)
2077 2076
 	{
2078
-		if(!isset($this->folderHashes)) $this->readFolderHashes();
2077
+		if (!isset($this->folderHashes)) $this->readFolderHashes();
2079 2078
 
2080 2079
 		return isset($this->folderHashes[$account]) ? $this->folderHashes[$account][$index] : null;
2081 2080
 	}
@@ -2131,9 +2130,9 @@  discard block
 block discarded – undo
2131 2130
 			if ((file_exists($file = $this->hashFile()) || file_exists($file = $this->hashFile(true))) &&
2132 2131
 				($hashes = file_get_contents($file)))
2133 2132
 			{
2134
-				$this->folderHashes = json_decode($hashes,true);
2133
+				$this->folderHashes = json_decode($hashes, true);
2135 2134
 				// fallback in case hashes have been serialized instead of being json-encoded
2136
-				if (json_last_error()!=JSON_ERROR_NONE)
2135
+				if (json_last_error() != JSON_ERROR_NONE)
2137 2136
 				{
2138 2137
 					//error_log(__METHOD__.__LINE__." error decoding with json");
2139 2138
 					$this->folderHashes = unserialize($hashes);
@@ -2179,9 +2178,9 @@  discard block
 block discarded – undo
2179 2178
 	 * @param boolean $old =false true: return old / pre-15 hash-file
2180 2179
 	 * @throws Api\Exception\AssertionFailed
2181 2180
 	 */
2182
-	private function hashFile($old=false)
2181
+	private function hashFile($old = false)
2183 2182
 	{
2184
-		if (!($dev_id=Request::GetDeviceID()))
2183
+		if (!($dev_id = Request::GetDeviceID()))
2185 2184
 		{
2186 2185
 			throw new Api\Exception\AssertionFailed(__METHOD__."() no DeviceID set!");
2187 2186
 		}
Please login to merge, or discard this patch.
Braces   +605 added lines, -177 removed lines patch added patch discarded remove patch
@@ -84,29 +84,47 @@  discard block
 block discarded – undo
84 84
 	 */
85 85
 	public function __construct(activesync_backend $backend)
86 86
 	{
87
-		if ($GLOBALS['egw_setup']) return;
87
+		if ($GLOBALS['egw_setup'])
88
+		{
89
+			return;
90
+		}
88 91
 
89 92
 		//$this->debugLevel=2;
90 93
 		$this->backend = $backend;
91 94
 		if (!isset($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']))
92 95
 		{
93
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' Noprefs set: using 0 as default');
96
+			if ($this->debugLevel>1)
97
+			{
98
+				error_log(__METHOD__.__LINE__.' Noprefs set: using 0 as default');
99
+			}
94 100
 			// globals preferences add appname varname value
95 101
 			$GLOBALS['egw']->preferences->add('activesync','mail-ActiveSyncProfileID',0,'user');
96 102
 			// save prefs
97 103
 			$GLOBALS['egw']->preferences->save_repository(true);
98 104
 		}
99
-		if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' ActiveProfileID:'.array2string(self::$profileID));
105
+		if ($this->debugLevel>1)
106
+		{
107
+			error_log(__METHOD__.__LINE__.' ActiveProfileID:'.array2string(self::$profileID));
108
+		}
100 109
 
101 110
 		if (is_null(self::$profileID))
102 111
 		{
103
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' self::ProfileID isNUll:'.array2string(self::$profileID));
112
+			if ($this->debugLevel>1)
113
+			{
114
+				error_log(__METHOD__.__LINE__.' self::ProfileID isNUll:'.array2string(self::$profileID));
115
+			}
104 116
 			self::$profileID =& Api\Cache::getSession('mail','activeSyncProfileID');
105
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' ActiveProfileID (after reading Cache):'.array2string(self::$profileID));
117
+			if ($this->debugLevel>1)
118
+			{
119
+				error_log(__METHOD__.__LINE__.' ActiveProfileID (after reading Cache):'.array2string(self::$profileID));
120
+			}
106 121
 		}
107 122
 		if (isset($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']))
108 123
 		{
109
-			if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' Pref for ProfileID:'.array2string($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']));
124
+			if ($this->debugLevel>1)
125
+			{
126
+				error_log(__METHOD__.__LINE__.' Pref for ProfileID:'.array2string($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID']));
127
+			}
110 128
 			if ($GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID'] == 'G')
111 129
 			{
112 130
 				self::$profileID = 'G'; // this should trigger the fetch of the first negative profile (or if no negative profile is available the firstb there is)
@@ -116,7 +134,10 @@  discard block
 block discarded – undo
116 134
 				self::$profileID = (int)$GLOBALS['egw_info']['user']['preferences']['activesync']['mail-ActiveSyncProfileID'];
117 135
 			}
118 136
 		}
119
-		if ($this->debugLevel>1) error_log(__METHOD__.__LINE__.' Profile Selected (after reading Prefs):'.array2string(self::$profileID));
137
+		if ($this->debugLevel>1)
138
+		{
139
+			error_log(__METHOD__.__LINE__.' Profile Selected (after reading Prefs):'.array2string(self::$profileID));
140
+		}
120 141
 
121 142
 		// verify we are on an existing profile, if not running in setup (settings can not be static according to interface!)
122 143
 		if (!isset($GLOBALS['egw_setup']))
@@ -129,7 +150,10 @@  discard block
 block discarded – undo
129 150
 				self::$profileID = Mail\Account::get_default_acc_id();
130 151
 			}
131 152
 		}
132
-		if ($this->debugLevel>0) error_log(__METHOD__.'::'.__LINE__.' ProfileSelected:'.self::$profileID);
153
+		if ($this->debugLevel>0)
154
+		{
155
+			error_log(__METHOD__.'::'.__LINE__.' ProfileSelected:'.self::$profileID);
156
+		}
133 157
 		//$this->debugLevel=0;
134 158
 	}
135 159
 
@@ -245,8 +269,14 @@  discard block
 block discarded – undo
245 269
 				$this->_connect(0,true);
246 270
 				$this->_disconnect();
247 271
 
248
-				if (!$this->_wasteID) $errors[] = lang('No valid %1 folder configured!', '<b>'.lang('trash').'</b>');
249
-				if (!$this->_sentID) $errors[] = lang('No valid %1 folder configured!', '<b>'.lang('send').'</b>');
272
+				if (!$this->_wasteID)
273
+				{
274
+					$errors[] = lang('No valid %1 folder configured!', '<b>'.lang('trash').'</b>');
275
+				}
276
+				if (!$this->_sentID)
277
+				{
278
+					$errors[] = lang('No valid %1 folder configured!', '<b>'.lang('send').'</b>');
279
+				}
250 280
 			}
251 281
 			catch(Exception $e) {
252 282
 				$errors[] = lang('Can not open IMAP connection').': '.$e->getMessage();
@@ -268,8 +298,14 @@  discard block
 block discarded – undo
268 298
 	 */
269 299
 	private function _connect($account=0)
270 300
 	{
271
-		if (!$account) $account = self::$profileID ? self::$profileID : 0;
272
-		if ($this->mail && $this->account != $account) $this->_disconnect();
301
+		if (!$account)
302
+		{
303
+			$account = self::$profileID ? self::$profileID : 0;
304
+		}
305
+		if ($this->mail && $this->account != $account)
306
+		{
307
+			$this->_disconnect();
308
+		}
273 309
 
274 310
 		$this->_wasteID = false;
275 311
 		$this->_sentID = false;
@@ -280,12 +316,18 @@  discard block
 block discarded – undo
280 316
 			// todo: tell mail which account to use
281 317
 			//error_log(__METHOD__.__LINE__.' create object with ProfileID:'.array2string(self::$profileID));
282 318
 			$this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
283
-			if (self::$profileID == 0 && isset($this->mail->icServer->ImapServerId) && !empty($this->mail->icServer->ImapServerId)) self::$profileID = $this->mail->icServer->ImapServerId;
319
+			if (self::$profileID == 0 && isset($this->mail->icServer->ImapServerId) && !empty($this->mail->icServer->ImapServerId))
320
+			{
321
+				self::$profileID = $this->mail->icServer->ImapServerId;
322
+			}
284 323
 		}
285 324
 		else
286 325
 		{
287 326
 			//error_log(__METHOD__.__LINE__." connect with profileID: ".self::$profileID);
288
-			if (self::$profileID == 0 && isset($this->mail->icServer->ImapServerId) && !empty($this->mail->icServer->ImapServerId)) self::$profileID = $this->mail->icServer->ImapServerId;
327
+			if (self::$profileID == 0 && isset($this->mail->icServer->ImapServerId) && !empty($this->mail->icServer->ImapServerId))
328
+			{
329
+				self::$profileID = $this->mail->icServer->ImapServerId;
330
+			}
289 331
 		}
290 332
 		$this->mail->openConnection(self::$profileID,false);
291 333
 
@@ -302,8 +344,14 @@  discard block
 block discarded – undo
302 344
 	 */
303 345
 	private function _disconnect()
304 346
 	{
305
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__);
306
-		if ($this->mail) $this->mail->closeConnection();
347
+		if ($this->debugLevel>0)
348
+		{
349
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__);
350
+		}
351
+		if ($this->mail)
352
+		{
353
+			$this->mail->closeConnection();
354
+		}
307 355
 
308 356
 		unset($this->mail);
309 357
 		unset($this->account);
@@ -318,24 +366,43 @@  discard block
 block discarded – undo
318 366
 	public function GetFolderList()
319 367
 	{
320 368
 		$folderlist = array();
321
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__);
369
+		if ($this->debugLevel>0)
370
+		{
371
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__);
372
+		}
322 373
 		/*foreach($available_accounts as $account)*/ $account = 0;
323 374
 		{
324 375
 			$this->_connect($account);
325
-			if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true,false,$_alwaysGetDefaultFolders=true);
326
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($this->folders));
376
+			if (!isset($this->folders))
377
+			{
378
+				$this->folders = $this->mail->getFolderObjects(true,false,$_alwaysGetDefaultFolders=true);
379
+			}
380
+			if ($this->debugLevel>1)
381
+			{
382
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($this->folders));
383
+			}
327 384
 
328
-			foreach ($this->folders as $folder => $folderObj) {
329
-				if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' folder='.$folder);
385
+			foreach ($this->folders as $folder => $folderObj)
386
+			{
387
+				if ($this->debugLevel>1)
388
+				{
389
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' folder='.$folder);
390
+				}
330 391
 				$folderlist[] = $f = array(
331 392
 					'id'     => $this->createID($account,$folder),
332 393
 					'mod'    => $folderObj->shortDisplayName,
333 394
 					'parent' => $this->getParentID($account,$folder),
334 395
 				);
335
-				if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."() returning ".array2string($f));
396
+				if ($this->debugLevel>1)
397
+				{
398
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."() returning ".array2string($f));
399
+				}
336 400
 			}
337 401
 		}
338
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."() returning ".array2string($folderlist));
402
+		if ($this->debugLevel>0)
403
+		{
404
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."() returning ".array2string($folderlist));
405
+		}
339 406
 
340 407
 		return $folderlist;
341 408
 	}
@@ -396,11 +463,17 @@  discard block
 block discarded – undo
396 463
 		$smartdata_task = ($smartdata->replyflag?'reply':($smartdata->forwardflag?'forward':'new'));
397 464
 
398 465
    		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__ . (isset($smartdata->mime) ? $smartdata->mime : ""). "task: ".(isset($smartdata_task) ? $smartdata_task : "")." itemid: ".(isset($smartdata->source->itemid) ? $smartdata->source->itemid : "")." folder: ".(isset($smartdata->source->folderid) ? $smartdata->source->folderid : ""));
399
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__."): Smartdata = ".array2string($smartdata));
466
+		if ($this->debugLevel>0)
467
+		{
468
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__."): Smartdata = ".array2string($smartdata));
469
+		}
400 470
 		//error_log("IMAP-Sendmail: Smartdata = ".array2string($smartdata));
401 471
 
402 472
 		// initialize our Mail
403
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
473
+		if (!isset($this->mail))
474
+		{
475
+			$this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
476
+		}
404 477
 		$activeMailProfiles = $this->mail->getAccountIdentities(self::$profileID);
405 478
 		// use the standardIdentity
406 479
 		$activeMailProfile = Mail::getStandardIdentityForProfile($activeMailProfiles,self::$profileID);
@@ -428,12 +501,18 @@  discard block
 block discarded – undo
428 501
 		$beforeHtml = ($disableRuler ?'&nbsp;<br>':'&nbsp;<br><hr style="border:dotted 1px silver; width:90%; border:dotted 1px silver;">');
429 502
 		$beforePlain = ($disableRuler ?"\r\n\r\n":"\r\n\r\n-- \r\n");
430 503
 		$sigText = Mail::merge($signature,array($GLOBALS['egw']->accounts->id2name($GLOBALS['egw_info']['user']['account_id'],'person_id')));
431
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Signature to use:'.$sigText);
504
+		if ($this->debugLevel>0)
505
+		{
506
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Signature to use:'.$sigText);
507
+		}
432 508
 		$sigTextHtml = $beforeHtml.$sigText;
433 509
 		$sigTextPlain = $beforePlain.Api\Mail\Html::convertHTMLToText($sigText);
434 510
 
435 511
 		$force8bit=false;
436
-		if (Api\Translation::detect_encoding($sigTextPlain)!='ascii') $force8bit=true;
512
+		if (Api\Translation::detect_encoding($sigTextPlain)!='ascii')
513
+		{
514
+			$force8bit=true;
515
+		}
437 516
 		// initialize the new Api\Mailer object for sending
438 517
 		$mailObject = new Api\Mailer(self::$profileID);
439 518
 		$this->mail->parseRawMessageIntoMailObject($mailObject,$smartdata->mime,$force8bit);
@@ -444,22 +523,34 @@  discard block
 block discarded – undo
444 523
 
445 524
 		// prepare addressee list; moved the adding of addresses to the mailobject down
446 525
 		// to
447
-		foreach(Mail::parseAddressList($mailObject->getHeader("To")) as $addressObject) {
448
-			if (!$addressObject->valid) continue;
526
+		foreach(Mail::parseAddressList($mailObject->getHeader("To")) as $addressObject)
527
+		{
528
+			if (!$addressObject->valid)
529
+			{
530
+				continue;
531
+			}
449 532
 			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") Header Sentmail To: ".array2string($addressObject) );
450 533
 			//$mailObject->AddAddress($addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : ''),$addressObject->personal);
451 534
 			$toMailAddr[] = imap_rfc822_write_address($addressObject->mailbox, $addressObject->host, $addressObject->personal);
452 535
 		}
453 536
 		// CC
454
-		foreach(Mail::parseAddressList($mailObject->getHeader("Cc")) as $addressObject) {
455
-			if (!$addressObject->valid) continue;
537
+		foreach(Mail::parseAddressList($mailObject->getHeader("Cc")) as $addressObject)
538
+		{
539
+			if (!$addressObject->valid)
540
+			{
541
+				continue;
542
+			}
456 543
 			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") Header Sentmail CC: ".array2string($addressObject) );
457 544
 			//$mailObject->AddCC($addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : ''),$addressObject->personal);
458 545
 			$ccMailAddr[] = imap_rfc822_write_address($addressObject->mailbox, $addressObject->host, $addressObject->personal);
459 546
 		}
460 547
 		// BCC
461
-		foreach($mailObject->getAddresses('bcc') as $addressObject) {
462
-			if (!$addressObject->valid) continue;
548
+		foreach($mailObject->getAddresses('bcc') as $addressObject)
549
+		{
550
+			if (!$addressObject->valid)
551
+			{
552
+				continue;
553
+			}
463 554
 			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") Header Sentmail BCC: ".array2string($addressObject) );
464 555
 			//$mailObject->AddBCC($addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : ''),$addressObject->personal);
465 556
 			$bccMailAddr[] = imap_rfc822_write_address($addressObject->mailbox, $addressObject->host, $addressObject->personal);
@@ -472,12 +563,14 @@  discard block
 block discarded – undo
472 563
 		$ContentType =$mailObject->getHeader('Content-Type');
473 564
 		//error_log(__METHOD__.__LINE__." Header Sentmail original Header (filtered): " . $k.  " = ".trim($ContentType));
474 565
 		// if the message is a multipart message, then we should use the sent body
475
-		if (preg_match("/multipart/i", $ContentType)) {
566
+		if (preg_match("/multipart/i", $ContentType))
567
+		{
476 568
 			$use_orgbody = true;
477 569
 		}
478 570
 
479 571
 		// save the original content-type header for the body part when forwarding
480
-		if ($smartdata_task == 'forward' && $smartdata->source->itemid && !$use_orgbody) {
572
+		if ($smartdata_task == 'forward' && $smartdata->source->itemid && !$use_orgbody)
573
+		{
481 574
 			//continue; // ignore
482 575
 		}
483 576
 		// horde/egw_ mailer does everything as utf-8, the following should not be needed
@@ -486,7 +579,8 @@  discard block
 block discarded – undo
486 579
 		// if the message is a multipart message, then we should use the sent body
487 580
 		if (($smartdata_task == 'new' || $smartdata_task == 'reply' || $smartdata_task == 'forward') &&
488 581
 			((isset($smartdata->replacemime) && $smartdata->replacemime == true) ||
489
-			$k == "Content-Type" && preg_match("/multipart/i", $ContentType))) {
582
+			$k == "Content-Type" && preg_match("/multipart/i", $ContentType)))
583
+		{
490 584
 			$use_orgbody = true;
491 585
 		}
492 586
 		$Body =  $AltBody = "";
@@ -519,12 +613,19 @@  discard block
 block discarded – undo
519 613
 			$AltBody = preg_replace("/(<|&lt;)*(([\w\.,-.,_.,0-9.]+)@([\w\.,-.,_.,0-9.]+))(>|&gt;)*/i","[$2]",
520 614
 				($html_body = $mailObject->findBody('html')) ? $html_body->getContents() : null);
521 615
 		}
522
-		if ($this->debugLevel>1 && $Body) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched Body as with MessageContentType:". $ContentType.'=>'.$Body);
523
-		if ($this->debugLevel>1 && $AltBody) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched AltBody as with MessageContentType:". $ContentType.'=>'.$AltBody);
616
+		if ($this->debugLevel>1 && $Body)
617
+		{
618
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched Body as with MessageContentType:". $ContentType.'=>'.$Body);
619
+		}
620
+		if ($this->debugLevel>1 && $AltBody)
621
+		{
622
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") fetched AltBody as with MessageContentType:". $ContentType.'=>'.$AltBody);
623
+		}
524 624
 		//error_log(__METHOD__.__LINE__.array2string($mailObject));
525 625
 		// if this is a multipart message with a boundary, we must use the original body
526 626
 		//if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' mailObject after Inital Parse:'.array2string($mailObject));
527
-        if ($use_orgbody) {
627
+        if ($use_orgbody)
628
+        {
528 629
     	    ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") use_orgbody = true ContentType:".$ContentType);
529 630
  			// if it is a ClientSideMeetingRequest, we report it as send at all times
530 631
 			if (($cal_body = $mailObject->findBody('calendar')) &&
@@ -534,15 +635,20 @@  discard block
 block discarded – undo
534 635
 				{
535 636
 					$organizer = calendar_ical::getIcalOrganizer($cal_body->getContents());
536 637
 				}
537
-				if ($this->debugLevel) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") we have a Client Side Meeting Request from organizer=$organizer");
638
+				if ($this->debugLevel)
639
+				{
640
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") we have a Client Side Meeting Request from organizer=$organizer");
641
+				}
538 642
 				$ClientSideMeetingRequest = true;
539 643
 			}
540 644
         }
541 645
 		// now handle the addressee list
542 646
 		$toCount = 0;
543 647
 		//error_log(__METHOD__.__LINE__.array2string($toMailAddr));
544
-		foreach((array)$toMailAddr as $address) {
545
-			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
648
+		foreach((array)$toMailAddr as $address)
649
+		{
650
+			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject)
651
+			{
546 652
 				$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
547 653
 				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' &&
548 654
 					calendar_boupdate::email_update_requested($emailAddress, isset($cSMRMethod) ? $cSMRMethod : 'REQUEST',
@@ -556,19 +662,29 @@  discard block
 block discarded – undo
556 662
 			}
557 663
 		}
558 664
 		$ccCount = 0;
559
-		foreach((array)$ccMailAddr as $address) {
560
-			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
665
+		foreach((array)$ccMailAddr as $address)
666
+		{
667
+			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject)
668
+			{
561 669
 				$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
562
-				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' && calendar_boupdate::email_update_requested($emailAddress)) continue;
670
+				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' && calendar_boupdate::email_update_requested($emailAddress))
671
+				{
672
+					continue;
673
+				}
563 674
 				$mailObject->AddCC($emailAddress, $addressObject->personal);
564 675
 				$ccCount++;
565 676
 			}
566 677
 		}
567 678
 		$bccCount = 0;
568
-		foreach((array)$bccMailAddr as $address) {
569
-			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
679
+		foreach((array)$bccMailAddr as $address)
680
+		{
681
+			foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject)
682
+			{
570 683
 				$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
571
-				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' && calendar_boupdate::email_update_requested($emailAddress)) continue;
684
+				if ($ClientSideMeetingRequest === true && $allowSendingInvitations == 'sendifnocalnotif' && calendar_boupdate::email_update_requested($emailAddress))
685
+				{
686
+					continue;
687
+				}
572 688
 				$mailObject->AddBCC($emailAddress, $addressObject->personal);
573 689
 				$bccCount++;
574 690
 			}
@@ -578,7 +694,10 @@  discard block
 block discarded – undo
578 694
 		{
579 695
 			return $ClientSideMeetingRequest && $allowSendingInvitations === 'sendifnocalnotif' && $organizer ? true : 0; // noone to send mail to
580 696
 		}
581
-		if ($ClientSideMeetingRequest === true && $allowSendingInvitations===false) return true;
697
+		if ($ClientSideMeetingRequest === true && $allowSendingInvitations===false)
698
+		{
699
+			return true;
700
+		}
582 701
 		// as we use our mailer (horde mailer) it is detecting / setting the mimetype by itself while creating the mail
583 702
 /*
584 703
 		if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' retrieved Body:'.$body);
@@ -601,10 +720,17 @@  discard block
 block discarded – undo
601 720
 			$this->mail->reopen($folder);
602 721
 			$bodyStruct = $this->mail->getMessageBody($uid, 'html_only');
603 722
 			$bodyBUFFHtml = $this->mail->getdisplayableBody($this->mail,$bodyStruct,true,false);
604
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
605
-		    if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html')) {
723
+			if ($this->debugLevel>3)
724
+			{
725
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
726
+			}
727
+		    if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html'))
728
+		    {
606 729
 				// may be html
607
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
730
+				if ($this->debugLevel>0)
731
+				{
732
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
733
+				}
608 734
 				$AltBody = $AltBody."</br>".$bodyBUFFHtml.$sigTextHtml;
609 735
 				$isreply = true;
610 736
 			}
@@ -613,8 +739,12 @@  discard block
 block discarded – undo
613 739
 			// if the new part of the message is html, we must preserve it, and handle that the original mail is text/plain
614 740
 			$bodyStruct = $this->mail->getMessageBody($uid,'never_display');//'never_display');
615 741
 			$bodyBUFF = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
616
-			if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/plain')) {
617
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
742
+			if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/plain'))
743
+			{
744
+				if ($this->debugLevel>0)
745
+				{
746
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
747
+				}
618 748
 				$Body = $Body."\r\n".$bodyBUFF.$sigTextPlain;
619 749
 				$isreply = true;
620 750
 			}
@@ -622,7 +752,10 @@  discard block
 block discarded – undo
622 752
 			{
623 753
 				$isreply = true;
624 754
 				$AltBody = $AltBody."</br><pre>".nl2br($bodyBUFF).'</pre>'.$sigTextHtml;
625
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." no Api\Html Body found use modified plaintext body for txt/html: ".$AltBody);
755
+				if ($this->debugLevel>0)
756
+				{
757
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." no Api\Html Body found use modified plaintext body for txt/html: ".$AltBody);
758
+				}
626 759
 			}
627 760
 		}
628 761
 
@@ -636,11 +769,17 @@  discard block
 block discarded – undo
636 769
 			(isset($smartdata->replacemime) && $smartdata->replacemime == false)))
637 770
 		{
638 771
 			//force the default for the forwarding -> asmail
639
-			if (is_array($preferencesArray)) {
772
+			if (is_array($preferencesArray))
773
+			{
640 774
 				if (!array_key_exists('message_forwarding',$preferencesArray)
641 775
 					|| !isset($preferencesArray['message_forwarding'])
642
-					|| empty($preferencesArray['message_forwarding'])) $preferencesArray['message_forwarding'] = 'asmail';
643
-			} else {
776
+					|| empty($preferencesArray['message_forwarding']))
777
+				{
778
+					$preferencesArray['message_forwarding'] = 'asmail';
779
+				}
780
+			}
781
+			else
782
+			{
644 783
 				$preferencesArray['message_forwarding'] = 'asmail';
645 784
 			}
646 785
 			// construct the uid of the message out of the itemid - seems to be the uid, no construction needed
@@ -672,27 +811,44 @@  discard block
 block discarded – undo
672 811
 				$this->mail->reopen($folder);
673 812
 				$bodyStruct = $this->mail->getMessageBody($uid, 'html_only');
674 813
 				$bodyBUFFHtml = $this->mail->getdisplayableBody($this->mail,$bodyStruct,true,false);
675
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
676
-				if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html')) {
814
+				if ($this->debugLevel>0)
815
+				{
816
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$bodyBUFFHtml);
817
+				}
818
+				if ($bodyBUFFHtml != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html'))
819
+				{
677 820
 					// may be html
678
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
821
+					if ($this->debugLevel>0)
822
+					{
823
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:html (fetched with html_only):'.$bodyBUFFHtml);
824
+					}
679 825
 					$AltBody = $AltBody."</br>".$bodyBUFFHtml.$sigTextHtml;
680 826
 					$isforward = true;
681 827
 				}
682 828
 				// plain text Message part
683
-				if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain, fetch text:');
829
+				if ($this->debugLevel>0)
830
+				{
831
+					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain, fetch text:');
832
+				}
684 833
 				// if the new part of the message is html, we must preserve it, and handle that the original mail is text/plain
685 834
 				$bodyStruct = $this->mail->getMessageBody($uid,'never_display');//'never_display');
686 835
 				$bodyBUFF = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
687
-				if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/plain')) {
688
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
836
+				if ($bodyBUFF != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/plain'))
837
+				{
838
+					if ($this->debugLevel>0)
839
+					{
840
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__.") MIME Body".' Type:plain (fetched with never_display):'.$bodyBUFF);
841
+					}
689 842
 					$Body = $Body."\r\n".$bodyBUFF.$sigTextPlain;
690 843
 					$isforward = true;
691 844
 				}
692 845
 				if (!empty($bodyBUFF) && empty($bodyBUFFHtml) && !empty($AltBody))
693 846
 				{
694 847
 					$AltBody = $AltBody."</br><pre>".nl2br($bodyBUFF).'</pre>'.$sigTextHtml;
695
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." no html Body found use modified plaintext body for txt/html: ".$AltBody);
848
+					if ($this->debugLevel>0)
849
+					{
850
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." no html Body found use modified plaintext body for txt/html: ".$AltBody);
851
+					}
696 852
 					$isforward = true;
697 853
 				}
698 854
 				// get all the attachments and add them too.
@@ -705,7 +861,10 @@  discard block
 block discarded – undo
705 861
 					ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' gather Attachments for BodyCreation of/for MessageID:'.$uid.' found:'.count($attachments));
706 862
 					foreach((array)$attachments as $key => $attachment)
707 863
 					{
708
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attachment));
864
+						if ($this->debugLevel>0)
865
+						{
866
+							ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attachment));
867
+						}
709 868
 						$attachmentNames .= $attachment['name']."\n";
710 869
 						$attachmentData	= $this->mail->getAttachment($uid, $attachment['partID'],0,false,false,$folder);
711 870
 						/*$x =*/ $mailObject->AddStringAttachment($attachmentData['attachment'], $attachment['name'], $attachment['mimeType']);
@@ -724,20 +883,29 @@  discard block
 block discarded – undo
724 883
 		// now set the body
725 884
 		if ($AltBody && ($html_body = $mailObject->findBody('html')))
726 885
 		{
727
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> '.$AltBody);
886
+			if ($this->debugLevel>1)
887
+			{
888
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> '.$AltBody);
889
+			}
728 890
 			//error_log(__METHOD__.__LINE__.' html:'.$AltBody);
729 891
 			$html_body->setContents($AltBody,array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
730 892
 		}
731 893
 		if ($Body && ($text_body = $mailObject->findBody('plain')))
732 894
 		{
733
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> '.$Body);
895
+			if ($this->debugLevel>1)
896
+			{
897
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' -> '.$Body);
898
+			}
734 899
 			//error_log(__METHOD__.__LINE__.' text:'.$Body);
735 900
 			$text_body->setContents($Body,array('encoding'=>Horde_Mime_Part::DEFAULT_ENCODING));
736 901
 		}
737 902
 		//advanced debugging
738 903
 		// Horde SMTP Class uses utf-8 by default.
739 904
         //ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SendMail: parsed message: ". print_r($message,1));
740
-		if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__."): MailObject:".array2string($mailObject));
905
+		if ($this->debugLevel>2)
906
+		{
907
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."(".__LINE__."): MailObject:".array2string($mailObject));
908
+		}
741 909
 
742 910
 		// set a higher timeout for big messages
743 911
 		@set_time_limit(120);
@@ -764,7 +932,9 @@  discard block
 block discarded – undo
764 932
 			if ($this->mail->isDraftFolder($folder) && !$this->mail->isTemplateFolder($folder))
765 933
 			{
766 934
 				$this->mail->deleteMessages(array($uid),$folder);
767
-			} else {
935
+			}
936
+			else
937
+			{
768 938
 				$this->mail->flagMessages("answered", array($uid),$folder);
769 939
 				if ($smartdata_task== "forward")
770 940
 				{
@@ -778,7 +948,8 @@  discard block
 block discarded – undo
778 948
 		{
779 949
 			$asf = false;
780 950
 			$sentFolder = $this->mail->getSentFolder();
781
-			if ($this->_sentID) {
951
+			if ($this->_sentID)
952
+			{
782 953
 				$folderArray[] = $this->_sentID;
783 954
 			}
784 955
 			else if(isset($sentFolder) && $sentFolder != 'none')
@@ -792,28 +963,41 @@  discard block
 block discarded – undo
792 963
 				// we dont try guessing
793 964
 				$asf = true;
794 965
 			}
795
-			if (count($folderArray) > 0) {
796
-				foreach((array)$bccMailAddr as $address) {
797
-					foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject) {
966
+			if (count($folderArray) > 0)
967
+			{
968
+				foreach((array)$bccMailAddr as $address)
969
+				{
970
+					foreach(Mail::parseAddressList((get_magic_quotes_gpc()?stripslashes($address):$address)) as $addressObject)
971
+					{
798 972
 						$emailAddress = $addressObject->mailbox. ($addressObject->host ? '@'.$addressObject->host : '');
799 973
 						$mailAddr[] = array($emailAddress, $addressObject->personal);
800 974
 					}
801 975
 				}
802 976
 				//$BCCmail='';
803
-				if (count($mailAddr)>0) $mailObject->forceBccHeader();
977
+				if (count($mailAddr)>0)
978
+				{
979
+					$mailObject->forceBccHeader();
980
+				}
804 981
 				//$BCCmail = $mailObject->AddrAppend("Bcc",$mailAddr);
805
-				foreach($folderArray as $folderName) {
806
-					if($this->mail->isSentFolder($folderName)) {
982
+				foreach($folderArray as $folderName)
983
+				{
984
+					if($this->mail->isSentFolder($folderName))
985
+					{
807 986
 						$flags = '\\Seen';
808
-					} elseif($this->mail->isDraftFolder($folderName)) {
987
+					}
988
+					elseif($this->mail->isDraftFolder($folderName))
989
+					{
809 990
 						$flags = '\\Draft';
810
-					} else {
991
+					}
992
+					else
993
+					{
811 994
 						$flags = '';
812 995
 					}
813 996
 					$asf = true;
814 997
 					//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.'->'.array2string($this->mail->icServer));
815 998
 					$this->mail->openConnection(self::$profileID,false);
816
-					if ($this->mail->folderExists($folderName)) {
999
+					if ($this->mail->folderExists($folderName))
1000
+					{
817 1001
 						try
818 1002
 						{
819 1003
 							$this->mail->appendMessage($folderName,$mailObject->getRaw(), null,
@@ -871,17 +1055,26 @@  discard block
 block discarded – undo
871 1055
 		$bodypreference = $contentparameters->GetBodyPreference(); /* fmbiete's contribution r1528, ZP-320 */
872 1056
 
873 1057
 		// fix for z-push bug returning additional bodypreference type 4, even if only 1 is requested and mimessupport = 0
874
-		if (!$mimesupport && ($key = array_search('4', $bodypreference))) unset($bodypreference[$key]);
1058
+		if (!$mimesupport && ($key = array_search('4', $bodypreference)))
1059
+		{
1060
+			unset($bodypreference[$key]);
1061
+		}
875 1062
 
876 1063
 		//$this->debugLevel=4;
877
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1064
+		if (!isset($this->mail))
1065
+		{
1066
+			$this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1067
+		}
878 1068
 		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' FolderID:'.$folderid.' ID:'.$id.' TruncSize:'.$truncsize.' Bodypreference: '.array2string($bodypreference));
879 1069
 		$account = $_folderName = $xid = null;
880 1070
 		$this->splitID($folderid,$account,$_folderName,$xid);
881 1071
 		$this->mail->reopen($_folderName);
882 1072
 		$messages = $this->fetchMessages($folderid, NULL, $id, true);	// true: return all headers
883 1073
 		$headers = $messages[$id];
884
-		if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($headers));
1074
+		if ($this->debugLevel>3)
1075
+		{
1076
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($headers));
1077
+		}
885 1078
 		// StatMessage should reopen the folder in question, so we dont need folderids in the following statements.
886 1079
 		if ($headers)
887 1080
 		{
@@ -891,16 +1084,25 @@  discard block
 block discarded – undo
891 1084
 			//$rawHeaders = $this->mail->getMessageRawHeader($id);
892 1085
 			// simple style
893 1086
 			// start AS12 Stuff (bodypreference === false) case = old behaviour
894
-			if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__. ' for message with ID:'.$id.' with headers:'.array2string($headers));
1087
+			if ($this->debugLevel>0)
1088
+			{
1089
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__. ' for message with ID:'.$id.' with headers:'.array2string($headers));
1090
+			}
895 1091
 
896
-			if ($bodypreference === false) {
1092
+			if ($bodypreference === false)
1093
+			{
897 1094
 				$bodyStruct = $this->mail->getMessageBody($id, 'only_if_no_text', '', null, true,$_folderName);
898 1095
 				$raw_body = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
899 1096
 				//$body = html_entity_decode($body,ENT_QUOTES,$this->mail->detect_encoding($body));
900
-				if (stripos($raw_body,'<style')!==false) $body = preg_replace("/<style.*?<\/style>/is", "", $raw_body); // in case there is only a html part
1097
+				if (stripos($raw_body,'<style')!==false)
1098
+				{
1099
+					$body = preg_replace("/<style.*?<\/style>/is", "", $raw_body);
1100
+				}
1101
+				// in case there is only a html part
901 1102
 				// remove all other html
902 1103
 				$body = strip_tags($raw_body);
903
-				if(strlen($body) > $truncsize) {
1104
+				if(strlen($body) > $truncsize)
1105
+				{
904 1106
 					$body = Utils::Utf8_truncate($body, $truncsize);
905 1107
 					$output->bodytruncated = 1;
906 1108
 				}
@@ -915,7 +1117,8 @@  discard block
 block discarded – undo
915 1117
 			{
916 1118
 				//Select body type preference
917 1119
 				$bpReturnType = 1;//SYNC_BODYPREFERENCE_PLAIN;
918
-				if ($bodypreference !== false) {
1120
+				if ($bodypreference !== false)
1121
+				{
919 1122
 					// bodypreference can occur multiple times
920 1123
 					// usually we would use Utils::GetBodyPreferenceBestMatch($bodypreference);
921 1124
 					$bpReturnType = Utils::GetBodyPreferenceBestMatch($bodypreference);
@@ -949,25 +1152,49 @@  discard block
 block discarded – undo
949 1152
 					// fetch the body (try to gather data only once)
950 1153
 					$css ='';
951 1154
 					$bodyStruct = $this->mail->getMessageBody($id, 'html_only', '', null, true,$_folderName);
952
-					if ($this->debugLevel>2) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only Struct:'.array2string($bodyStruct));
1155
+					if ($this->debugLevel>2)
1156
+					{
1157
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only Struct:'.array2string($bodyStruct));
1158
+					}
953 1159
 					$body = $this->mail->getdisplayableBody($this->mail,$bodyStruct,true,false);
954
-					if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$body);
955
-					if ($body != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html')) {
1160
+					if ($this->debugLevel>3)
1161
+					{
1162
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' html_only:'.$body);
1163
+					}
1164
+					if ($body != "" && (is_array($bodyStruct) && $bodyStruct[0]['mimeType']=='text/html'))
1165
+					{
956 1166
 						// may be html
957
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:html (fetched with html_only)');
1167
+						if ($this->debugLevel>0)
1168
+						{
1169
+							ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:html (fetched with html_only)');
1170
+						}
958 1171
 						$css = $this->mail->getStyles($bodyStruct);
959 1172
 						$output->nativebodytype=2;
960
-					} else {
1173
+					}
1174
+					else
1175
+					{
961 1176
 						// plain text Message
962
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:plain, fetch text (HTML, if no text available)');
1177
+						if ($this->debugLevel>0)
1178
+						{
1179
+							ZLog::Write(LOGLEVEL_DEBUG, "MIME Body".' Type:plain, fetch text (HTML, if no text available)');
1180
+						}
963 1181
 						$output->nativebodytype=1;
964 1182
 						$bodyStruct = $this->mail->getMessageBody($id,'never_display', '', null, true,$_folderName); //'only_if_no_text');
965
-						if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' plain text Struct:'.array2string($bodyStruct));
1183
+						if ($this->debugLevel>3)
1184
+						{
1185
+							ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' plain text Struct:'.array2string($bodyStruct));
1186
+						}
966 1187
 						$body = $this->mail->getdisplayableBody($this->mail,$bodyStruct,false,false);
967
-						if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' never display html(plain text only):'.$body);
1188
+						if ($this->debugLevel>3)
1189
+						{
1190
+							ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' never display html(plain text only):'.$body);
1191
+						}
968 1192
 					}
969 1193
 					// whatever format decode (using the correct encoding)
970
-					if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__."MIME Body".' Type:'.($output->nativebodytype==2?' html ':' plain ').$body);
1194
+					if ($this->debugLevel>3)
1195
+					{
1196
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__."MIME Body".' Type:'.($output->nativebodytype==2?' html ':' plain ').$body);
1197
+					}
971 1198
 					//$body = html_entity_decode($body,ENT_QUOTES,$this->mail->detect_encoding($body));
972 1199
 					// prepare plaintextbody
973 1200
 					$plainBody='';
@@ -988,12 +1215,18 @@  discard block
 block discarded – undo
988 1215
 					// remove all other html
989 1216
 					$plainBody = preg_replace("/<br.*>/is","\r\n",$plainBody);
990 1217
 					$plainBody = strip_tags($plainBody);
991
-					if ($this->debugLevel>3 && $output->nativebodytype==1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Plain Text:'.$plainBody);
1218
+					if ($this->debugLevel>3 && $output->nativebodytype==1)
1219
+					{
1220
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Plain Text:'.$plainBody);
1221
+					}
992 1222
 					//$body = str_replace("\n","\r\n", str_replace("\r","",$body)); // do we need that?
993 1223
 
994
-					if ($bpReturnType==2) //SYNC_BODYPREFERENCE_HTML
1224
+					if ($bpReturnType==2)
1225
+					{
1226
+						//SYNC_BODYPREFERENCE_HTML
995 1227
 					{
996 1228
 						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "HTML Body with requested pref 2");
1229
+					}
997 1230
 						// Send HTML if requested and native type was html
998 1231
 						$output->asbody->type = 2;
999 1232
 						$htmlbody = '<html>'.
@@ -1005,7 +1238,10 @@  discard block
 block discarded – undo
1005 1238
 							'<body>';
1006 1239
 						if ($output->nativebodytype==2)
1007 1240
 						{
1008
-							if ($css) Api\Mail\Html::replaceTagsCompletley($body,'style');
1241
+							if ($css)
1242
+							{
1243
+								Api\Mail\Html::replaceTagsCompletley($body,'style');
1244
+							}
1009 1245
 							// as we fetch html, and body is HTML, we may not need to handle this
1010 1246
 							$htmlbody .= $body;
1011 1247
 						}
@@ -1030,7 +1266,10 @@  discard block
 block discarded – undo
1030 1266
 					else
1031 1267
 					{
1032 1268
 						// Send Plaintext as Fallback or if original body is plainttext
1033
-						if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG, "Plaintext Body:".$plainBody);
1269
+						if ($this->debugLevel>0)
1270
+						{
1271
+							ZLog::Write(LOGLEVEL_DEBUG, "Plaintext Body:".$plainBody);
1272
+						}
1034 1273
 						/* we use plainBody (set above) instead
1035 1274
 						$bodyStruct = $this->mail->getMessageBody($id,'only_if_no_text'); //'never_display');
1036 1275
 						$plain = $this->mail->getdisplayableBody($this->mail,$bodyStruct);
@@ -1067,7 +1306,9 @@  discard block
 block discarded – undo
1067 1306
 			{
1068 1307
 				$output->flag->flagstatus = 2;
1069 1308
 				//$output->flag->flagtype = "Flag for Follow up";
1070
-			} else {
1309
+			}
1310
+			else
1311
+			{
1071 1312
 				$output->flag->flagstatus = 0;
1072 1313
 			}
1073 1314
 			if ($headers['answered'])
@@ -1083,10 +1324,20 @@  discard block
 block discarded – undo
1083 1324
 				($headers['priority'] < 3 ? 2 : 1) ;
1084 1325
 			$output->datereceived = $this->mail->_strtotime($headers['date'],'ts',true);
1085 1326
 			$output->to = $headers['to_address'];
1086
-			if ($headers['to']) $output->displayto = $headers['to_address']; //$headers['FETCHED_HEADER']['to_name']
1327
+			if ($headers['to'])
1328
+			{
1329
+				$output->displayto = $headers['to_address'];
1330
+			}
1331
+			//$headers['FETCHED_HEADER']['to_name']
1087 1332
 			$output->from = $headers['sender_address'];
1088
-			if (isset($headers['cc_addresses']) && $headers['cc_addresses']) $output->cc = $headers['cc_addresses'];
1089
-			if (isset($headers['reply_to_address']) && $headers['reply_to_address']) $output->reply_to = $headers['reply_to_address'];
1333
+			if (isset($headers['cc_addresses']) && $headers['cc_addresses'])
1334
+			{
1335
+				$output->cc = $headers['cc_addresses'];
1336
+			}
1337
+			if (isset($headers['reply_to_address']) && $headers['reply_to_address'])
1338
+			{
1339
+				$output->reply_to = $headers['reply_to_address'];
1340
+			}
1090 1341
 
1091 1342
 			$output->messageclass = "IPM.Note";
1092 1343
 			if (stripos($headers['mimetype'],'multipart')!== false &&
@@ -1094,7 +1345,8 @@  discard block
 block discarded – undo
1094 1345
 			{
1095 1346
 				$output->messageclass = "IPM.Note.SMIME.MultipartSigned";
1096 1347
 			}
1097
-			if (Request::GetProtocolVersion() >= 12.0) {
1348
+			if (Request::GetProtocolVersion() >= 12.0)
1349
+			{
1098 1350
 				$output->contentclass = "urn:content-classes:message";
1099 1351
 			}
1100 1352
 
@@ -1107,7 +1359,10 @@  discard block
 block discarded – undo
1107 1359
 				//error_log(__METHOD__.__LINE__.array2string($attachments));
1108 1360
 				foreach ($attachments as $key => $attach)
1109 1361
 				{
1110
-					if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attach));
1362
+					if ($this->debugLevel>0)
1363
+					{
1364
+						ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Key:'.$key.'->'.array2string($attach));
1365
+					}
1111 1366
 
1112 1367
 					// pass meeting requests to calendar plugin
1113 1368
 					if (strtolower($attach['mimeType']) == 'text/calendar' && strtolower($attach['method']) == 'request' &&
@@ -1124,17 +1379,24 @@  discard block
 block discarded – undo
1124 1379
 						unset($attachment);
1125 1380
 						continue;	// do NOT add attachment as attachment
1126 1381
 					}
1127
-					if (Request::GetProtocolVersion() >= 12.0) {
1382
+					if (Request::GetProtocolVersion() >= 12.0)
1383
+					{
1128 1384
 						$attachment = new SyncBaseAttachment();
1129 1385
 						if (!isset($output->asattachments) || !is_array($output->asattachments))
1130
-							$output->asattachments = array();
1386
+						{
1387
+													$output->asattachments = array();
1388
+						}
1131 1389
 						$attachment->estimatedDataSize = $attach['size'];
1132 1390
 						$attachment->method = 1;
1133 1391
 						$attachment->filereference = $folderid . ":" . $id . ":" . $attach['partID'];
1134
-					} else {
1392
+					}
1393
+					else
1394
+					{
1135 1395
 						$attachment = new SyncAttachment();
1136 1396
 						if (!isset($output->attachments) || !is_array($output->attachments))
1137
-							$output->attachments = array();
1397
+						{
1398
+													$output->attachments = array();
1399
+						}
1138 1400
 						$attachment->attsize = $attach['size'];
1139 1401
 						$attachment->attmethod = 1;
1140 1402
 						$attachment->attname = $folderid . ":" . $id . ":" . $attach['partID'];//$key;
@@ -1151,10 +1413,13 @@  discard block
 block discarded – undo
1151 1413
 						{
1152 1414
 							$attachment->isinline = true;
1153 1415
 						}
1154
-						if (Request::GetProtocolVersion() >= 12.0) {
1416
+						if (Request::GetProtocolVersion() >= 12.0)
1417
+						{
1155 1418
 							$attachment->method=1;
1156 1419
 							$attachment->contentid= str_replace(array("<",">"), "",$attach['cid']);
1157
-						} else {
1420
+						}
1421
+						else
1422
+						{
1158 1423
 							$attachment->attmethod=6;
1159 1424
 							$attachment->attoid = str_replace(array("<",">"), "",$attach['cid']);
1160 1425
 						}
@@ -1162,9 +1427,12 @@  discard block
 block discarded – undo
1162 1427
 						$attachment->contenttype = trim($attach['mimeType']);
1163 1428
 						//	ZLog::Write(LOGLEVEL_DEBUG, "'".$part->headers['content-type']."'  ".$attachment->contentid);
1164 1429
 					}
1165
-					if (Request::GetProtocolVersion() >= 12.0) {
1430
+					if (Request::GetProtocolVersion() >= 12.0)
1431
+					{
1166 1432
 						array_push($output->asattachments, $attachment);
1167
-					} else {
1433
+					}
1434
+					else
1435
+					{
1168 1436
 						array_push($output->attachments, $attachment);
1169 1437
 					}
1170 1438
 					unset($attachment);
@@ -1177,8 +1445,11 @@  discard block
 block discarded – undo
1177 1445
             // Language Code Page ID: http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756%28v=vs.85%29.aspx
1178 1446
             $output->internetcpid = INTERNET_CPID_UTF8;
1179 1447
 
1180
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($output));
1181
-//$this->debugLevel=0;
1448
+			if ($this->debugLevel>3)
1449
+			{
1450
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($output));
1451
+			}
1452
+			//$this->debugLevel=0;
1182 1453
 			return $output;
1183 1454
 		}
1184 1455
 //$this->debugLevel=0;
@@ -1237,7 +1508,8 @@  discard block
 block discarded – undo
1237 1508
      * @param string $attname - should contain (folder)id
1238 1509
 	 * @return SyncItemOperationsAttachment-object
1239 1510
 	 */
1240
-	function GetAttachmentData($fid,$attname) {
1511
+	function GetAttachmentData($fid,$attname)
1512
+	{
1241 1513
 		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": $fid (attname: '$attname')");
1242 1514
 		return $this->_GetAttachmentData($fid,$attname);
1243 1515
 	}
@@ -1252,7 +1524,8 @@  discard block
 block discarded – undo
1252 1524
      * @param string $attname - should contain (folder)id
1253 1525
 	 * @return SyncItemOperationsAttachment-object
1254 1526
 	 */
1255
-	function ItemOperationsGetAttachmentData($fid,$attname) {
1527
+	function ItemOperationsGetAttachmentData($fid,$attname)
1528
+	{
1256 1529
 		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": $fid (attname: '$attname')");
1257 1530
 		return $this->_GetAttachmentData($fid,$attname);
1258 1531
 	}
@@ -1274,7 +1547,10 @@  discard block
 block discarded – undo
1274 1547
 
1275 1548
 		$this->splitID($folderid, $account, $folder);
1276 1549
 
1277
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1550
+		if (!isset($this->mail))
1551
+		{
1552
+			$this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1553
+		}
1278 1554
 
1279 1555
 		$this->mail->reopen($folder);
1280 1556
 		$attachment = $this->mail->getAttachment($id,$part,0,false,true,$folder);
@@ -1283,7 +1559,9 @@  discard block
 block discarded – undo
1283 1559
 		$SIOattachment->data = $attachment['attachment'];
1284 1560
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.": $fid (attname: '$attname') Data:".$attachment['attachment']);
1285 1561
 		if (isset($attachment['type']) )
1286
-			$SIOattachment->contenttype = $attachment['type'];
1562
+		{
1563
+					$SIOattachment->contenttype = $attachment['type'];
1564
+		}
1287 1565
 
1288 1566
 		unset($attachment);
1289 1567
 
@@ -1329,11 +1607,15 @@  discard block
 block discarded – undo
1329 1607
 		//unset($folderid, $id, $message, $contentParameters);
1330 1608
 		$account = $folder = null;
1331 1609
 		$this->splitID($folderid, $account, $folder);
1332
-		if (isset($message->flag)) {
1333
-			if (isset($message->flag->flagstatus) && $message->flag->flagstatus == 2) {
1610
+		if (isset($message->flag))
1611
+		{
1612
+			if (isset($message->flag->flagstatus) && $message->flag->flagstatus == 2)
1613
+			{
1334 1614
 				$rv = $this->mail->flagMessages((($message->flag->flagstatus == 2) ? "flagged" : "unflagged"), $id,$folder);
1335 1615
 				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." -> set ".array2string($id).' in Folder '.$folder." as " . (($message->flag->flagstatus == 2) ? "flagged" : "unflagged") . "-->". $rv);
1336
-			} else {
1616
+			}
1617
+			else
1618
+			{
1337 1619
 				$rv = $this->mail->flagMessages("unflagged", $id,$folder);
1338 1620
 				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." -> set ".array2string($id).' in Folder '.$folder." as " . "unflagged" . "-->". $rv);
1339 1621
 			}
@@ -1363,7 +1645,10 @@  discard block
 block discarded – undo
1363 1645
 		$this->splitID($folderid, $account, $srcFolder);
1364 1646
 		$this->splitID($newfolderid, $account, $destFolder);
1365 1647
 		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-MoveMessage: (SourceFolder: '$srcFolder'  id: '$id'  DestFolder: '$destFolder' )");
1366
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1648
+		if (!isset($this->mail))
1649
+		{
1650
+			$this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
1651
+		}
1367 1652
 		$this->mail->reopen($destFolder);
1368 1653
 		$status = $this->mail->getFolderStatus($destFolder);
1369 1654
 		$uidNext = $status['uidnext'];
@@ -1395,7 +1680,10 @@  discard block
 block discarded – undo
1395 1680
 				$maximumSyncRangeInDays = $GLOBALS['egw_info']['user']['preferences']['activesync']['mail-maximumSyncRange'];
1396 1681
 			}
1397 1682
 			$cutoffdate = (is_numeric($maximumSyncRangeInDays) ? Api\DateTime::to('now','ts')-(3600*24*$maximumSyncRangeInDays):null);
1398
-			if (is_numeric($maximumSyncRangeInDays)) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' Client set no truncationdate. Using '.$maximumSyncRangeInDays.' days.'.date("d-M-Y", $cutoffdate));
1683
+			if (is_numeric($maximumSyncRangeInDays))
1684
+			{
1685
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' Client set no truncationdate. Using '.$maximumSyncRangeInDays.' days.'.date("d-M-Y", $cutoffdate));
1686
+			}
1399 1687
 		}
1400 1688
 		return $this->fetchMessages($folderid, $cutoffdate);
1401 1689
 	}
@@ -1417,7 +1705,10 @@  discard block
 block discarded – undo
1417 1705
 	{
1418 1706
 		static $headers = array();
1419 1707
 
1420
-		if ($this->debugLevel>1) $gstarttime = microtime (true);
1708
+		if ($this->debugLevel>1)
1709
+		{
1710
+			$gstarttime = microtime (true);
1711
+		}
1421 1712
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__);
1422 1713
 		$rv_messages = array();
1423 1714
 		// if the message is still available within the class, we use it instead of fetching it again
@@ -1430,7 +1721,10 @@  discard block
 block discarded – undo
1430 1721
 		{
1431 1722
 			$headers = array();	// clear cache to not use too much memory
1432 1723
 
1433
-			if ($this->debugLevel>1) $starttime = microtime (true);
1724
+			if ($this->debugLevel>1)
1725
+			{
1726
+				$starttime = microtime (true);
1727
+			}
1434 1728
 			$this->_connect($this->account);
1435 1729
 			if ($this->debugLevel>1)
1436 1730
 			{
@@ -1439,8 +1733,14 @@  discard block
 block discarded – undo
1439 1733
 			}
1440 1734
 			$messagelist = $_filter = array();
1441 1735
 			// if not connected, any further action must fail
1442
-			if (!empty($cutoffdate)) $_filter = array('status'=>array('UNDELETED'),'range'=>"SINCE",'date'=> date("d-M-Y", $cutoffdate));
1443
-			if ($this->debugLevel>1) $starttime = microtime (true);
1736
+			if (!empty($cutoffdate))
1737
+			{
1738
+				$_filter = array('status'=>array('UNDELETED'),'range'=>"SINCE",'date'=> date("d-M-Y", $cutoffdate));
1739
+			}
1740
+			if ($this->debugLevel>1)
1741
+			{
1742
+				$starttime = microtime (true);
1743
+			}
1444 1744
 			$account = $_folderName = $id = null;
1445 1745
 			$this->splitID($folderid,$account,$_folderName,$id);
1446 1746
 			if ($this->debugLevel>1)
@@ -1448,8 +1748,14 @@  discard block
 block discarded – undo
1448 1748
 				$endtime = microtime(true) - $starttime;
1449 1749
 				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__. " splitID took : ".$endtime.' for FolderID:'.$folderid);
1450 1750
 			}
1451
-			if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_id).'/'.$id);
1452
-			if ($this->debugLevel>1) $starttime = microtime (true);
1751
+			if ($this->debugLevel>1)
1752
+			{
1753
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_id).'/'.$id);
1754
+			}
1755
+			if ($this->debugLevel>1)
1756
+			{
1757
+				$starttime = microtime (true);
1758
+			}
1453 1759
 			$_numberOfMessages = (empty($cutoffdate)?250:99999);
1454 1760
 			$rv_messages = $this->mail->getHeaders($_folderName, $_startMessage=1, $_numberOfMessages, $_sort=0, $_reverse=false, $_filter, $_id);
1455 1761
 			if ($this->debugLevel>1)
@@ -1458,27 +1764,56 @@  discard block
 block discarded – undo
1458 1764
 				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__. " getHeaders call took : ".$endtime.' for FolderID:'.$_folderName);
1459 1765
 			}
1460 1766
 		}
1461
-		if ($_id == NULL && $this->debugLevel>1)  ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." found :". count($rv_messages['header']));
1767
+		if ($_id == NULL && $this->debugLevel>1)
1768
+		{
1769
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__." found :". count($rv_messages['header']));
1770
+		}
1462 1771
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' Result:'.array2string($rv_messages));
1463 1772
 		$messagelist = array();
1464
-		if (!isset($rv_messages['header'])||empty($rv_messages['header'])) return $messagelist;
1773
+		if (!isset($rv_messages['header'])||empty($rv_messages['header']))
1774
+		{
1775
+			return $messagelist;
1776
+		}
1465 1777
 		//if ($_returnModHash) $messageFolderHash = array();
1466 1778
 		foreach ((array)$rv_messages['header'] as $k => $vars)
1467 1779
 		{
1468
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' ID to process:'.$vars['uid'].' Subject:'.$vars['subject']);
1780
+			if ($this->debugLevel>3)
1781
+			{
1782
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' ID to process:'.$vars['uid'].' Subject:'.$vars['subject']);
1783
+			}
1469 1784
 			$headers[$vars['uid']] = $vars;
1470
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' MailID:'.$k.'->'.array2string($vars));
1471
-			if (!empty($vars['deleted'])) continue; // cut of deleted messages
1472
-			if ($cutoffdate && $vars['date'] < $cutoffdate) continue; // message is out of range for cutoffdate, ignore it
1473
-			if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' ID to report:'.$vars['uid'].' Subject:'.$vars['subject']);
1785
+			if ($this->debugLevel>3)
1786
+			{
1787
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' MailID:'.$k.'->'.array2string($vars));
1788
+			}
1789
+			if (!empty($vars['deleted']))
1790
+			{
1791
+				continue;
1792
+			}
1793
+			// cut of deleted messages
1794
+			if ($cutoffdate && $vars['date'] < $cutoffdate)
1795
+			{
1796
+				continue;
1797
+			}
1798
+			// message is out of range for cutoffdate, ignore it
1799
+			if ($this->debugLevel>0)
1800
+			{
1801
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.' ID to report:'.$vars['uid'].' Subject:'.$vars['subject']);
1802
+			}
1474 1803
 			$mess = $return_all_headers ? $vars : array();
1475 1804
 			$mess["mod"] = self::doFlagsMod($vars).$vars['date'];
1476 1805
 			$mess["id"] = $vars['uid'];
1477 1806
 			// 'seen' aka 'read' is the only flag we want to know about
1478 1807
 			$mess["flags"] = 0;
1479 1808
 			// outlook supports additional flags, set them to 0
1480
-			if($vars["seen"]) $mess["flags"] = 1;
1481
-			if ($this->debugLevel>3) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($mess));
1809
+			if($vars["seen"])
1810
+			{
1811
+				$mess["flags"] = 1;
1812
+			}
1813
+			if ($this->debugLevel>3)
1814
+			{
1815
+				ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($mess));
1816
+			}
1482 1817
 			$messagelist[$vars['uid']] = $mess;
1483 1818
 			unset($mess);
1484 1819
 		}
@@ -1503,9 +1838,18 @@  discard block
 block discarded – undo
1503 1838
 	static function doFlagsMod($headerFlags)
1504 1839
 	{
1505 1840
 		$flags = 'nnn';
1506
-		if ($headerFlags['flagged']) $flags[0] = 'f';
1507
-		if ($headerFlags['answered']) $flags[1] = 'a';
1508
-		if ($headerFlags['forwarded']) $flags[2] = 'f';
1841
+		if ($headerFlags['flagged'])
1842
+		{
1843
+			$flags[0] = 'f';
1844
+		}
1845
+		if ($headerFlags['answered'])
1846
+		{
1847
+			$flags[1] = 'a';
1848
+		}
1849
+		if ($headerFlags['forwarded'])
1850
+		{
1851
+			$flags[2] = 'f';
1852
+		}
1509 1853
 		//ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.'('.array2string($headerFlags).') returning '.array2string($flags));
1510 1854
 		return $flags;
1511 1855
 	}
@@ -1537,31 +1881,55 @@  discard block
 block discarded – undo
1537 1881
 	{
1538 1882
 		//$this->debugLevel=1;
1539 1883
 		$searchquery=$_searchquery->GetDataArray();
1540
-		if (!is_array($searchquery)) return array();
1541
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($searchquery));
1884
+		if (!is_array($searchquery))
1885
+		{
1886
+			return array();
1887
+		}
1888
+		if ($this->debugLevel>0)
1889
+		{
1890
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($searchquery));
1891
+		}
1542 1892
 
1543
-		if (isset($searchquery['searchrebuildresults'])) {
1893
+		if (isset($searchquery['searchrebuildresults']))
1894
+		{
1544 1895
 			$rebuildresults = $searchquery['searchrebuildresults'];
1545
-		} else {
1896
+		}
1897
+		else
1898
+		{
1546 1899
 			$rebuildresults = false;
1547 1900
 		}
1548
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,  'RebuildResults ['.$rebuildresults.']' );
1901
+		if ($this->debugLevel>0)
1902
+		{
1903
+			ZLog::Write(LOGLEVEL_DEBUG,  'RebuildResults ['.$rebuildresults.']' );
1904
+		}
1549 1905
 
1550
-		if (isset($searchquery['deeptraversal'])) {
1906
+		if (isset($searchquery['deeptraversal']))
1907
+		{
1551 1908
 			$deeptraversal = $searchquery['deeptraversal'];
1552
-		} else {
1909
+		}
1910
+		else
1911
+		{
1553 1912
 			$deeptraversal = false;
1554 1913
 		}
1555
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,  'DeepTraversal ['.$deeptraversal.']' );
1914
+		if ($this->debugLevel>0)
1915
+		{
1916
+			ZLog::Write(LOGLEVEL_DEBUG,  'DeepTraversal ['.$deeptraversal.']' );
1917
+		}
1556 1918
 
1557
-		if (isset($searchquery['searchrange'])) {
1919
+		if (isset($searchquery['searchrange']))
1920
+		{
1558 1921
 			$range = explode("-",$_searchquery->GetSearchRange());
1559 1922
 			$start =$range[0] + 1;
1560 1923
 			$limit = $range[1] - $range[0] + 1;
1561
-		} else {
1924
+		}
1925
+		else
1926
+		{
1562 1927
 			$range = false;
1563 1928
 		}
1564
-		if ($this->debugLevel>0) ZLog::Write(LOGLEVEL_DEBUG,  'Range ['.print_r($range, true).']' );
1929
+		if ($this->debugLevel>0)
1930
+		{
1931
+			ZLog::Write(LOGLEVEL_DEBUG,  'Range ['.print_r($range, true).']' );
1932
+		}
1565 1933
 
1566 1934
 		//foreach($searchquery['query'] as $k => $value) {
1567 1935
 		//	$query = $value;
@@ -1613,7 +1981,10 @@  discard block
 block discarded – undo
1613 1981
 			$_filter['since'] = date("d-M-Y", Api\DateTime::to($sincedate,'ts'));
1614 1982
 		}
1615 1983
 		//$_filter[] = array('type'=>"SINCE",'string'=> date("d-M-Y", $cutoffdate));
1616
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter));
1984
+		if ($this->debugLevel>1)
1985
+		{
1986
+			ZLog::Write(LOGLEVEL_DEBUG, __METHOD__.' for Folder:'.$_folderName.' Filter:'.array2string($_filter));
1987
+		}
1617 1988
 		$rv_messages = $this->mail->getHeaders($_folderName, $_startMessage=($range?$start:1), $_numberOfMessages=($limit?$limit:9999999), $_sort=0, $_reverse=false, $_filter, $_id=NULL);
1618 1989
 		//ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__.array2string($rv_messages));
1619 1990
 		$list=array();
@@ -1645,17 +2016,26 @@  discard block
 block discarded – undo
1645 2016
 	private function getParentID($account,$folder)
1646 2017
 	{
1647 2018
 		$this->_connect($account);
1648
-		if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true,false);
2019
+		if (!isset($this->folders))
2020
+		{
2021
+			$this->folders = $this->mail->getFolderObjects(true,false);
2022
+		}
1649 2023
 
1650 2024
 		$mailFolder = $this->folders[$folder];
1651
-		if (!isset($mailFolder)) return false;
2025
+		if (!isset($mailFolder))
2026
+		{
2027
+			return false;
2028
+		}
1652 2029
 		$delimiter = (isset($mailFolder->delimiter)?$mailFolder->delimiter:$this->mail->getHierarchyDelimiter());
1653 2030
 		$parent = explode($delimiter,$folder);
1654 2031
 		array_pop($parent);
1655 2032
 		$parent = implode($delimiter,$parent);
1656 2033
 
1657 2034
 		$id = $parent && $this->folders[$parent] ? $this->createID($account, $parent) : '0';
1658
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."('$folder') --> parent=$parent --> $id");
2035
+		if ($this->debugLevel>1)
2036
+		{
2037
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."('$folder') --> parent=$parent --> $id");
2038
+		}
1659 2039
 		return $id;
1660 2040
 	}
1661 2041
 
@@ -1669,7 +2049,10 @@  discard block
 block discarded – undo
1669 2049
 	{
1670 2050
 		static $last_id = null;
1671 2051
 		static $folderObj = null;
1672
-		if (isset($last_id) && $last_id === $id) return $folderObj;
2052
+		if (isset($last_id) && $last_id === $id)
2053
+		{
2054
+			return $folderObj;
2055
+		}
1673 2056
 
1674 2057
 		try {
1675 2058
 			$account = $folder = null;
@@ -1680,18 +2063,30 @@  discard block
 block discarded – undo
1680 2063
 			return $folderObj=false;
1681 2064
 		}
1682 2065
 		$this->_connect($account);
1683
-		if (!isset($this->folders)) $this->folders = $this->mail->getFolderObjects(true,false);
2066
+		if (!isset($this->folders))
2067
+		{
2068
+			$this->folders = $this->mail->getFolderObjects(true,false);
2069
+		}
1684 2070
 
1685 2071
 		$mailFolder = $this->folders[$folder];
1686
-		if (!isset($mailFolder)) return $folderObj=false;
2072
+		if (!isset($mailFolder))
2073
+		{
2074
+			return $folderObj=false;
2075
+		}
1687 2076
 
1688 2077
 		$folderObj = new SyncFolder();
1689 2078
 		$folderObj->serverid = $id;
1690 2079
 		$folderObj->parentid = $this->getParentID($account,$folder);
1691 2080
 		$folderObj->displayname = $mailFolder->shortDisplayName;
1692
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." ID: $id, Account:$account, Folder:$folder");
2081
+		if ($this->debugLevel>1)
2082
+		{
2083
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." ID: $id, Account:$account, Folder:$folder");
2084
+		}
1693 2085
 		// get folder-type
1694
-		foreach($this->folders as $inbox => $mailFolder) break;
2086
+		foreach($this->folders as $inbox => $mailFolder)
2087
+		{
2088
+			break;
2089
+		}
1695 2090
 		if ($folder == $inbox)
1696 2091
 		{
1697 2092
 			$folderObj->type = SYNC_FOLDER_TYPE_INBOX;
@@ -1728,7 +2123,10 @@  discard block
 block discarded – undo
1728 2123
 			$folderObj->type = SYNC_FOLDER_TYPE_USER_MAIL;
1729 2124
 		}
1730 2125
 
1731
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($id) --> $folder --> type=$folderObj->type, parentID=$folderObj->parentid, displayname=$folderObj->displayname");
2126
+		if ($this->debugLevel>1)
2127
+		{
2128
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($id) --> $folder --> type=$folderObj->type, parentID=$folderObj->parentid, displayname=$folderObj->displayname");
2129
+		}
1732 2130
 		return $folderObj;
1733 2131
 	}
1734 2132
 
@@ -1772,11 +2170,20 @@  discard block
 block discarded – undo
1772 2170
 	{
1773 2171
 		$account = $folder = null;
1774 2172
 		$this->splitID($folderid, $account, $folder);
1775
-		if (is_numeric($account)) $type = 'mail';
2173
+		if (is_numeric($account))
2174
+		{
2175
+			$type = 'mail';
2176
+		}
1776 2177
 
1777
-		if ($type != 'mail') return false;
2178
+		if ($type != 'mail')
2179
+		{
2180
+			return false;
2181
+		}
1778 2182
 
1779
-		if (!isset($this->mail)) $this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
2183
+		if (!isset($this->mail))
2184
+		{
2185
+			$this->mail = Mail::getInstance(false,self::$profileID,true,false,true);
2186
+		}
1780 2187
 
1781 2188
         $this->mail->reopen($folder);
1782 2189
 
@@ -1821,7 +2228,7 @@  discard block
 block discarded – undo
1821 2228
      * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1822 2229
      */
1823 2230
     public function DeleteMessage($folderid, $id, $contentParameters)
1824
-	{
2231
+    {
1825 2232
 		unset($contentParameters);	// not used, but required by function signature
1826 2233
 		ZLog::Write(LOGLEVEL_DEBUG, "IMAP-DeleteMessage: (fid: '$folderid'  id: '$id' )");
1827 2234
 		/*
@@ -1847,7 +2254,10 @@  discard block
 block discarded – undo
1847 2254
 			$error = $e->getMessage();
1848 2255
 			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__.__LINE__." $_messageUID, $folder ->".$error);
1849 2256
 			// if the server thinks the message does not exist report deletion as success
1850
-			if (stripos($error,'[NONEXISTENT]')!==false) return true;
2257
+			if (stripos($error,'[NONEXISTENT]')!==false)
2258
+			{
2259
+				return true;
2260
+			}
1851 2261
 			return false;
1852 2262
 		}
1853 2263
 
@@ -1880,7 +2290,7 @@  discard block
 block discarded – undo
1880 2290
      * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1881 2291
      */
1882 2292
     public function SetReadFlag($folderid, $id, $flags, $contentParameters)
1883
-	{
2293
+    {
1884 2294
 		unset($contentParameters);	// not used, but required by function signature
1885 2295
 		// ZLog::Write(LOGLEVEL_DEBUG, "IMAP-SetReadFlag: (fid: '$folderid'  id: '$id'  flags: '$flags' )");
1886 2296
 		$account = $folder = null;
@@ -1964,10 +2374,16 @@  discard block
 block discarded – undo
1964 2374
 		$account = $parent_id = $app = null;
1965 2375
 		$this->splitID($id, $account, $folder, $app);
1966 2376
 		$old_hash = $this->folder2hash($account, $folder);
1967
-		if ($parentid) $this->splitID($parentid, $account, $parentfolder, $app);
2377
+		if ($parentid)
2378
+		{
2379
+			$this->splitID($parentid, $account, $parentfolder, $app);
2380
+		}
1968 2381
 		ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."( '$id (-> $folder)','$parentid ".($parentid?'(->'.$parentfolder.')':'')."') called!");
1969 2382
 		$ret = $this->mail->deleteFolder($folder);
1970
-		if ($ret) $newHash = $this->rename_folder_hash($account, $old_hash, "##Dele#edFolder#$folder##");
2383
+		if ($ret)
2384
+		{
2385
+			$newHash = $this->rename_folder_hash($account, $old_hash, "##Dele#edFolder#$folder##");
2386
+		}
1971 2387
 		return $ret;
1972 2388
 	}
1973 2389
 
@@ -2012,7 +2428,10 @@  discard block
 block discarded – undo
2012 2428
 
2013 2429
 		$str = $this->backend->createID($account, $folder, $id);
2014 2430
 
2015
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($account,'$f',$id) type=$account, folder=$folder --> '$str'");
2431
+		if ($this->debugLevel>1)
2432
+		{
2433
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."($account,'$f',$id) type=$account, folder=$folder --> '$str'");
2434
+		}
2016 2435
 
2017 2436
 		return $str;
2018 2437
 	}
@@ -2033,7 +2452,10 @@  discard block
 block discarded – undo
2033 2452
 		// convert numeric folder-id back to folder name
2034 2453
 		$folder = $this->hash2folder($account,$f=$folder);
2035 2454
 
2036
-		if ($this->debugLevel>1) ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."('$str','$account','$folder',$appid)");
2455
+		if ($this->debugLevel>1)
2456
+		{
2457
+			ZLog::Write(LOGLEVEL_DEBUG,__METHOD__."('$str','$account','$folder',$appid)");
2458
+		}
2037 2459
 	}
2038 2460
 
2039 2461
 	/**
@@ -2052,7 +2474,10 @@  discard block
 block discarded – undo
2052 2474
 	 */
2053 2475
 	private function folder2hash($account,$folder)
2054 2476
 	{
2055
-		if(!isset($this->folderHashes)) $this->readFolderHashes();
2477
+		if(!isset($this->folderHashes))
2478
+		{
2479
+			$this->readFolderHashes();
2480
+		}
2056 2481
 
2057 2482
 		if (($index = array_search($folder, (array)$this->folderHashes[$account])) === false)
2058 2483
 		{
@@ -2075,7 +2500,10 @@  discard block
 block discarded – undo
2075 2500
 	 */
2076 2501
 	private function hash2folder($account,$index)
2077 2502
 	{
2078
-		if(!isset($this->folderHashes)) $this->readFolderHashes();
2503
+		if(!isset($this->folderHashes))
2504
+		{
2505
+			$this->readFolderHashes();
2506
+		}
2079 2507
 
2080 2508
 		return isset($this->folderHashes[$account]) ? $this->folderHashes[$account][$index] : null;
2081 2509
 	}
Please login to merge, or discard this patch.