Passed
Push — 17.1 ( 431f3f...4dae72 )
by Ralf
01:23 queued 12s
created
api/src/Mail.php 1 patch
Spacing   +1190 added lines, -1191 removed lines patch added patch discarded remove patch
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 	 *
125 125
 	 * @array
126 126
 	 */
127
-	static $tidy_config = array('clean'=>false,'output-html'=>true,'join-classes'=>true,'join-styles'=>true,'show-body-only'=>"auto",'word-2000'=>true,'wrap'=>0);
127
+	static $tidy_config = array('clean'=>false, 'output-html'=>true, 'join-classes'=>true, 'join-styles'=>true, 'show-body-only'=>"auto", 'word-2000'=>true, 'wrap'=>0);
128 128
 
129 129
 	/**
130 130
 	 * static used to configure htmLawed, for use with emails
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
 		'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
136 136
 		'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)
137 137
 		// we switch the balance off because of some broken html mails contents get removed like (td in table), and let browser deal with it
138
-		'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)
138
+		'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)
139 139
 		'direct_list_nest' => 1,
140
-		'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
140
+		'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
141 141
 		// tidy eats away even some wanted whitespace, so we switch it off;
142 142
 		// we used it for its compacting and beautifying capabilities, which resulted in better html for further processing
143 143
 		'tidy'=>0,
@@ -152,13 +152,13 @@  discard block
 block discarded – undo
152 152
 	 *
153 153
 	 * @array
154 154
 	 */
155
-	static $aclShortCuts = array('' => array('label'=>'none','title'=>'The user has no rights whatsoever.'),
156
-		'lrs'		=> array('label'=>'readable','title'=>'Allows a user to read the contents of the mailbox.'),
157
-		'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.'),
158
-		'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.'),
159
-		'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.'),
160
-		'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.'),
161
-		'custom'	=> array('label'=>'custom','title'=>'User defined combination of rights for the ACL'),
155
+	static $aclShortCuts = array('' => array('label'=>'none', 'title'=>'The user has no rights whatsoever.'),
156
+		'lrs'		=> array('label'=>'readable', 'title'=>'Allows a user to read the contents of the mailbox.'),
157
+		'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.'),
158
+		'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.'),
159
+		'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.'),
160
+		'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.'),
161
+		'custom'	=> array('label'=>'custom', 'title'=>'User defined combination of rights for the ACL'),
162 162
 	);
163 163
 
164 164
 	/**
@@ -200,13 +200,13 @@  discard block
 block discarded – undo
200 200
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
201 201
 	 * @return Mail
202 202
 	 */
203
-	public static function getInstance($_restoreSession=true, &$_profileID=0, $_validate=true, $_oldImapServerObject=false, $_reuseCache=null)
203
+	public static function getInstance($_restoreSession = true, &$_profileID = 0, $_validate = true, $_oldImapServerObject = false, $_reuseCache = null)
204 204
 	{
205 205
 		//$_restoreSession=false;
206 206
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
207 207
 		//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());
208 208
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_oldImapServerObject));
209
-		self::$profileDefunct = Cache::getCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),5*1);
209
+		self::$profileDefunct = Cache::getCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 5 * 1);
210 210
 		if (isset(self::$profileDefunct[$_profileID]) && strlen(self::$profileDefunct[$_profileID]))
211 211
 		{
212 212
 			throw new Exception(__METHOD__." failed to instanciate Mail for Profile #$_profileID Reason:".self::$profileDefunct[$_profileID]);
@@ -215,13 +215,13 @@  discard block
 block discarded – undo
215 215
 		{
216 216
 			if (!is_object(self::$instances[$_profileID]))
217 217
 			{
218
-				self::$instances[$_profileID] = new Mail('utf-8',false,$_profileID,false,$_reuseCache);
218
+				self::$instances[$_profileID] = new Mail('utf-8', false, $_profileID, false, $_reuseCache);
219 219
 			}
220 220
 			self::$instances[$_profileID]->icServer = $_oldImapServerObject;
221
-			self::$instances[$_profileID]->accountid= $_oldImapServerObject->ImapServerId;
222
-			self::$instances[$_profileID]->profileID= $_oldImapServerObject->ImapServerId;
221
+			self::$instances[$_profileID]->accountid = $_oldImapServerObject->ImapServerId;
222
+			self::$instances[$_profileID]->profileID = $_oldImapServerObject->ImapServerId;
223 223
 			self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
224
-			self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
224
+			self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
225 225
 			return self::$instances[$_profileID];
226 226
 		}
227 227
 		if ($_profileID == 0)
@@ -234,14 +234,14 @@  discard block
 block discarded – undo
234 234
 			{
235 235
 				$profileID = Mail\Account::get_default_acc_id();
236 236
 			}
237
-			if ($profileID!=$_profileID) $_restoreSession==false;
238
-			$_profileID=$profileID;
237
+			if ($profileID != $_profileID) $_restoreSession == false;
238
+			$_profileID = $profileID;
239 239
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' called with profileID==0 using '.$profileID.' instead->'.function_backtrace());
240 240
 		}
241 241
 		// no validation or restoreSession for old ImapServer Object, just fetch it and return it
242
-		if ($_oldImapServerObject===true)
242
+		if ($_oldImapServerObject === true)
243 243
 		{
244
-			return new Mail('utf-8',false,$_profileID,true,$_reuseCache);
244
+			return new Mail('utf-8', false, $_profileID, true, $_reuseCache);
245 245
 		}
246 246
 		if ($_profileID != 0 && $_validate)
247 247
 		{
@@ -261,9 +261,9 @@  discard block
 block discarded – undo
261 261
 			//Cache::setSession('mail','activeProfileID',$_profileID);
262 262
 		}
263 263
 		//error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID.' called from:'.function_backtrace());
264
-		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession===false))
264
+		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession === false))
265 265
 		{
266
-			self::$instances[$_profileID] = new Mail('utf-8',$_restoreSession,$_profileID,false,$_reuseCache);
266
+			self::$instances[$_profileID] = new Mail('utf-8', $_restoreSession, $_profileID, false, $_reuseCache);
267 267
 		}
268 268
 		else
269 269
 		{
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 				self::$instances[$_profileID]->ogServer = Mail\Account::read($_profileID)->smtpServer();
275 275
 				// TODO: merge mailprefs into userprefs, for easy treatment
276 276
 				self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
277
-				self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
277
+				self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
278 278
 			} catch (\Exception $e)
279 279
 			{
280 280
 				$newprofileID = Mail\Account::get_default_acc_id();
@@ -282,15 +282,15 @@  discard block
 block discarded – undo
282 282
 				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());
283 283
 				if ($newprofileID)
284 284
 				{
285
-					self::$instances[$newprofileID] = new Mail('utf-8',false,$newprofileID,false,$_reuseCache);
285
+					self::$instances[$newprofileID] = new Mail('utf-8', false, $newprofileID, false, $_reuseCache);
286 286
 					$_profileID = $newprofileID;
287 287
 				}
288 288
 				else
289 289
 				{
290
-					throw new Exception(__METHOD__." failed to load the Profile for ProfileID for $_profileID with error:".$e->getMessage().($e->details?', '.$e->details:''));
290
+					throw new Exception(__METHOD__." failed to load the Profile for ProfileID for $_profileID with error:".$e->getMessage().($e->details ? ', '.$e->details : ''));
291 291
 				}
292 292
 			}
293
-			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate );
293
+			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate);
294 294
 		}
295 295
 		self::$instances[$_profileID]->profileID = $_profileID;
296 296
 		if (!isset(self::$instances[$_profileID]->idna2)) self::$instances[$_profileID]->idna2 = new Horde_Idna;
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 	public static function fixInvalidAliasAddress($refrence, $address)
312 312
 	{
313 313
 		$parts = explode('@', $refrence);
314
-		if (!strpos($address,'@') && !empty($parts[1])) $address .= '@'.$parts[1];
314
+		if (!strpos($address, '@') && !empty($parts[1])) $address .= '@'.$parts[1];
315 315
 		return $address;
316 316
 	}
317 317
 
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 	 * @param boolean $_testConnection = 0
323 323
 	 * @return mixed $_profileID or false on failed ConnectionTest
324 324
 	 */
325
-	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID=0, $_testConnection=true)
325
+	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID = 0, $_testConnection = true)
326 326
 	{
327 327
 		if (isset($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']) && !empty($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']))
328 328
 		{
@@ -343,12 +343,12 @@  discard block
 block discarded – undo
343 343
 		}
344 344
 		if ($oldProfileID != $_profileID)
345 345
 		{
346
-			if ($oldProfileID && $_profileID==0) $_profileID = $oldProfileID;
347
-			$GLOBALS['egw']->preferences->add('mail','ActiveProfileID',$_profileID,'user');
346
+			if ($oldProfileID && $_profileID == 0) $_profileID = $oldProfileID;
347
+			$GLOBALS['egw']->preferences->add('mail', 'ActiveProfileID', $_profileID, 'user');
348 348
 			// save prefs
349 349
 			$GLOBALS['egw']->preferences->save_repository(true);
350 350
 			$GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $_profileID;
351
-			Cache::setSession('mail','activeProfileID',$_profileID);
351
+			Cache::setSession('mail', 'activeProfileID', $_profileID);
352 352
 		}
353 353
 		return $_profileID;
354 354
 	}
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 	 * @param int $_acc_id = 0
364 364
 	 * @return int validated acc_id -> either acc_id given, or first valid one
365 365
 	 */
366
-	public static function validateProfileID($_acc_id=0)
366
+	public static function validateProfileID($_acc_id = 0)
367 367
 	{
368 368
 		if ($_acc_id)
369 369
 		{
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
 		}
383 383
 		// no account specified or specified account not found or not valid
384 384
 		// --> search existing account for first valid one and return that
385
-		foreach(Mail\Account::search($only_current_user=true, 'acc_imap_host') as $acc_id => $imap_host)
385
+		foreach (Mail\Account::search($only_current_user = true, 'acc_imap_host') as $acc_id => $imap_host)
386 386
 		{
387 387
 			if (!empty($imap_host) && ($account = Mail\Account::read($acc_id)) && $account->is_imap())
388 388
 			{
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 	 * @param boolean $_oldImapServerObject = false
405 405
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
406 406
 	 */
407
-	private function __construct($_displayCharset='utf-8',$_restoreSession=true, $_profileID=0, $_oldImapServerObject=false, $_reuseCache=null)
407
+	private function __construct($_displayCharset = 'utf-8', $_restoreSession = true, $_profileID = 0, $_oldImapServerObject = false, $_reuseCache = null)
408 408
 	{
409 409
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
410 410
 		if (!empty($_displayCharset)) self::$displayCharset = $_displayCharset;
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
 			$firstMessage = $this->sessionData['previewMessage'];
425 425
 			$this->sessionData = array();
426 426
 		}
427
-		if (!$_reuseCache) $this->forcePrefReload($_profileID,!$_reuseCache);
427
+		if (!$_reuseCache) $this->forcePrefReload($_profileID, !$_reuseCache);
428 428
 		try
429 429
 		{
430 430
 			$this->profileID = self::validateProfileID($_profileID);
@@ -438,11 +438,11 @@  discard block
 block discarded – undo
438 438
 			throw new Exception(__METHOD__." failed to instanciate Mail for $_profileID / ".$this->profileID." with error:".$e->getMessage());
439 439
 		}
440 440
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($acc->imapServer()));
441
-		$this->icServer = ($_oldImapServerObject?$acc->oldImapServer():$acc->imapServer());
441
+		$this->icServer = ($_oldImapServerObject ? $acc->oldImapServer() : $acc->imapServer());
442 442
 		$this->ogServer = $acc->smtpServer();
443 443
 		// TODO: merge mailprefs into userprefs, for easy treatment
444 444
 		$this->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
445
-		$this->htmlOptions  = $this->mailPreferences['htmlOptions'];
445
+		$this->htmlOptions = $this->mailPreferences['htmlOptions'];
446 446
 		if (isset($this->icServer->ImapServerId) && !empty($this->icServer->ImapServerId))
447 447
 		{
448 448
 			$_profileID = $this->profileID = $GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $this->icServer->ImapServerId;
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
 	public static function &forceEAProfileLoad($_profile_id)
461 461
 	{
462 462
 		self::unsetCachedObjects($_profile_id);
463
-		$mail = self::getInstance(false, $_profile_id,false);
463
+		$mail = self::getInstance(false, $_profile_id, false);
464 464
 		//_debug_array( $_profile_id);
465 465
 		$mail->icServer = Mail\Account::read($_profile_id)->imapServer();
466 466
 		$mail->ogServer = Mail\Account::read($_profile_id)->smtpServer();
@@ -472,11 +472,11 @@  discard block
 block discarded – undo
472 472
 	 * @param int $_profile_id
473 473
 	 * @param boolean $_resetFolderObjects
474 474
 	 */
475
-	public static function forcePrefReload($_profile_id=null,$_resetFolderObjects=true)
475
+	public static function forcePrefReload($_profile_id = null, $_resetFolderObjects = true)
476 476
 	{
477 477
 		// unset the mail_preferences session object, to force the reload/rebuild
478
-		Cache::setSession('mail','mail_preferences',serialize(array()));
479
-		Cache::setSession('emailadmin','session_data',serialize(array()));
478
+		Cache::setSession('mail', 'mail_preferences', serialize(array()));
479
+		Cache::setSession('emailadmin', 'session_data', serialize(array()));
480 480
 		if ($_resetFolderObjects) self::resetFolderObjectCache($_profile_id);
481 481
 	}
482 482
 
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 	function restoreSessionData()
487 487
 	{
488 488
 		$this->sessionData = array();
489
-		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
489
+		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
490 490
 		if (is_array(self::$activeFolderCache[$this->profileID]))
491 491
 		{
492 492
 			foreach (self::$activeFolderCache[$this->profileID] as $key => $value)
@@ -508,19 +508,19 @@  discard block
 block discarded – undo
508 508
 			{
509 509
 				self::$activeFolderCache = array($this->profileID => array($key => $value));
510 510
 			}
511
-			else if(empty(self::$activeFolderCache[$this->profileID]))
511
+			else if (empty(self::$activeFolderCache[$this->profileID]))
512 512
 			{
513 513
 				self::$activeFolderCache += array($this->profileID => array($key => $value));
514 514
 			}
515 515
 			else
516 516
 			{
517
-				self::$activeFolderCache[$this->profileID] =  array_merge(self::$activeFolderCache[$this->profileID], array($key => $value));
517
+				self::$activeFolderCache[$this->profileID] = array_merge(self::$activeFolderCache[$this->profileID], array($key => $value));
518 518
 			}
519 519
 		}
520 520
 
521 521
 		if (isset(self::$activeFolderCache) && is_array(self::$activeFolderCache))
522 522
 		{
523
-			Cache::setCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),self::$activeFolderCache, 60*60*10);
523
+			Cache::setCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), self::$activeFolderCache, 60 * 60 * 10);
524 524
 		}
525 525
 		// no need to block session any longer
526 526
 		$GLOBALS['egw']->session->commit_session();
@@ -538,40 +538,40 @@  discard block
 block discarded – undo
538 538
 	 * @param int $_profileID = null default profile of user as returned by getUserDefaultProfileID
539 539
 	 * @return void
540 540
 	 */
541
-	static function unsetCachedObjects($_profileID=null)
541
+	static function unsetCachedObjects($_profileID = null)
542 542
 	{
543 543
 		if (is_null($_profileID)) $_profileID = Mail\Account::get_default_acc_id();
544 544
 		if (is_array($_profileID) && $_profileID['account_id']) $account_id = $_profileID['account_id'];
545 545
 		//error_log(__METHOD__.__LINE__.' called with ProfileID:'.array2string($_profileID).' from '.function_backtrace());
546
-		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID,'tracker_')===false)))
546
+		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID, 'tracker_') === false)))
547 547
 		{
548 548
 			self::resetConnectionErrorCache($_profileID);
549
-			$rawHeadersCache = Cache::getCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
549
+			$rawHeadersCache = Cache::getCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
550 550
 			if (isset($rawHeadersCache[$_profileID]))
551 551
 			{
552 552
 				unset($rawHeadersCache[$_profileID]);
553
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$rawHeadersCache, $expiration=60*60*1);
553
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $rawHeadersCache, $expiration = 60 * 60 * 1);
554 554
 			}
555
-			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*5);
555
+			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 5);
556 556
 			if (isset($HierarchyDelimiterCache[$_profileID]))
557 557
 			{
558 558
 				unset($HierarchyDelimiterCache[$_profileID]);
559
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$HierarchyDelimiterCache, $expiration=60*60*24*5);
559
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $HierarchyDelimiterCache, $expiration = 60 * 60 * 24 * 5);
560 560
 			}
561 561
 			//reset folderObject cache, to trigger reload
562 562
 			self::resetFolderObjectCache($_profileID);
563 563
 			//reset counter of deleted messages per folder
564
-			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
564
+			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
565 565
 			if (isset($eMailListContainsDeletedMessages[$_profileID]))
566 566
 			{
567 567
 				unset($eMailListContainsDeletedMessages[$_profileID]);
568
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$eMailListContainsDeletedMessages, $expiration=60*60*1);
568
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $eMailListContainsDeletedMessages, $expiration = 60 * 60 * 1);
569 569
 			}
570
-			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*1);
570
+			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 1);
571 571
 			if (isset($vacationCached[$_profileID]))
572 572
 			{
573 573
 				unset($vacationCached[$_profileID]);
574
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),$vacationCached, $expiration=60*60*24*1);
574
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $vacationCached, $expiration = 60 * 60 * 24 * 1);
575 575
 			}
576 576
 
577 577
 			if (isset(self::$instances[$_profileID])) unset(self::$instances[$_profileID]);
@@ -579,17 +579,17 @@  discard block
 block discarded – undo
579 579
 		if (is_array($_profileID) && $_profileID['location'] == 'clear_cache')
580 580
 		{
581 581
 			// called via hook
582
-			foreach($GLOBALS['egw']->accounts->search(array('type' => 'accounts','order' => 'account_lid')) as $account)
582
+			foreach ($GLOBALS['egw']->accounts->search(array('type' => 'accounts', 'order' => 'account_lid')) as $account)
583 583
 			{
584 584
 				//error_log(__METHOD__.__LINE__.array2string($account));
585 585
 				$account_id = $account['account_id'];
586 586
 				$_profileID = null;
587
-				self::resetConnectionErrorCache($_profileID,$account_id);
588
-				self::resetFolderObjectCache($_profileID,$account_id);
589
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),array(), 60*60*1);
590
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),array(), 60*60*24*5);
591
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),array(), 60*60*1);
592
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),array(), 60*60*24*1);
587
+				self::resetConnectionErrorCache($_profileID, $account_id);
588
+				self::resetFolderObjectCache($_profileID, $account_id);
589
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), array(), 60 * 60 * 1);
590
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), array(), 60 * 60 * 24 * 5);
591
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), array(), 60 * 60 * 1);
592
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), array(), 60 * 60 * 24 * 1);
593 593
 			}
594 594
 		}
595 595
 	}
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
 	 * @param int $_ImapServerId the profileID to look for
601 601
 	 * @param int $account_id the egw account to look for
602 602
 	 */
603
-	static function resetConnectionErrorCache($_ImapServerId=null,$account_id=null)
603
+	static function resetConnectionErrorCache($_ImapServerId = null, $account_id = null)
604 604
 	{
605 605
 		//error_log(__METHOD__.' ('.__LINE__.') '.' for Profile:'.array2string($_ImapServerId) .' for user:'.trim($account_id));
606 606
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
@@ -618,19 +618,19 @@  discard block
 block discarded – undo
618 618
 		}
619 619
 		else
620 620
 		{
621
-			$isConError = Cache::getCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id));
621
+			$isConError = Cache::getCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id));
622 622
 			if (isset($isConError[$_ImapServerId]))
623 623
 			{
624 624
 				unset($isConError[$_ImapServerId]);
625 625
 			}
626
-			$waitOnFailure = Cache::getCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),null,array(),60*60*2);
626
+			$waitOnFailure = Cache::getCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), null, array(), 60 * 60 * 2);
627 627
 			if (isset($waitOnFailure[$_ImapServerId]))
628 628
 			{
629 629
 				unset($waitOnFailure[$_ImapServerId]);
630 630
 			}
631 631
 		}
632
-		Cache::setCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id),$isConError,60*15);
633
-		Cache::setCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),$waitOnFailure,60*60*2);
632
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id), $isConError, 60 * 15);
633
+		Cache::setCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), $waitOnFailure, 60 * 60 * 2);
634 634
 	}
635 635
 
636 636
 	/**
@@ -639,13 +639,13 @@  discard block
 block discarded – undo
639 639
 	 * @param int $_ImapServerId the profileID to look for
640 640
 	 * @param int $account_id the egw account to look for
641 641
 	 */
642
-	static function resetFolderObjectCache($_ImapServerId=null,$account_id=null)
642
+	static function resetFolderObjectCache($_ImapServerId = null, $account_id = null)
643 643
 	{
644 644
 		//error_log(__METHOD__.' ('.__LINE__.') '.' called for Profile:'.array2string($_ImapServerId).'->'.function_backtrace());
645 645
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
646 646
 		// on [location] => verify_settings we coud either use [prefs] => Array([ActiveProfileID] => 9, .. as $_ImapServerId
647 647
 		// or treat it as not given. we try that path
648
-		if (is_null($_ImapServerId)||is_array($_ImapServerId))
648
+		if (is_null($_ImapServerId) || is_array($_ImapServerId))
649 649
 		{
650 650
 			$folders2return = array();
651 651
 			$folderInfo = array();
@@ -654,12 +654,12 @@  discard block
 block discarded – undo
654 654
 		}
655 655
 		else
656 656
 		{
657
-			$folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),null,array(),60*60*1);
657
+			$folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), null, array(), 60 * 60 * 1);
658 658
 			if (!empty($folders2return) && isset($folders2return[$_ImapServerId]))
659 659
 			{
660 660
 				unset($folders2return[$_ImapServerId]);
661 661
 			}
662
-			$folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),null,array(),60*60*5);
662
+			$folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), null, array(), 60 * 60 * 5);
663 663
 			if (!empty($folderInfo) && isset($folderInfo[$_ImapServerId]))
664 664
 			{
665 665
 				unset($folderInfo[$_ImapServerId]);
@@ -671,23 +671,23 @@  discard block
 block discarded – undo
671 671
 				unset($lastFolderUsedForMove[$_ImapServerId]);
672 672
 			}
673 673
 			*/
674
-			$folderBasicInfo = Cache::getCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),null,array(),60*60*1);
674
+			$folderBasicInfo = Cache::getCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), null, array(), 60 * 60 * 1);
675 675
 			if (!empty($folderBasicInfo) && isset($folderBasicInfo[$_ImapServerId]))
676 676
 			{
677 677
 				unset($folderBasicInfo[$_ImapServerId]);
678 678
 			}
679
-			$_specialUseFolders = Cache::getCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),null,array(),60*60*12);
679
+			$_specialUseFolders = Cache::getCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), null, array(), 60 * 60 * 12);
680 680
 			if (!empty($_specialUseFolders) && isset($_specialUseFolders[$_ImapServerId]))
681 681
 			{
682 682
 				unset($_specialUseFolders[$_ImapServerId]);
683
-				self::$specialUseFolders=null;
683
+				self::$specialUseFolders = null;
684 684
 			}
685 685
 		}
686
-		Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),$folders2return, 60*60*1);
687
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),$folderInfo,60*60*5);
686
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), $folders2return, 60 * 60 * 1);
687
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), $folderInfo, 60 * 60 * 5);
688 688
 		//Cache::setCache(Cache::INSTANCE,'email','lastFolderUsedForMove'.trim($account_id),$lastFolderUsedForMove,$expiration=60*60*1);
689
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),$folderBasicInfo,60*60*1);
690
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),$_specialUseFolders,60*60*12);
689
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), $folderBasicInfo, 60 * 60 * 1);
690
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), $_specialUseFolders, 60 * 60 * 12);
691 691
 	}
692 692
 
693 693
 	/**
@@ -708,15 +708,15 @@  discard block
 block discarded – undo
708 708
 	 * @param string $_profileID the ID of the mailaccount to check for identities, if null current mail-account is used
709 709
 	 * @return array - array(email=>realname)
710 710
 	 */
711
-	function getUserEMailAddresses($_profileID=null)
711
+	function getUserEMailAddresses($_profileID = null)
712 712
 	{
713
-		$acc = Mail\Account::read((!empty($_profileID)?$_profileID:$this->profileID));
713
+		$acc = Mail\Account::read((!empty($_profileID) ? $_profileID : $this->profileID));
714 714
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($acc));
715 715
 		$identities = Mail\Account::identities($acc);
716 716
 
717 717
 		$userEMailAdresses = array($acc['ident_email']=>$acc['ident_realname']);
718 718
 
719
-		foreach($identities as $ik => $ident) {
719
+		foreach ($identities as $ik => $ident) {
720 720
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
721 721
 			$identity = Mail\Account::read_identity($ik);
722 722
 			if (!empty($identity['ident_email']) && !isset($userEMailAdresses[$identity['ident_email']])) $userEMailAdresses[$identity['ident_email']] = $identity['ident_realname'];
@@ -731,19 +731,19 @@  discard block
 block discarded – undo
731 731
 	 * @param boolean $resolve_placeholders wether or not resolve possible placeholders in identities
732 732
 	 * @return array - array(email=>realname)
733 733
 	 */
734
-	static function getAllIdentities($_accountToSearch=null,$resolve_placeholders=false)
734
+	static function getAllIdentities($_accountToSearch = null, $resolve_placeholders = false)
735 735
 	{
736 736
 		$userEMailAdresses = array();
737
-		foreach(Mail\Account::search($only_current_user=($_accountToSearch?$_accountToSearch:true), $just_name=true) as $acc_id => $identity_name)
737
+		foreach (Mail\Account::search($only_current_user = ($_accountToSearch ? $_accountToSearch : true), $just_name = true) as $acc_id => $identity_name)
738 738
 		{
739
-			$acc = Mail\Account::read($acc_id,($_accountToSearch?$_accountToSearch:null));
740
-			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']);
739
+			$acc = Mail\Account::read($acc_id, ($_accountToSearch ? $_accountToSearch : null));
740
+			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']);
741 741
 
742
-			foreach(Mail\Account::identities($acc) as $ik => $ident) {
742
+			foreach (Mail\Account::identities($acc) as $ik => $ident) {
743 743
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
744
-				$identity = Mail\Account::read_identity($ik,$resolve_placeholders);
744
+				$identity = Mail\Account::read_identity($ik, $resolve_placeholders);
745 745
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
746
-				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']);
746
+				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']);
747 747
 			}
748 748
 		}
749 749
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($userEMailAdresses));
@@ -763,9 +763,9 @@  discard block
 block discarded – undo
763 763
 			$account = Mail\Account::read($account);
764 764
 		}
765 765
 		$userEMailAdresses = array();
766
-		foreach(Mail\Account::identities($account, true, 'params') as $ik => $ident) {
766
+		foreach (Mail\Account::identities($account, true, 'params') as $ik => $ident) {
767 767
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
768
-			$identity = Mail\Account::read_identity($ik,true,null,$account);
768
+			$identity = Mail\Account::read_identity($ik, true, null, $account);
769 769
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
770 770
 			// standardIdentity has ident_id==acc_id (as it is done within account->identities)
771 771
 			if (empty($identity['ident_id'])) $identity['ident_id'] = $identity['acc_id'];
@@ -792,9 +792,9 @@  discard block
 block discarded – undo
792 792
 	function getDefaultIdentity()
793 793
 	{
794 794
 		// retrieve the signature accociated with the identity
795
-		$id = $this->getIdentitiesWithAccounts($_accountData=array());
796
-		foreach(Mail\Account::identities($_accountData[$this->profileID] ?
797
-			$this->profileID : $_accountData[$id],false,'ident_id') as $accountData)
795
+		$id = $this->getIdentitiesWithAccounts($_accountData = array());
796
+		foreach (Mail\Account::identities($_accountData[$this->profileID] ?
797
+			$this->profileID : $_accountData[$id], false, 'ident_id') as $accountData)
798 798
 		{
799 799
 			return $accountData;
800 800
 		}
@@ -810,13 +810,13 @@  discard block
 block discarded – undo
810 810
 	{
811 811
 		// account select box
812 812
 		$selectedID = $this->profileID;
813
-		$allAccountData = Mail\Account::search($only_current_user=true, false, null);
813
+		$allAccountData = Mail\Account::search($only_current_user = true, false, null);
814 814
 		if ($allAccountData) {
815
-			$rememberFirst=$selectedFound=null;
815
+			$rememberFirst = $selectedFound = null;
816 816
 			foreach ($allAccountData as $tmpkey => $icServers)
817 817
 			{
818 818
 				if (is_null($rememberFirst)) $rememberFirst = $tmpkey;
819
-				if ($tmpkey == $selectedID) $selectedFound=true;
819
+				if ($tmpkey == $selectedID) $selectedFound = true;
820 820
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($icServers->acc_imap_host));
821 821
 				$host = $icServers->acc_imap_host;
822 822
 				if (empty($host)) continue;
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($identities[$icServers->acc_id]));
825 825
 			}
826 826
 		}
827
-		return ($selectedFound?$selectedID:$rememberFirst);
827
+		return ($selectedFound ? $selectedID : $rememberFirst);
828 828
 	}
829 829
 
830 830
 	/**
@@ -834,7 +834,7 @@  discard block
 block discarded – undo
834 834
 	 * @var boolean $fullString full or false=NamePart only is returned
835 835
 	 * @return string - constructed of identity object data as defined in mailConfig
836 836
 	 */
837
-	static function generateIdentityString($identity, $fullString=true)
837
+	static function generateIdentityString($identity, $fullString = true)
838 838
 	{
839 839
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($identity));
840 840
 		//if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
@@ -845,16 +845,16 @@  discard block
 block discarded – undo
845 845
 		{
846 846
 			case 'email';
847 847
 				//$retData = str_replace('@',' ',$identity->emailAddress).($fullString===true?' <'.$identity->emailAddress.'>':'');
848
-				$retData = $identity['ident_email'].($fullString===true?' <'.$identity['ident_email'].'>':'');
848
+				$retData = $identity['ident_email'].($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
849 849
 				break;
850 850
 			case 'nameNemail';
851
-				$retData = (!empty($identity['ident_realname'])?$identity['ident_realname']:substr_replace($identity['ident_email'],'',strpos($identity['ident_email'],'@'))).($fullString===true?' <'.$identity['ident_email'].'>':'');
851
+				$retData = (!empty($identity['ident_realname']) ? $identity['ident_realname'] : substr_replace($identity['ident_email'], '', strpos($identity['ident_email'], '@'))).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
852 852
 				break;
853 853
 			case 'orgNemail';
854
-				$retData = (!empty($identity['ident_org'])?$identity['ident_org']:substr_replace($identity['ident_email'],'',0,strpos($identity['ident_email'],'@')+1)).($fullString===true?' <'.$identity['ident_email'].'>':'');
854
+				$retData = (!empty($identity['ident_org']) ? $identity['ident_org'] : substr_replace($identity['ident_email'], '', 0, strpos($identity['ident_email'], '@') + 1)).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
855 855
 				break;
856 856
 			default:
857
-				$retData = $identity['ident_realname'].(!empty($identity['ident_org'])?' '.$identity['ident_org']:'').($fullString===true?' <'.$identity['ident_email'].'>':'');
857
+				$retData = $identity['ident_realname'].(!empty($identity['ident_org']) ? ' '.$identity['ident_org'] : '').($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
858 858
 		}
859 859
 		return $retData;
860 860
 	}
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
 	 */
880 880
 	function reopen($_foldername)
881 881
 	{
882
-		if (self::$debugTimes) $starttime = microtime (true);
882
+		if (self::$debugTimes) $starttime = microtime(true);
883 883
 
884 884
 		//error_log(__METHOD__.' ('.__LINE__.') '."('$_foldername') ".function_backtrace());
885 885
 		// TODO: trying to reduce traffic to the IMAP Server here, introduces problems with fetching the bodies of
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 			}
895 895
 			$folderOpened = $_foldername;
896 896
 		//}
897
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'Folder:'.$_foldername,__METHOD__.' ('.__LINE__.') ');
897
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'Folder:'.$_foldername, __METHOD__.' ('.__LINE__.') ');
898 898
 	}
899 899
 
900 900
 
@@ -905,15 +905,15 @@  discard block
 block discarded – undo
905 905
 	 * @throws Horde_Imap_Client_Exception on connection error or authentication failure
906 906
 	 * @throws InvalidArgumentException on missing credentials
907 907
 	 */
908
-	function openConnection($_icServerID=0)
908
+	function openConnection($_icServerID = 0)
909 909
 	{
910 910
 		//error_log( "-------------------------->open connection ".function_backtrace());
911 911
 		//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.array2string($this->icServer));
912
-		if (self::$debugTimes) $starttime = microtime (true);
913
-		$mailbox=null;
912
+		if (self::$debugTimes) $starttime = microtime(true);
913
+		$mailbox = null;
914 914
 		try
915 915
 		{
916
-			if(isset($this->sessionData['mailbox'])&&$this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
916
+			if (isset($this->sessionData['mailbox']) && $this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
917 917
 			if (empty($mailbox)) $mailbox = $this->icServer->getCurrentMailbox();
918 918
 /*
919 919
 			if (isset(Mail\Imap::$supports_keywords[$_icServerID]))
@@ -940,7 +940,7 @@  discard block
 block discarded – undo
940 940
 			error_log(__METHOD__.' ('.__LINE__.') '."->open connection for Server with profileID:".$_icServerID." trying to examine ($mailbox) failed!".$e->getMessage());
941 941
 			throw new Exception(__METHOD__." failed to ".__METHOD__." on Profile to $_icServerID while trying to examine $mailbox:".$e->getMessage());
942 942
 		}
943
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'ProfileID:'.$_icServerID,__METHOD__.' ('.__LINE__.') ');
943
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'ProfileID:'.$_icServerID, __METHOD__.' ('.__LINE__.') ');
944 944
 	}
945 945
 
946 946
 	/**
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
 		try
962 962
 		{
963 963
 			$this->icServer->getCurrentMailbox();
964
-			if(!$this->icServer->hasCapability('QUOTA')) {
964
+			if (!$this->icServer->hasCapability('QUOTA')) {
965 965
 				$quota = false;
966 966
 				return false;
967 967
 			}
@@ -971,15 +971,15 @@  discard block
 block discarded – undo
971 971
 		{
972 972
 			//error_log(__METHOD__.array2string($e));
973 973
 			//error_log(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
974
-			if ($e->getCode()==102)
974
+			if ($e->getCode() == 102)
975 975
 			{
976
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
977
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
978
-				throw new Exception(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
976
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
977
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
978
+				throw new Exception(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : ''));
979 979
 			}
980 980
 		}
981 981
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($quota));
982
-		if(is_array($quota)) {
982
+		if (is_array($quota)) {
983 983
 			$quota = array(
984 984
 				'usage'	=> $quota['USED'],
985 985
 				'limit'	=> $quota['QMAX'],
@@ -997,10 +997,10 @@  discard block
 block discarded – undo
997 997
 	 *
998 998
 	 * @return int - timeout (either set or default 20/10)
999 999
 	 */
1000
-	static function getTimeOut($_use='IMAP')
1000
+	static function getTimeOut($_use = 'IMAP')
1001 1001
 	{
1002 1002
 		$timeout = $GLOBALS['egw_info']['user']['preferences']['mail']['connectionTimeout'];
1003
-		if (empty($timeout)) $timeout = ($_use=='SIEVE'?10:20); // this is the default value
1003
+		if (empty($timeout)) $timeout = ($_use == 'SIEVE' ? 10 : 20); // this is the default value
1004 1004
 		return $timeout;
1005 1005
 	}
1006 1006
 
@@ -1021,18 +1021,18 @@  discard block
 block discarded – undo
1021 1021
 		if (is_null($nameSpace)) $nameSpace = $this->icServer->getNameSpaceArray();
1022 1022
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($nameSpace));
1023 1023
 		if (is_array($nameSpace)) {
1024
-			foreach($nameSpace as $type => $singleNameSpaceArray)
1024
+			foreach ($nameSpace as $type => $singleNameSpaceArray)
1025 1025
 			{
1026 1026
 				foreach ($singleNameSpaceArray as $singleNameSpace)
1027 1027
 				{
1028 1028
 					$_foldersNameSpace = array();
1029
-					if($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail')||$this->folderExists('INBOX')))
1029
+					if ($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail') || $this->folderExists('INBOX')))
1030 1030
 					{
1031 1031
 						$_foldersNameSpace['prefix_present'] = 'forced';
1032 1032
 						// uw-imap server with mailbox prefix or dovecot maybe
1033
-						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail')?'Mail':(!empty($singleNameSpace['name'])?$singleNameSpace['name']:''));
1033
+						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail') ? 'Mail' : (!empty($singleNameSpace['name']) ? $singleNameSpace['name'] : ''));
1034 1034
 					}
1035
-					elseif($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
1035
+					elseif ($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
1036 1036
 					{
1037 1037
 						$_foldersNameSpace['prefix_present'] = 'forced';
1038 1038
 						// uw-imap server with mailbox prefix or dovecot maybe
@@ -1041,9 +1041,9 @@  discard block
 block discarded – undo
1041 1041
 						$_foldersNameSpace['prefix_present'] = !empty($singleNameSpace['name']);
1042 1042
 						$_foldersNameSpace['prefix'] = $singleNameSpace['name'];
1043 1043
 					}
1044
-					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter']?$singleNameSpace['delimiter']:$delimiter);
1044
+					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter'] ? $singleNameSpace['delimiter'] : $delimiter);
1045 1045
 					$_foldersNameSpace['type'] = $type;
1046
-					$foldersNameSpace[] =$_foldersNameSpace;
1046
+					$foldersNameSpace[] = $_foldersNameSpace;
1047 1047
 				}
1048 1048
 				//echo "############## $type->".print_r($foldersNameSpace[$type],true)." ###################<br>";
1049 1049
 			}
@@ -1061,10 +1061,10 @@  discard block
 block discarded – undo
1061 1061
 	 */
1062 1062
 	function getFolderPrefixFromNamespace($nameSpace, $folderName)
1063 1063
 	{
1064
-		foreach($nameSpace as &$singleNameSpace)
1064
+		foreach ($nameSpace as &$singleNameSpace)
1065 1065
 		{
1066 1066
 			//if (substr($singleNameSpace['prefix'],0,strlen($folderName))==$folderName) return $singleNameSpace['prefix'];
1067
-			if (substr($folderName,0,strlen($singleNameSpace['prefix']))==$singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1067
+			if (substr($folderName, 0, strlen($singleNameSpace['prefix'])) == $singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1068 1068
 		}
1069 1069
 		return "";
1070 1070
 	}
@@ -1075,12 +1075,12 @@  discard block
 block discarded – undo
1075 1075
 	 * @var boolean $_useCache
1076 1076
 	 * @return string the hierarchyDelimiter
1077 1077
 	 */
1078
-	function getHierarchyDelimiter($_useCache=true)
1078
+	function getHierarchyDelimiter($_useCache = true)
1079 1079
 	{
1080 1080
 		static $HierarchyDelimiter = null;
1081
-		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1082
-		if ($_useCache===false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1083
-		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId])&&!empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1081
+		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 24 * 5);
1082
+		if ($_useCache === false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1083
+		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId]) && !empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1084 1084
 		{
1085 1085
 			return $HierarchyDelimiter[$this->icServer->ImapServerId];
1086 1086
 		}
@@ -1090,17 +1090,17 @@  discard block
 block discarded – undo
1090 1090
 			$this->icServer->getCurrentMailbox();
1091 1091
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = $this->icServer->getDelimiter();
1092 1092
 		}
1093
-		catch(\Exception $e)
1093
+		catch (\Exception $e)
1094 1094
 		{
1095
-			if ($e->getCode()==102)
1095
+			if ($e->getCode() == 102)
1096 1096
 			{
1097
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1098
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1097
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1098
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1099 1099
 			}
1100 1100
 			unset($e);
1101 1101
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = '/';
1102 1102
 		}
1103
-		Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),$HierarchyDelimiter, 60*60*24*5);
1103
+		Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), $HierarchyDelimiter, 60 * 60 * 24 * 5);
1104 1104
 		return $HierarchyDelimiter[$this->icServer->ImapServerId];
1105 1105
 	}
1106 1106
 
@@ -1113,7 +1113,7 @@  discard block
 block discarded – undo
1113 1113
 	{
1114 1114
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$this->icServer->ImapServerId.' Connected:'.$this->icServer->_connected);
1115 1115
 		static $_specialUseFolders = null;
1116
-		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);
1116
+		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);
1117 1117
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_trash));
1118 1118
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_sent));
1119 1119
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_draft));
@@ -1121,20 +1121,20 @@  discard block
 block discarded – undo
1121 1121
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1122 1122
 		if (isset($_specialUseFolders[$this->icServer->ImapServerId]) && !empty($_specialUseFolders[$this->icServer->ImapServerId]))
1123 1123
 			return $_specialUseFolders[$this->icServer->ImapServerId];
1124
-		$_specialUseFolders[$this->icServer->ImapServerId]=array();
1124
+		$_specialUseFolders[$this->icServer->ImapServerId] = array();
1125 1125
 		//if (!empty($this->icServer->acc_folder_trash) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]))
1126
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]='Trash';
1126
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash] = 'Trash';
1127 1127
 		//if (!empty($this->icServer->acc_folder_draft) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]))
1128
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]='Drafts';
1128
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft] = 'Drafts';
1129 1129
 		//if (!empty($this->icServer->acc_folder_sent) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]))
1130
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]='Sent';
1130
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent] = 'Sent';
1131 1131
 		//if (!empty($this->icServer->acc_folder_template) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]))
1132
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]='Templates';
1133
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk]='Junk';
1134
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive]='Archive';
1132
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template] = 'Templates';
1133
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk] = 'Junk';
1134
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive] = 'Archive';
1135 1135
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_specialUseFolders));//.'<->'.array2string($this->icServer));
1136 1136
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1137
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$_specialUseFolders, 60*60*24*5);
1137
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $_specialUseFolders, 60 * 60 * 24 * 5);
1138 1138
 		return $_specialUseFolders[$this->icServer->ImapServerId];
1139 1139
 	}
1140 1140
 
@@ -1148,8 +1148,8 @@  discard block
 block discarded – undo
1148 1148
 	function folderIsSelectable($folderToSelect)
1149 1149
 	{
1150 1150
 		$retval = true;
1151
-		if($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect,false,true))) {
1152
-			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']),'noselect')!==false)
1151
+		if ($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect, false, true))) {
1152
+			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']), 'noselect') !== false)
1153 1153
 			{
1154 1154
 				$retval = false;
1155 1155
 			}
@@ -1169,7 +1169,7 @@  discard block
 block discarded – undo
1169 1169
 	 *
1170 1170
 	 * @throws Exception
1171 1171
 	 */
1172
-	function _getStatus($folderName,$ignoreStatusCache=false)
1172
+	function _getStatus($folderName, $ignoreStatusCache = false)
1173 1173
 	{
1174 1174
 		static $folderStatus = null;
1175 1175
 		if (!$ignoreStatusCache && isset($folderStatus[$this->icServer->ImapServerId][$folderName]))
@@ -1179,11 +1179,11 @@  discard block
 block discarded – undo
1179 1179
 		}
1180 1180
 		try
1181 1181
 		{
1182
-			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName,$ignoreStatusCache);
1182
+			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName, $ignoreStatusCache);
1183 1183
 		}
1184 1184
 		catch (\Exception $e)
1185 1185
 		{
1186
-			throw new Exception(__METHOD__.' ('.__LINE__.') '." failed for $folderName with error:".$e->getMessage().($e->details?', '.$e->details:''));
1186
+			throw new Exception(__METHOD__.' ('.__LINE__.') '." failed for $folderName with error:".$e->getMessage().($e->details ? ', '.$e->details : ''));
1187 1187
 		}
1188 1188
 		return $folderStatus[$this->icServer->ImapServerId][$folderName];
1189 1189
 	}
@@ -1199,10 +1199,10 @@  discard block
 block discarded – undo
1199 1199
 	 * @param fetchSubscribedInfo bool fetch Subscribed Info on folder
1200 1200
 	 * @return array
1201 1201
 	 */
1202
-	function getFolderStatus($_folderName,$ignoreStatusCache=false,$basicInfoOnly=false,$fetchSubscribedInfo=true)
1202
+	function getFolderStatus($_folderName, $ignoreStatusCache = false, $basicInfoOnly = false, $fetchSubscribedInfo = true)
1203 1203
 	{
1204 1204
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." called with:$_folderName,$ignoreStatusCache,$basicInfoOnly");
1205
-		if (!is_string($_folderName) || empty($_folderName)||(isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID])))
1205
+		if (!is_string($_folderName) || empty($_folderName) || (isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID])))
1206 1206
 		{
1207 1207
 			// something is wrong. Do not proceed. either no folder or profile is marked as defunct for this request
1208 1208
 			return false;
@@ -1213,7 +1213,7 @@  discard block
 block discarded – undo
1213 1213
 		{
1214 1214
 			$folderInfoCache = $folderBasicInfo[$this->profileID];
1215 1215
 		}
1216
-		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache==false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1216
+		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache == false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1217 1217
 		$retValue = array();
1218 1218
 		$retValue['subscribed'] = false;
1219 1219
 /*
@@ -1234,41 +1234,41 @@  discard block
 block discarded – undo
1234 1234
 			{
1235 1235
 				//error_log(__METHOD__.array2string($e));
1236 1236
 				//error_log(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
1237
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1238
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1239
-				throw new Exception(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
1237
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1238
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1239
+				throw new Exception(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : ''));
1240 1240
 			}
1241 1241
 			//error_log(__METHOD__.' ('.__LINE__.') '.$_folderName.' '.array2string($ret));
1242 1242
 			if (is_array($ret))
1243 1243
 			{
1244 1244
 				$retkeys = array_keys($ret);
1245
-				if ($retkeys[0]==$_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1245
+				if ($retkeys[0] == $_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1246 1246
 			}
1247 1247
 			else
1248 1248
 			{
1249
-				$folderInfoCache[$_folderName]=false;
1249
+				$folderInfoCache[$_folderName] = false;
1250 1250
 			}
1251 1251
 		}
1252 1252
 		$folderInfo = $folderInfoCache[$_folderName];
1253 1253
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($folderInfo).'->'.function_backtrace());
1254
-		if($ignoreStatusCache||!$folderInfo|| !is_array($folderInfo)) {
1254
+		if ($ignoreStatusCache || !$folderInfo || !is_array($folderInfo)) {
1255 1255
 			try
1256 1256
 			{
1257
-				$folderInfo = $this->_getStatus($_folderName,$ignoreStatusCache);
1257
+				$folderInfo = $this->_getStatus($_folderName, $ignoreStatusCache);
1258 1258
 			}
1259 1259
 			catch (\Exception $e)
1260 1260
 			{
1261 1261
 				//error_log(__METHOD__.array2string($e));
1262
-				error_log(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
1263
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1264
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1262
+				error_log(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : '')/*.function_backtrace()*/);
1263
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1264
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1265 1265
 				//throw new Exception(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
1266
-				$folderInfo=null;
1266
+				$folderInfo = null;
1267 1267
 			}
1268 1268
 			if (!is_array($folderInfo))
1269 1269
 			{
1270 1270
 				// no folder info, but there is a status returned for the folder: something is wrong, try to cope with it
1271
-				$folderInfo = is_array($folderInfo)?$folderInfo:array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1271
+				$folderInfo = is_array($folderInfo) ? $folderInfo : array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1272 1272
 					'ATTRIBUTES' => '');
1273 1273
 				if (!isset($folderInfo['HIERACHY_DELIMITER']) || empty($folderInfo['HIERACHY_DELIMITER']) || (isset($folderInfo['delimiter']) && empty($folderInfo['delimiter'])))
1274 1274
 				{
@@ -1280,24 +1280,24 @@  discard block
 block discarded – undo
1280 1280
 		#if(!is_array($folderInfo)) {
1281 1281
 		#	return false;
1282 1282
 		#}
1283
-		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER']?$folderInfo['HIERACHY_DELIMITER']:$folderInfo['delimiter']);
1284
-		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES']?$folderInfo['ATTRIBUTES']:$folderInfo['attributes']);
1285
-		$shortNameParts			= explode($retValue['delimiter'], $_folderName);
1283
+		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER'] ? $folderInfo['HIERACHY_DELIMITER'] : $folderInfo['delimiter']);
1284
+		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES'] ? $folderInfo['ATTRIBUTES'] : $folderInfo['attributes']);
1285
+		$shortNameParts = explode($retValue['delimiter'], $_folderName);
1286 1286
 		$retValue['shortName']		= array_pop($shortNameParts);
1287 1287
 		$retValue['displayName']	= $_folderName;
1288
-		$retValue['shortDisplayName']	= $retValue['shortName'];
1289
-		if(strtoupper($retValue['shortName']) == 'INBOX') {
1290
-			$retValue['displayName']	= lang('INBOX');
1291
-			$retValue['shortDisplayName']	= lang('INBOX');
1288
+		$retValue['shortDisplayName'] = $retValue['shortName'];
1289
+		if (strtoupper($retValue['shortName']) == 'INBOX') {
1290
+			$retValue['displayName'] = lang('INBOX');
1291
+			$retValue['shortDisplayName'] = lang('INBOX');
1292 1292
 		}
1293 1293
 		// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
1294
-		elseif (in_array($retValue['shortName'],self::$autoFolders))
1294
+		elseif (in_array($retValue['shortName'], self::$autoFolders))
1295 1295
 		{
1296 1296
 			$retValue['displayName'] = $retValue['shortDisplayName'] = lang($retValue['shortName']);
1297 1297
 		}
1298
-		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName]=$retValue;
1298
+		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName] = $retValue;
1299 1299
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.$_folderName.array2string($retValue['attributes']));
1300
-		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']),'noselect')!==false))
1300
+		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']), 'noselect') !== false))
1301 1301
 		{
1302 1302
 			return $retValue;
1303 1303
 		}
@@ -1310,12 +1310,12 @@  discard block
 block discarded – undo
1310 1310
 		if (is_null($nameSpace) || empty($nameSpace[$this->profileID])) $nameSpace[$this->profileID] = $this->_getNameSpaces();
1311 1311
 		if (!empty($nameSpace[$this->profileID]))
1312 1312
 		{
1313
-			$nsNoPersonal=array();
1314
-			foreach($nameSpace[$this->profileID] as &$ns)
1313
+			$nsNoPersonal = array();
1314
+			foreach ($nameSpace[$this->profileID] as &$ns)
1315 1315
 			{
1316
-				if ($ns['type']!='personal') $nsNoPersonal[]=$ns;
1316
+				if ($ns['type'] != 'personal') $nsNoPersonal[] = $ns;
1317 1317
 			}
1318
-			$nameSpace[$this->profileID]=$nsNoPersonal;
1318
+			$nameSpace[$this->profileID] = $nsNoPersonal;
1319 1319
 		}
1320 1320
 		if (is_null($prefix) || empty($prefix[$this->profileID]) || empty($prefix[$this->profileID][$_folderName])) $prefix[$this->profileID][$_folderName] = $this->getFolderPrefixFromNamespace($nameSpace[$this->profileID], $_folderName);
1321 1321
 
@@ -1324,34 +1324,34 @@  discard block
 block discarded – undo
1324 1324
 			$subscribedFolders[$this->profileID] = $this->icServer->listSubscribedMailboxes();
1325 1325
 		}
1326 1326
 
1327
-		if($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName,$subscribedFolders[$this->profileID])) {
1327
+		if ($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName, $subscribedFolders[$this->profileID])) {
1328 1328
 			$retValue['subscribed'] = true;
1329 1329
 		}
1330 1330
 
1331 1331
 		try
1332 1332
 		{
1333 1333
 			//$folderStatus = $this->_getStatus($_folderName,$ignoreStatusCache);
1334
-			$folderStatus = $this->getMailBoxCounters($_folderName,false);
1335
-			$retValue['messages']		= $folderStatus['MESSAGES'];
1334
+			$folderStatus = $this->getMailBoxCounters($_folderName, false);
1335
+			$retValue['messages'] = $folderStatus['MESSAGES'];
1336 1336
 			$retValue['recent']		= $folderStatus['RECENT'];
1337
-			$retValue['uidnext']		= $folderStatus['UIDNEXT'];
1338
-			$retValue['uidvalidity']	= $folderStatus['UIDVALIDITY'];
1337
+			$retValue['uidnext'] = $folderStatus['UIDNEXT'];
1338
+			$retValue['uidvalidity'] = $folderStatus['UIDVALIDITY'];
1339 1339
 			$retValue['unseen']		= $folderStatus['UNSEEN'];
1340 1340
 			if (//$retValue['unseen']==0 &&
1341 1341
 				(isset($this->mailPreferences['trustServersUnseenInfo']) && // some servers dont serve the UNSEEN information
1342
-				$this->mailPreferences['trustServersUnseenInfo']==false) ||
1342
+				$this->mailPreferences['trustServersUnseenInfo'] == false) ||
1343 1343
 				(isset($this->mailPreferences['trustServersUnseenInfo']) &&
1344
-				$this->mailPreferences['trustServersUnseenInfo']==2 &&
1345
-				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName,$prefix[$this->profileID][$_folderName]) !== false)
1344
+				$this->mailPreferences['trustServersUnseenInfo'] == 2 &&
1345
+				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName, $prefix[$this->profileID][$_folderName]) !== false)
1346 1346
 			)
1347 1347
 			{
1348 1348
 				//error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($prefix,true).' TS:'.$this->mailPreferences['trustServersUnseenInfo']);
1349 1349
 				// we filter for the combined status of unseen and undeleted, as this is what we show in list
1350 1350
 				try
1351 1351
 				{
1352
-					$byUid=true;
1353
-					$_reverse=1;
1354
-					$sortResult = $this->getSortedList($_folderName, $_sort=0, $_reverse, array('status'=>array('UNSEEN','UNDELETED')),$byUid,false);
1352
+					$byUid = true;
1353
+					$_reverse = 1;
1354
+					$sortResult = $this->getSortedList($_folderName, $_sort = 0, $_reverse, array('status'=>array('UNSEEN', 'UNDELETED')), $byUid, false);
1355 1355
 					$retValue['unseen'] = $sortResult['count'];
1356 1356
 				}
1357 1357
 				catch (\Exception $ee)
@@ -1362,7 +1362,7 @@  discard block
 block discarded – undo
1362 1362
 		}
1363 1363
 		catch (\Exception $e)
1364 1364
 		{
1365
-			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(),true));
1365
+			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(), true));
1366 1366
 		}
1367 1367
 
1368 1368
 		return $retValue;
@@ -1381,9 +1381,9 @@  discard block
 block discarded – undo
1381 1381
 		try {
1382 1382
 			$arr = $headers->toArray();
1383 1383
 		}
1384
-		catch(\Horde_Idna_Exception $e) {
1384
+		catch (\Horde_Idna_Exception $e) {
1385 1385
 			$arr = array();
1386
-			foreach($headers as $header)
1386
+			foreach ($headers as $header)
1387 1387
 			{
1388 1388
 				try {
1389 1389
 					$val = $header->sendEncode();
@@ -1412,7 +1412,7 @@  discard block
 block discarded – undo
1412 1412
 	 * @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))
1413 1413
 	 * @return array result as array(header=>array,total=>int,first=>int,last=>int)
1414 1414
 	 */
1415
-	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly=null, $_cacheResult=true, $_fetchPreviews=false)
1415
+	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly = null, $_cacheResult = true, $_fetchPreviews = false)
1416 1416
 	{
1417 1417
 		//self::$debug=true;
1418 1418
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.function_backtrace());
@@ -1425,7 +1425,7 @@  discard block
 block discarded – undo
1425 1425
 		$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
1426 1426
 		#print "<pre>";
1427 1427
 		#$this->icServer->setDebug(true);
1428
-		$total=0;
1428
+		$total = 0;
1429 1429
 		if ($_thisUIDOnly === null)
1430 1430
 		{
1431 1431
 			if (($_startMessage || $_numberOfMessages) && !isset($_filter['range']))
@@ -1438,24 +1438,24 @@  discard block
 block discarded – undo
1438 1438
 				//$_filter['range'] ="$_startMessage:*";
1439 1439
 			}
1440 1440
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_sort, $reverse, ".array2string($_filter).", $rByUid");
1441
-			if (self::$debug||self::$debugTimes) $starttime = microtime (true);
1441
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1442 1442
 			//see this example below for a 12 week datefilter (since)
1443 1443
 			//$_filter = array('status'=>array('UNDELETED'),'type'=>"SINCE",'string'=> date("d-M-Y", $starttime-(3600*24*7*12)));
1444 1444
 			$_sortResult = $this->getSortedList($_folderName, $_sort, $reverse, $_filter, $rByUid, $_cacheResult);
1445 1445
 			$sortResult = $_sortResult['match']->ids;
1446 1446
 			//$modseq = $_sortResult['modseq'];
1447 1447
 			//error_log(__METHOD__.' ('.__LINE__.') '.'Modsequence:'.$modseq);
1448
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly),__METHOD__.' ('.__LINE__.') ');
1448
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly), __METHOD__.' ('.__LINE__.') ');
1449 1449
 
1450 1450
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1451 1451
 			#$this->icServer->setDebug(false);
1452 1452
 			#print "</pre>";
1453 1453
 			// nothing found
1454
-			if(!is_array($sortResult) || empty($sortResult)) {
1454
+			if (!is_array($sortResult) || empty($sortResult)) {
1455 1455
 				$retValue = array();
1456 1456
 				$retValue['info']['total']	= 0;
1457 1457
 				$retValue['info']['first']	= 0;
1458
-				$retValue['info']['last']	= 0;
1458
+				$retValue['info']['last'] = 0;
1459 1459
 				return $retValue;
1460 1460
 			}
1461 1461
 
@@ -1463,54 +1463,54 @@  discard block
 block discarded – undo
1463 1463
 			#_debug_array($sortResult);
1464 1464
 			#_debug_array(array_slice($sortResult, -5, -2));
1465 1465
 			//error_log("REVERSE: $reverse");
1466
-			if($reverse === true) {
1467
-				if  ($_startMessage<=$total)
1466
+			if ($reverse === true) {
1467
+				if ($_startMessage <= $total)
1468 1468
 				{
1469
-					$startMessage = $_startMessage-1;
1469
+					$startMessage = $_startMessage - 1;
1470 1470
 				}
1471 1471
 				else
1472 1472
 				{
1473 1473
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1474
-					if ($_startMessage+$_numberOfMessages>$total)
1474
+					if ($_startMessage + $_numberOfMessages > $total)
1475 1475
 					{
1476
-						$numberOfMessages = $total%$_numberOfMessages;
1476
+						$numberOfMessages = $total % $_numberOfMessages;
1477 1477
 						//$numberOfMessages = abs($_startMessage-$total-1);
1478
-						if ($numberOfMessages>0 && $numberOfMessages<=$_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1478
+						if ($numberOfMessages > 0 && $numberOfMessages <= $_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1479 1479
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1480 1480
 					}
1481
-					$startMessage=($total-$_numberOfMessages)-1;
1481
+					$startMessage = ($total - $_numberOfMessages) - 1;
1482 1482
 					//$retValue['info']['first'] = $startMessage;
1483 1483
 					//$retValue['info']['last'] = $total;
1484 1484
 
1485 1485
 				}
1486
-				if ($startMessage+$_numberOfMessages>$total)
1486
+				if ($startMessage + $_numberOfMessages > $total)
1487 1487
 				{
1488
-					$_numberOfMessages = $_numberOfMessages-($total-($startMessage+$_numberOfMessages));
1488
+					$_numberOfMessages = $_numberOfMessages - ($total - ($startMessage + $_numberOfMessages));
1489 1489
 					//$retValue['info']['first'] = $startMessage;
1490 1490
 					//$retValue['info']['last'] = $total;
1491 1491
 				}
1492
-				if($startMessage > 0) {
1493
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+$startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1494
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+$startMessage), -$startMessage);
1492
+				if ($startMessage > 0) {
1493
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + $startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1494
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + $startMessage), -$startMessage);
1495 1495
 				} else {
1496
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+($_startMessage-1))).', AllTheRest, Number of Messages:'.count($sortResult));
1497
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+($_startMessage-1)));
1496
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + ($_startMessage - 1))).', AllTheRest, Number of Messages:'.count($sortResult));
1497
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + ($_startMessage - 1)));
1498 1498
 				}
1499 1499
 				$sortResult = array_reverse($sortResult);
1500 1500
 			} else {
1501
-				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage-1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1502
-				$sortResult = array_slice($sortResult, $_startMessage-1, $_numberOfMessages);
1501
+				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage - 1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1502
+				$sortResult = array_slice($sortResult, $_startMessage - 1, $_numberOfMessages);
1503 1503
 			}
1504 1504
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1505 1505
 		}
1506 1506
 		else
1507 1507
 		{
1508
-			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly:(array)$_thisUIDOnly);
1508
+			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly : (array)$_thisUIDOnly);
1509 1509
 		}
1510 1510
 
1511 1511
 
1512 1512
 		// fetch the data for the selected messages
1513
-		if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1513
+		if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1514 1514
 		try
1515 1515
 		{
1516 1516
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -1519,22 +1519,22 @@  discard block
 block discarded – undo
1519 1519
 			$fquery = new Horde_Imap_Client_Fetch_Query();
1520 1520
 
1521 1521
 			// Pre-cache the headers we want, 'fetchHeaders' is a label into the cache
1522
-			$fquery->headers('fetchHeaders',array(
1523
-				'DISPOSITION-NOTIFICATION-TO','RETURN-RECEIPT-TO','X-CONFIRM-READING-TO',
1524
-				'DATE','SUBJECT','FROM','TO','CC','REPLY-TO',
1522
+			$fquery->headers('fetchHeaders', array(
1523
+				'DISPOSITION-NOTIFICATION-TO', 'RETURN-RECEIPT-TO', 'X-CONFIRM-READING-TO',
1524
+				'DATE', 'SUBJECT', 'FROM', 'TO', 'CC', 'REPLY-TO',
1525 1525
 				'X-PRIORITY'
1526
-			),array(
1526
+			), array(
1527 1527
 				// Cache headers, we'll look at them below
1528
-				'cache' => true,//$_cacheResult,
1528
+				'cache' => true, //$_cacheResult,
1529 1529
 				// Set peek so messages are not flagged as read
1530 1530
 				'peek' => true
1531 1531
 			));
1532 1532
 			$fquery->size();
1533 1533
 			$fquery->structure();
1534 1534
 			$fquery->flags();
1535
-			$fquery->imapDate();// needed to ensure getImapDate fetches the internaldate, not the current time
1535
+			$fquery->imapDate(); // needed to ensure getImapDate fetches the internaldate, not the current time
1536 1536
 			// if $_fetchPreviews is activated fetch part of the messages too
1537
-			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true,'length'=>((int)$_fetchPreviews<5000?5000:$_fetchPreviews),'start'=>0));
1537
+			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true, 'length'=>((int)$_fetchPreviews < 5000 ? 5000 : $_fetchPreviews), 'start'=>0));
1538 1538
 			$headersNew = $this->icServer->fetch($_folderName, $fquery, array(
1539 1539
 				'ids' => $uidsToFetch,
1540 1540
 			));
@@ -1545,9 +1545,9 @@  discard block
 block discarded – undo
1545 1545
 			$headersNew = array();
1546 1546
 			$sortResult = array();
1547 1547
 		}
1548
-		if (self::$debug||self::$debugTimes)
1548
+		if (self::$debug || self::$debugTimes)
1549 1549
 		{
1550
-			self::logRunTimes($starttime,null,'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter),__METHOD__.' ('.__LINE__.') ');
1550
+			self::logRunTimes($starttime, null, 'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter), __METHOD__.' ('.__LINE__.') ');
1551 1551
 			if (self::$debug)
1552 1552
 			{
1553 1553
 				$queryString = implode(',', $sortResult);
@@ -1557,27 +1557,27 @@  discard block
 block discarded – undo
1557 1557
 
1558 1558
 		$cnt = 0;
1559 1559
 
1560
-		foreach((array)$sortResult as $uid) {
1560
+		foreach ((array)$sortResult as $uid) {
1561 1561
 			$sortOrder[$uid] = $cnt++;
1562 1562
 		}
1563 1563
 
1564 1564
 		$count = 0;
1565 1565
 		if (is_object($headersNew)) {
1566
-			if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1567
-			foreach($headersNew->ids() as $id) {
1566
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1567
+			foreach ($headersNew->ids() as $id) {
1568 1568
 				$_headerObject = $headersNew->get($id);
1569 1569
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject));
1570 1570
 				$headerObject = array();
1571 1571
 				$bodyPreview = null;
1572
-				$uid = $headerObject['UID']= ($_headerObject->getUid()?$_headerObject->getUid():$id);
1572
+				$uid = $headerObject['UID'] = ($_headerObject->getUid() ? $_headerObject->getUid() : $id);
1573 1573
 				$headerObject['MSG_NUM'] = $_headerObject->getSeq();
1574 1574
 				$headerObject['SIZE'] = $_headerObject->getSize();
1575 1575
 				$headerObject['INTERNALDATE'] = $_headerObject->getImapDate();
1576 1576
 
1577 1577
 					// Get already cached headers, 'fetchHeaders' is a label matchimg above
1578
-				$headerForPrio = self::headers2array($_headerObject->getHeaders('fetchHeaders',Horde_Imap_Client_Data_Fetch::HEADER_PARSE));
1578
+				$headerForPrio = self::headers2array($_headerObject->getHeaders('fetchHeaders', Horde_Imap_Client_Data_Fetch::HEADER_PARSE));
1579 1579
 				// Try to fetch header with key='' as some servers might have no fetchHeaders index. e.g. yandex.com
1580
-				if (empty($headerForPrio)) $headerForPrio = self::headers2array($_headerObject->getHeaders('',Horde_Imap_Client_Data_Fetch::HEADER_PARSE));
1580
+				if (empty($headerForPrio)) $headerForPrio = self::headers2array($_headerObject->getHeaders('', Horde_Imap_Client_Data_Fetch::HEADER_PARSE));
1581 1581
 				//fetch the fullMsg part if all conditions match to be available in case $_headerObject->getHeaders returns
1582 1582
 				//nothing worthwhile (as it does for googlemail accounts, when preview is switched on
1583 1583
 				if ($_fetchPreviews)
@@ -1585,16 +1585,16 @@  discard block
 block discarded – undo
1585 1585
 					// on enabled preview $bodyPreview is needed lateron. fetched here, for fallback-reasons
1586 1586
 					// in case of failed Header-Retrieval
1587 1587
 					$bodyPreview = $_headerObject->getFullMsg();
1588
-					if (empty($headerForPrio)||(is_array($headerForPrio)&&count($headerForPrio)===1&&$headerForPrio['']))
1588
+					if (empty($headerForPrio) || (is_array($headerForPrio) && count($headerForPrio) === 1 && $headerForPrio['']))
1589 1589
 					{
1590 1590
 						$length = strpos($bodyPreview, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
1591
-						if ($length===false) $length = strlen($bodyPreview);
1592
-						$headerForPrio = self::headers2array(Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0,$length)));
1591
+						if ($length === false) $length = strlen($bodyPreview);
1592
+						$headerForPrio = self::headers2array(Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0, $length)));
1593 1593
 					}
1594 1594
 				}
1595 1595
 				$headerForPrio = array_change_key_case($headerForPrio, CASE_UPPER);
1596 1596
 				if (self::$debug) {
1597
-					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'));
1597
+					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'));
1598 1598
 					error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerForPrio));
1599 1599
 				}
1600 1600
 				// message deleted from server but cache still reporting its existence ; may happen on QRESYNC with No permanent modsequences
@@ -1603,22 +1603,22 @@  discard block
 block discarded – undo
1603 1603
 					$total--;
1604 1604
 					continue;
1605 1605
 				}
1606
-				if ( isset($headerForPrio['DISPOSITION-NOTIFICATION-TO']) ) {
1606
+				if (isset($headerForPrio['DISPOSITION-NOTIFICATION-TO'])) {
1607 1607
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['DISPOSITION-NOTIFICATION-TO']));
1608
-				} else if ( isset($headerForPrio['RETURN-RECEIPT-TO']) ) {
1608
+				} else if (isset($headerForPrio['RETURN-RECEIPT-TO'])) {
1609 1609
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['RETURN-RECEIPT-TO']));
1610
-				} else if ( isset($headerForPrio['X-CONFIRM-READING-TO']) ) {
1610
+				} else if (isset($headerForPrio['X-CONFIRM-READING-TO'])) {
1611 1611
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['X-CONFIRM-READING-TO']));
1612 1612
 				} /*else $sent_not = "";*/
1613 1613
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1614 1614
 				$headerObject['DATE'] = $headerForPrio['DATE'];
1615
-				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT'])?$headerForPrio['SUBJECT'][0]:$headerForPrio['SUBJECT']);
1616
-				$headerObject['FROM'] = (array)($headerForPrio['FROM']?$headerForPrio['FROM']:($headerForPrio['REPLY-TO']?$headerForPrio['REPLY-TO']:$headerForPrio['RETURN-PATH']));
1615
+				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT']) ? $headerForPrio['SUBJECT'][0] : $headerForPrio['SUBJECT']);
1616
+				$headerObject['FROM'] = (array)($headerForPrio['FROM'] ? $headerForPrio['FROM'] : ($headerForPrio['REPLY-TO'] ? $headerForPrio['REPLY-TO'] : $headerForPrio['RETURN-PATH']));
1617 1617
 				$headerObject['TO'] = (array)$headerForPrio['TO'];
1618
-				$headerObject['CC'] = isset($headerForPrio['CC'])?(array)$headerForPrio['CC']:array();
1619
-				$headerObject['REPLY-TO'] = isset($headerForPrio['REPLY-TO'])?(array)$headerForPrio['REPLY-TO']:array();
1620
-				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY'])?$headerForPrio['X-PRIORITY']:null;
1621
-				foreach (array('FROM','TO','CC','REPLY-TO') as $key)
1618
+				$headerObject['CC'] = isset($headerForPrio['CC']) ? (array)$headerForPrio['CC'] : array();
1619
+				$headerObject['REPLY-TO'] = isset($headerForPrio['REPLY-TO']) ? (array)$headerForPrio['REPLY-TO'] : array();
1620
+				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY']) ? $headerForPrio['X-PRIORITY'] : null;
1621
+				foreach (array('FROM', 'TO', 'CC', 'REPLY-TO') as $key)
1622 1622
 				{
1623 1623
 					$address = array();
1624 1624
 					foreach ($headerObject[$key] as $k => $ad)
@@ -1640,13 +1640,13 @@  discard block
 block discarded – undo
1640 1640
 						foreach ($rfcAddr as $_rfcAddr)
1641 1641
 						{
1642 1642
 							if (!$_rfcAddr->valid)	continue; // skip. not a valid address
1643
-							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox,$_rfcAddr->host,$_rfcAddr->personal);
1643
+							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox, $_rfcAddr->host, $_rfcAddr->personal);
1644 1644
 						}
1645 1645
 					}
1646 1646
 					$headerObject[$key] = $address;
1647 1647
 				}
1648 1648
 				$headerObject['FLAGS'] = $_headerObject->getFlags();
1649
-				$headerObject['BODYPREVIEW']=null;
1649
+				$headerObject['BODYPREVIEW'] = null;
1650 1650
 				// this section fetches part of the message-body (if enabled) for some kind of preview
1651 1651
 				// if we fail to succeed, we fall back to the retrieval of the message-body with
1652 1652
 				// fetchPartContents (see below, when we iterate over the structure to determine the
@@ -1658,17 +1658,17 @@  discard block
 block discarded – undo
1658 1658
 					if (empty($bodyPreview)) $bodyPreview = $_headerObject->getFullMsg();
1659 1659
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($bodyPreview));
1660 1660
 					$base = Horde_Mime_Part::parseMessage($bodyPreview);
1661
-					foreach($base->partIterator() as $part)
1661
+					foreach ($base->partIterator() as $part)
1662 1662
 					{
1663 1663
 						//error_log(__METHOD__.__LINE__.'Part:'.$part->getPrimaryType());
1664
-						if (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'text')
1664
+						if (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'text')
1665 1665
 						{
1666 1666
 							$charset = $part->getContentTypeParameter('charset');
1667 1667
 							$buffer = Mail\Html::convertHTMLToText($part->toString(array(
1668
-												'encode' => Horde_Mime_Part::ENCODE_BINARY,	// otherwise we cant recode charset
1668
+												'encode' => Horde_Mime_Part::ENCODE_BINARY, // otherwise we cant recode charset
1669 1669
 											)), $charset, 'utf-8');
1670
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Translation::convert_jsonsafe($buffer),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1671
-						} elseif (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'multipart')
1670
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Translation::convert_jsonsafe($buffer), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1671
+						} elseif (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'multipart')
1672 1672
 						{
1673 1673
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part));
1674 1674
 						}
@@ -1679,12 +1679,12 @@  discard block
 block discarded – undo
1679 1679
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1680 1680
 				//error_log(__METHOD__.' ('.__LINE__.') '.' MimeMap:'.array2string($mailStructureObject->contentTypeMap()));
1681 1681
 				//foreach ($_headerObject->getStructure()->getParts() as $p => $part)
1682
-				$headerObject['ATTACHMENTS']=null;
1683
-				$skipParts=array();
1684
-				$messageMimeType='';
1682
+				$headerObject['ATTACHMENTS'] = null;
1683
+				$skipParts = array();
1684
+				$messageMimeType = '';
1685 1685
 				foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
1686 1686
 				{
1687
-					if ($mime_id==0 || $messageMimeType==='') $messageMimeType = $mime_type;
1687
+					if ($mime_id == 0 || $messageMimeType === '') $messageMimeType = $mime_type;
1688 1688
 					$part = $mailStructureObject->getPart($mime_id);
1689 1689
 					$partdisposition = $part->getDisposition();
1690 1690
 					$partPrimaryType = $part->getPrimaryType();
@@ -1692,16 +1692,16 @@  discard block
 block discarded – undo
1692 1692
 					// drawback here it is talking to the mailserver for each mail thus consuming
1693 1693
 					// more time than expected; so we call this section only when there is no
1694 1694
 					// bodypreview could be found (multipart/....)
1695
-					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW'])&&($partPrimaryType == 'text') &&
1695
+					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW']) && ($partPrimaryType == 'text') &&
1696 1696
 						((intval($mime_id) === 1) || !$mime_id) &&
1697 1697
 						($partdisposition !== 'attachment')) {
1698
-							$_structure=$part;
1699
-							$this->fetchPartContents($uid, $_structure, false,true);
1700
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1701
-							$charSet=Translation::detect_encoding($headerObject['BODYPREVIEW']);
1698
+							$_structure = $part;
1699
+							$this->fetchPartContents($uid, $_structure, false, true);
1700
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1701
+							$charSet = Translation::detect_encoding($headerObject['BODYPREVIEW']);
1702 1702
 							// add line breaks to $bodyParts
1703 1703
 							//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
1704
-							$headerObject['BODYPREVIEW']  = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1704
+							$headerObject['BODYPREVIEW'] = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1705 1705
 							//error_log(__METHOD__.__LINE__.$headerObject['BODYPREVIEW']);
1706 1706
 					}
1707 1707
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType);
@@ -1711,31 +1711,31 @@  discard block
 block discarded – undo
1711 1711
 						// the presence of an cid does not necessarily indicate its inline. it may lack the needed
1712 1712
 						// link to show the image. Considering this: we "list" everything that matches the above criteria
1713 1713
 						// as attachment in order to not loose/miss information on our data
1714
-						$partdisposition='attachment';//($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1714
+						$partdisposition = 'attachment'; //($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1715 1715
 					}
1716
-					if ($mime_type=='message/rfc822')
1716
+					if ($mime_type == 'message/rfc822')
1717 1717
 					{
1718 1718
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
1719
-						foreach($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
1719
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
1720 1720
 					}
1721 1721
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType.' Skip:'.array2string($skipParts));
1722
-					if (array_key_exists($mime_id,$skipParts)) continue;
1723
-					if ($partdisposition=='attachment' ||
1724
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&$mime_type=='image/tiff') || // as we are not able to display tiffs
1725
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&empty($cid)) ||
1726
-						($partdisposition=='inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1722
+					if (array_key_exists($mime_id, $skipParts)) continue;
1723
+					if ($partdisposition == 'attachment' ||
1724
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && $mime_type == 'image/tiff') || // as we are not able to display tiffs
1725
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && empty($cid)) ||
1726
+						($partdisposition == 'inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1727 1727
 					{
1728
-						$headerObject['ATTACHMENTS'][$mime_id]=$part->getAllDispositionParameters();
1729
-						$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=$mime_type;
1730
-						$headerObject['ATTACHMENTS'][$mime_id]['uid']=$uid;
1728
+						$headerObject['ATTACHMENTS'][$mime_id] = $part->getAllDispositionParameters();
1729
+						$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] = $mime_type;
1730
+						$headerObject['ATTACHMENTS'][$mime_id]['uid'] = $uid;
1731 1731
 						$headerObject['ATTACHMENTS'][$mime_id]['cid'] = $cid;
1732
-						$headerObject['ATTACHMENTS'][$mime_id]['partID']=$mime_id;
1732
+						$headerObject['ATTACHMENTS'][$mime_id]['partID'] = $mime_id;
1733 1733
 						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))
1734 1734
 						{
1735
-							$headerObject['ATTACHMENTS'][$mime_id]['name']= $part->getName() ? $part->getName() : lang('forwarded message');
1735
+							$headerObject['ATTACHMENTS'][$mime_id]['name'] = $part->getName() ? $part->getName() : lang('forwarded message');
1736 1736
 						}
1737
-						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'],'winmail.dat') ||
1738
-							$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=='application/ms-tnef')
1737
+						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'], 'winmail.dat') ||
1738
+							$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] == 'application/ms-tnef')
1739 1739
 						{
1740 1740
 							$headerObject['ATTACHMENTS'][$mime_id]['is_winmail'] = true;
1741 1741
 						}
@@ -1750,68 +1750,68 @@  discard block
 block discarded – undo
1750 1750
 				if (empty($headerObject['UID'])) continue;
1751 1751
 				//$uid = ($rByUid ? $headerObject['UID'] : $headerObject['MSG_NUM']);
1752 1752
 				// make dates like "Mon, 23 Apr 2007 10:11:06 UT" working with strtotime
1753
-				if(substr($headerObject['DATE'],-2) === 'UT') {
1753
+				if (substr($headerObject['DATE'], -2) === 'UT') {
1754 1754
 					$headerObject['DATE'] .= 'C';
1755 1755
 				}
1756
-				if(substr($headerObject['INTERNALDATE'],-2) === 'UT') {
1756
+				if (substr($headerObject['INTERNALDATE'], -2) === 'UT') {
1757 1757
 					$headerObject['INTERNALDATE'] .= 'C';
1758 1758
 				}
1759 1759
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$headerObject['SUBJECT'].'->'.$headerObject['DATE'].'<->'.$headerObject['INTERNALDATE'] .'#');
1760 1760
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$this->decode_subject($headerObject['SUBJECT']).'->'.$headerObject['DATE']);
1761
-				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][]=$a;}
1762
-				$retValue['header'][$sortOrder[$uid]]['subject']	= $this->decode_subject($headerObject['SUBJECT']);
1763
-				$retValue['header'][$sortOrder[$uid]]['size'] 		= $headerObject['SIZE'];
1764
-				$retValue['header'][$sortOrder[$uid]]['date']		= self::_strtotime(($headerObject['DATE']&&!($headerObject['DATE']=='NIL')?$headerObject['DATE']:$headerObject['INTERNALDATE']),'ts',true);
1765
-				$retValue['header'][$sortOrder[$uid]]['internaldate']= self::_strtotime($headerObject['INTERNALDATE'],'ts',true);
1766
-				$retValue['header'][$sortOrder[$uid]]['mimetype']	= $messageMimeType;
1767
-				$retValue['header'][$sortOrder[$uid]]['id']		= $headerObject['MSG_NUM'];
1768
-				$retValue['header'][$sortOrder[$uid]]['uid']		= $headerObject['UID'];
1769
-				$retValue['header'][$sortOrder[$uid]]['bodypreview']		= $headerObject['BODYPREVIEW'];
1770
-				$retValue['header'][$sortOrder[$uid]]['priority']		= ($headerObject['PRIORITY']?$headerObject['PRIORITY']:3);
1771
-				$retValue['header'][$sortOrder[$uid]]['smimeType']		= Mail\Smime::getSmimeType($mailStructureObject);
1761
+				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][] = $a; }
1762
+				$retValue['header'][$sortOrder[$uid]]['subject'] = $this->decode_subject($headerObject['SUBJECT']);
1763
+				$retValue['header'][$sortOrder[$uid]]['size'] = $headerObject['SIZE'];
1764
+				$retValue['header'][$sortOrder[$uid]]['date'] = self::_strtotime(($headerObject['DATE'] && !($headerObject['DATE'] == 'NIL') ? $headerObject['DATE'] : $headerObject['INTERNALDATE']), 'ts', true);
1765
+				$retValue['header'][$sortOrder[$uid]]['internaldate'] = self::_strtotime($headerObject['INTERNALDATE'], 'ts', true);
1766
+				$retValue['header'][$sortOrder[$uid]]['mimetype'] = $messageMimeType;
1767
+				$retValue['header'][$sortOrder[$uid]]['id'] = $headerObject['MSG_NUM'];
1768
+				$retValue['header'][$sortOrder[$uid]]['uid'] = $headerObject['UID'];
1769
+				$retValue['header'][$sortOrder[$uid]]['bodypreview'] = $headerObject['BODYPREVIEW'];
1770
+				$retValue['header'][$sortOrder[$uid]]['priority'] = ($headerObject['PRIORITY'] ? $headerObject['PRIORITY'] : 3);
1771
+				$retValue['header'][$sortOrder[$uid]]['smimeType'] = Mail\Smime::getSmimeType($mailStructureObject);
1772 1772
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.array2string($retValue['header'][$sortOrder[$uid]]));
1773 1773
 				if (isset($headerObject['DISPOSITION-NOTIFICATION-TO'])) $retValue['header'][$sortOrder[$uid]]['disposition-notification-to'] = $headerObject['DISPOSITION-NOTIFICATION-TO'];
1774 1774
 				if (is_array($headerObject['FLAGS'])) {
1775
-					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]],self::prepareFlagsArray($headerObject));
1775
+					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]], self::prepareFlagsArray($headerObject));
1776 1776
 				}
1777 1777
 				//error_log(__METHOD__.' ('.__LINE__.') '.$headerObject['SUBJECT'].'->'.array2string($_headerObject->getEnvelope()->__get('from')));
1778
-				if(is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1779
-					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0],true);
1780
-					if (count($headerObject['FROM'])>1)
1778
+				if (is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1779
+					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0], true);
1780
+					if (count($headerObject['FROM']) > 1)
1781 1781
 					{
1782
-						$ki=0;
1783
-						foreach($headerObject['FROM'] as $k => $add)
1782
+						$ki = 0;
1783
+						foreach ($headerObject['FROM'] as $k => $add)
1784 1784
 						{
1785
-							if ($k==0) continue;
1786
-							$retValue['header'][$sortOrder[$uid]]['additional_from_addresses'][$ki] = self::decode_header($add,true);
1785
+							if ($k == 0) continue;
1786
+							$retValue['header'][$sortOrder[$uid]]['additional_from_addresses'][$ki] = self::decode_header($add, true);
1787 1787
 							$ki++;
1788 1788
 						}
1789 1789
 					}
1790 1790
 				}
1791
-				if(is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0]) {
1792
-					$retValue['header'][$sortOrder[$uid]]['reply_to_address'] = self::decode_header($headerObject['REPLY-TO'][0],true);
1791
+				if (is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0]) {
1792
+					$retValue['header'][$sortOrder[$uid]]['reply_to_address'] = self::decode_header($headerObject['REPLY-TO'][0], true);
1793 1793
 				}
1794
-				if(is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1795
-					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0],true);
1796
-					if (count($headerObject['TO'])>1)
1794
+				if (is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1795
+					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0], true);
1796
+					if (count($headerObject['TO']) > 1)
1797 1797
 					{
1798
-						$ki=0;
1799
-						foreach($headerObject['TO'] as $k => $add)
1798
+						$ki = 0;
1799
+						foreach ($headerObject['TO'] as $k => $add)
1800 1800
 						{
1801
-							if ($k==0) continue;
1801
+							if ($k == 0) continue;
1802 1802
 							//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1803
-							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add,true);
1803
+							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add, true);
1804 1804
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1805 1805
 							$ki++;
1806 1806
 						}
1807 1807
 					}
1808 1808
 				}
1809
-				if(is_array($headerObject['CC']) && count($headerObject['CC'])>0) {
1810
-					$ki=0;
1811
-					foreach($headerObject['CC'] as $k => $add)
1809
+				if (is_array($headerObject['CC']) && count($headerObject['CC']) > 0) {
1810
+					$ki = 0;
1811
+					foreach ($headerObject['CC'] as $k => $add)
1812 1812
 					{
1813 1813
 						//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1814
-						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add,true);
1814
+						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add, true);
1815 1815
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1816 1816
 						$ki++;
1817 1817
 					}
@@ -1820,27 +1820,27 @@  discard block
 block discarded – undo
1820 1820
 
1821 1821
 				$count++;
1822 1822
 			}
1823
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' fetching Headers and stuff for Folder:'.$_folderName,__METHOD__.' ('.__LINE__.') ');
1823
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' fetching Headers and stuff for Folder:'.$_folderName, __METHOD__.' ('.__LINE__.') ');
1824 1824
 			//self::$debug=false;
1825 1825
 			// sort the messages to the requested displayorder
1826
-			if(is_array($retValue['header'])) {
1826
+			if (is_array($retValue['header'])) {
1827 1827
 				$countMessages = $total;
1828 1828
 				if (isset($_filter['range'])) $countMessages = self::$folderStatusCache[$this->profileID][$_folderName]['messages'];
1829 1829
 				ksort($retValue['header']);
1830 1830
 				$retValue['info']['total']	= $total;
1831 1831
 				//if ($_startMessage>$total) $_startMessage = $total-($count-1);
1832 1832
 				$retValue['info']['first']	= $_startMessage;
1833
-				$retValue['info']['last']	= $_startMessage + $count - 1 ;
1833
+				$retValue['info']['last'] = $_startMessage + $count - 1;
1834 1834
 				return $retValue;
1835 1835
 			} else {
1836 1836
 				$retValue = array();
1837 1837
 				$retValue['info']['total']	= 0;
1838 1838
 				$retValue['info']['first']	= 0;
1839
-				$retValue['info']['last']	= 0;
1839
+				$retValue['info']['last'] = 0;
1840 1840
 				return $retValue;
1841 1841
 			}
1842 1842
 		} else {
1843
-			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew,TRUE));
1843
+			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew, TRUE));
1844 1844
 			$retValue = array();
1845 1845
 			$retValue['info']['total']  = 0;
1846 1846
 			$retValue['info']['first']  = 0;
@@ -1857,17 +1857,17 @@  discard block
 block discarded – undo
1857 1857
 	 */
1858 1858
 	static function prepareFlagsArray($headerObject)
1859 1859
 	{
1860
-		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower',$headerObject['FLAGS']);
1860
+		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower', $headerObject['FLAGS']);
1861 1861
 		$retValue = array();
1862 1862
 		$retValue['recent']		= in_array('\\recent', $headerFlags);
1863 1863
 		$retValue['flagged']	= in_array('\\flagged', $headerFlags);
1864
-		$retValue['answered']	= in_array('\\answered', $headerFlags);
1865
-		$retValue['forwarded']   = in_array('$forwarded', $headerFlags);
1864
+		$retValue['answered'] = in_array('\\answered', $headerFlags);
1865
+		$retValue['forwarded'] = in_array('$forwarded', $headerFlags);
1866 1866
 		$retValue['deleted']	= in_array('\\deleted', $headerFlags);
1867
-		$retValue['seen']		= in_array('\\seen', $headerFlags);
1868
-		$retValue['draft']		= in_array('\\draft', $headerFlags);
1869
-		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags)||in_array('mdnsent', $headerFlags);
1870
-		$retValue['mdnnotsent']	= in_array('$mdnnotsent', $headerFlags)||in_array('mdnnotsent', $headerFlags);
1867
+		$retValue['seen'] = in_array('\\seen', $headerFlags);
1868
+		$retValue['draft'] = in_array('\\draft', $headerFlags);
1869
+		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags) || in_array('mdnsent', $headerFlags);
1870
+		$retValue['mdnnotsent'] = in_array('$mdnnotsent', $headerFlags) || in_array('mdnnotsent', $headerFlags);
1871 1871
 		$retValue['label1']   = in_array('$label1', $headerFlags);
1872 1872
 		$retValue['label2']   = in_array('$label2', $headerFlags);
1873 1873
 		$retValue['label3']   = in_array('$label3', $headerFlags);
@@ -1891,12 +1891,12 @@  discard block
 block discarded – undo
1891 1891
 	 * @param bool $setSession if set to true the session will be populated with the result of the query
1892 1892
 	 * @return mixed bool/array false or array of ids
1893 1893
 	 */
1894
-	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid=true, $setSession=true)
1894
+	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid = true, $setSession = true)
1895 1895
 	{
1896 1896
 		static $cachedFolderStatus = null;
1897 1897
 		// in the past we needed examineMailbox to figure out if the server with the serverID support keywords
1898 1898
 		// this information is filled/provided by examineMailbox; but caching within one request seems o.k.
1899
-		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]) )
1899
+		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]))
1900 1900
 		{
1901 1901
 			$folderStatus = $cachedFolderStatus[$this->profileID][$_folderName] = $this->icServer->examineMailbox($_folderName);
1902 1902
 		}
@@ -1908,29 +1908,29 @@  discard block
 block discarded – undo
1908 1908
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Filter:'.array2string($_filter));
1909 1909
 		$try2useCache = true;
1910 1910
 		static $eMailListContainsDeletedMessages = null;
1911
-		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
1911
+		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
1912 1912
 		// this indicates, that there is no Filter set, and the returned set/subset should not contain DELETED Messages, nor filtered for UNDELETED
1913
-		if ($setSession==true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1913
+		if ($setSession == true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1914 1914
 		{
1915 1915
 			if (self::$debugTimes) $starttime = microtime(true);
1916
-			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);
1917
-			$five=true;
1918
-			$dReverse=1;
1919
-			$deletedMessages = $this->getSortedList($_folderName, 0, $dReverse, array('status'=>array('DELETED')),$five,false);
1916
+			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);
1917
+			$five = true;
1918
+			$dReverse = 1;
1919
+			$deletedMessages = $this->getSortedList($_folderName, 0, $dReverse, array('status'=>array('DELETED')), $five, false);
1920 1920
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') Found DeletedMessages:'.array2string($eMailListContainsDeletedMessages));
1921
-			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] =$deletedMessages['count'];
1922
-			Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),$eMailListContainsDeletedMessages, 60*60*1);
1923
-			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']);
1921
+			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] = $deletedMessages['count'];
1922
+			Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), $eMailListContainsDeletedMessages, 60 * 60 * 1);
1923
+			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']);
1924 1924
 		}
1925 1925
 		$try2useCache = false;
1926 1926
 		//self::$supportsORinQuery[$this->profileID]=true;
1927 1927
 		if (is_null(self::$supportsORinQuery) || !isset(self::$supportsORinQuery[$this->profileID]))
1928 1928
 		{
1929
-			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
1930
-			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID]=true;
1929
+			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
1930
+			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID] = true;
1931 1931
 		}
1932 1932
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_filter).' SupportsOrInQuery:'.self::$supportsORinQuery[$this->profileID]);
1933
-		$filter = $this->createIMAPFilter($_folderName, $_filter,self::$supportsORinQuery[$this->profileID]);
1933
+		$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1934 1934
 		if (self::$debug)
1935 1935
 		{
1936 1936
 			$query_str = $filter->build();
@@ -1938,14 +1938,14 @@  discard block
 block discarded – undo
1938 1938
 		}
1939 1939
 		//_debug_array($filter);
1940 1940
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($filter).'#'.array2string($this->icServer->capability()));
1941
-		if($this->icServer->hasCapability('SORT')) {
1941
+		if ($this->icServer->hasCapability('SORT')) {
1942 1942
 			// when using an orQuery and we sort by date. sort seems to fail on certain servers => ZIMBRA with Horde_Imap_Client
1943 1943
 			// thus we translate the search request from date to Horde_Imap_Client::SORT_SEQUENCE (which should be the same, if
1944 1944
 			// there is no messing with the dates)
1945 1945
 			//if (self::$supportsORinQuery[$this->profileID]&&$_sort=='date'&&$_filter['type']=='quick'&&!empty($_filter['string']))$_sort='INTERNALDATE';
1946 1946
 			if (self::$debug) error_log(__METHOD__." Mailserver has SORT Capability, SortBy: ".array2string($_sort)." Reverse: $_reverse");
1947 1947
 			$sortOrder = $this->_getSortString($_sort, $_reverse);
1948
-			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE,$sortOrder)) $_reverse=false; // as we reversed the result already
1948
+			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE, $sortOrder)) $_reverse = false; // as we reversed the result already
1949 1949
 			if (self::$debug) error_log(__METHOD__." Mailserver runs SORT: SortBy:".array2string($_sort)."->".array2string($sortOrder)." Filter: ".array2string($filter));
1950 1950
 			try
1951 1951
 			{
@@ -1959,24 +1959,24 @@  discard block
 block discarded – undo
1959 1959
 
1960 1960
 			// if there is an Error, we assume that the server is not capable of sorting
1961 1961
 			}
1962
-			catch(\Exception $e)
1962
+			catch (\Exception $e)
1963 1963
 			{
1964 1964
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1965 1965
 				$resultByUid = false;
1966 1966
 				$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
1967
-				if ($_reverse) array_unshift($sortOrder,Horde_Imap_Client::SORT_REVERSE);
1967
+				if ($_reverse) array_unshift($sortOrder, Horde_Imap_Client::SORT_REVERSE);
1968 1968
 				try
1969 1969
 				{
1970 1970
 					$sortResult = $this->icServer->search($_folderName, $filter, array(
1971 1971
 						'sort' => $sortOrder));
1972 1972
 				}
1973
-				catch(\Exception $e)
1973
+				catch (\Exception $e)
1974 1974
 				{
1975 1975
 					error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1976 1976
 					$sortResult = self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'];
1977 1977
 				}
1978 1978
 			}
1979
-			if (self::$debug) error_log(__METHOD__.print_r($sortResult,true));
1979
+			if (self::$debug) error_log(__METHOD__.print_r($sortResult, true));
1980 1980
 		} else {
1981 1981
 			if (self::$debug) error_log(__METHOD__." Mailserver has NO SORT Capability");
1982 1982
 			//$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
@@ -1986,12 +1986,12 @@  discard block
 block discarded – undo
1986 1986
 				$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
1987 1987
 					'sort' => $sortOrder)*/);
1988 1988
 			}
1989
-			catch(\Exception $e)
1989
+			catch (\Exception $e)
1990 1990
 			{
1991 1991
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1992 1992
 				// possible error OR Query. But Horde gives no detailed Info :-(
1993
-				self::$supportsORinQuery[$this->profileID]=false;
1994
-				Cache::setCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),self::$supportsORinQuery,60*60*10);
1993
+				self::$supportsORinQuery[$this->profileID] = false;
1994
+				Cache::setCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), self::$supportsORinQuery, 60 * 60 * 10);
1995 1995
 				if (self::$debug) error_log(__METHOD__.__LINE__." Mailserver seems to have NO OR Capability for Search:".$sortResult->message);
1996 1996
 				$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1997 1997
 				try
@@ -1999,25 +1999,25 @@  discard block
 block discarded – undo
1999 1999
 					$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
2000 2000
 						'sort' => $sortOrder)*/);
2001 2001
 				}
2002
-				catch(\Exception $e)
2002
+				catch (\Exception $e)
2003 2003
 				{
2004 2004
 				}
2005 2005
 			}
2006
-			if(is_array($sortResult['match'])) {
2006
+			if (is_array($sortResult['match'])) {
2007 2007
 					// not sure that this is going so succeed as $sortResult['match'] is a hordeObject
2008 2008
 					sort($sortResult['match'], SORT_NUMERIC);
2009 2009
 			}
2010
-			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
2010
+			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter, true)." ->".print_r($sortResult, true));
2011 2011
 		}
2012 2012
 		if ($setSession)
2013 2013
 		{
2014 2014
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidValidity'] = $folderStatus['UIDVALIDITY'];
2015
-			self::$folderStatusCache[$this->profileID][$_folderName]['messages']	= $folderStatus['MESSAGES'];
2015
+			self::$folderStatusCache[$this->profileID][$_folderName]['messages'] = $folderStatus['MESSAGES'];
2016 2016
 			self::$folderStatusCache[$this->profileID][$_folderName]['deleted']	= $eMailListContainsDeletedMessages[$this->profileID][$_folderName];
2017 2017
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidnext']	= $folderStatus['UIDNEXT'];
2018
-			self::$folderStatusCache[$this->profileID][$_folderName]['filter']	= $_filter;
2018
+			self::$folderStatusCache[$this->profileID][$_folderName]['filter'] = $_filter;
2019 2019
 			self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'] = $sortResult;
2020
-			self::$folderStatusCache[$this->profileID][$_folderName]['sort']	= $_sort;
2020
+			self::$folderStatusCache[$this->profileID][$_folderName]['sort'] = $_sort;
2021 2021
 		}
2022 2022
 		//error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
2023 2023
 		//_debug_array($sortResult['match']->ids);
@@ -2031,12 +2031,12 @@  discard block
 block discarded – undo
2031 2031
 	 * @param bool _reverse wether to add REVERSE to the Sort String or not
2032 2032
 	 * @return the sort sequence for horde search
2033 2033
 	 */
2034
-	function _getSortString($_sort, $_reverse=false)
2034
+	function _getSortString($_sort, $_reverse = false)
2035 2035
 	{
2036
-		$_reverse=false;
2036
+		$_reverse = false;
2037 2037
 		if (is_numeric($_sort))
2038 2038
 		{
2039
-			switch($_sort) {
2039
+			switch ($_sort) {
2040 2040
 				case 2:
2041 2041
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
2042 2042
 					break;
@@ -2058,7 +2058,7 @@  discard block
 block discarded – undo
2058 2058
 		}
2059 2059
 		else
2060 2060
 		{
2061
-			switch(strtoupper($_sort)) {
2061
+			switch (strtoupper($_sort)) {
2062 2062
 				case 'FROMADDRESS':
2063 2063
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
2064 2064
 					break;
@@ -2084,7 +2084,7 @@  discard block
 block discarded – undo
2084 2084
 					break;
2085 2085
 			}
2086 2086
 		}
2087
-		if ($_reverse) array_unshift($retValue,Horde_Imap_Client::SORT_REVERSE);
2087
+		if ($_reverse) array_unshift($retValue, Horde_Imap_Client::SORT_REVERSE);
2088 2088
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.($_reverse?'REVERSE ':'').$_sort.'->'.$retValue);
2089 2089
 		return $retValue;
2090 2090
 	}
@@ -2097,28 +2097,28 @@  discard block
 block discarded – undo
2097 2097
 	 * @param boolean $_supportsOrInQuery wether to use the OR Query on QuickSearch
2098 2098
 	 * @return Horde_Imap_Client_Search_Query the IMAP filter
2099 2099
 	 */
2100
-	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery=true)
2100
+	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery = true)
2101 2101
 	{
2102 2102
 		$imapFilter = new Horde_Imap_Client_Search_Query();
2103 2103
 		$imapFilter->charset('UTF-8');
2104 2104
 
2105 2105
 		//_debug_array($_criterias);
2106
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2107
-		if((!is_array($_criterias) || $_criterias['status']=='any') &&
2106
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias) ? " none -> returning" : array2string($_criterias)));
2107
+		if ((!is_array($_criterias) || $_criterias['status'] == 'any') &&
2108 2108
 			(!isset($_criterias['string']) || empty($_criterias['string'])) &&
2109
-			(!isset($_criterias['range'])|| empty($_criterias['range']) ||
2110
-			( !empty($_criterias['range'])&& ($_criterias['range']!='BETWEEN' && empty($_criterias['date'])||
2111
-			($_criterias['range']=='BETWEEN' && empty($_criterias['since'])&& empty($_criterias['before']))))))
2109
+			(!isset($_criterias['range']) || empty($_criterias['range']) ||
2110
+			(!empty($_criterias['range']) && ($_criterias['range'] != 'BETWEEN' && empty($_criterias['date']) ||
2111
+			($_criterias['range'] == 'BETWEEN' && empty($_criterias['since']) && empty($_criterias['before']))))))
2112 2112
 		{
2113 2113
 			//error_log(__METHOD__.' ('.__LINE__.') returning early Criterias:'.print_r($_criterias, true));
2114
-			$imapFilter->flag('DELETED', $set=false);
2114
+			$imapFilter->flag('DELETED', $set = false);
2115 2115
 			return $imapFilter;
2116 2116
 		}
2117 2117
 		$queryValid = false;
2118 2118
 		// statusQuery MUST be placed first, as search for subject/mailbody and such is
2119 2119
 		// depending on charset. flagSearch is not BUT messes the charset if called afterwards
2120 2120
 		$statusQueryValid = false;
2121
-		foreach((array)$_criterias['status'] as $k => $criteria) {
2121
+		foreach ((array)$_criterias['status'] as $k => $criteria) {
2122 2122
 			$imapStatusFilter = new Horde_Imap_Client_Search_Query();
2123 2123
 			$imapStatusFilter->charset('UTF-8');
2124 2124
 			$criteria = strtoupper($criteria);
@@ -2128,12 +2128,12 @@  discard block
 block discarded – undo
2128 2128
 				case 'FLAGGED':
2129 2129
 				case 'RECENT':
2130 2130
 				case 'SEEN':
2131
-					$imapStatusFilter->flag($criteria, $set=true);
2132
-					$queryValid = $statusQueryValid =true;
2131
+					$imapStatusFilter->flag($criteria, $set = true);
2132
+					$queryValid = $statusQueryValid = true;
2133 2133
 					break;
2134 2134
 				case 'READ':
2135
-					$imapStatusFilter->flag('SEEN', $set=true);
2136
-					$queryValid = $statusQueryValid =true;
2135
+					$imapStatusFilter->flag('SEEN', $set = true);
2136
+					$queryValid = $statusQueryValid = true;
2137 2137
 					break;
2138 2138
 				case 'LABEL1':
2139 2139
 				case 'KEYWORD1':
@@ -2145,38 +2145,38 @@  discard block
 block discarded – undo
2145 2145
 				case 'KEYWORD4':
2146 2146
 				case 'LABEL5':
2147 2147
 				case 'KEYWORD5':
2148
-					$imapStatusFilter->flag(str_ireplace('KEYWORD','$LABEL',$criteria), $set=true);
2149
-					$queryValid = $statusQueryValid =true;
2148
+					$imapStatusFilter->flag(str_ireplace('KEYWORD', '$LABEL', $criteria), $set = true);
2149
+					$queryValid = $statusQueryValid = true;
2150 2150
 					break;
2151 2151
 				case 'NEW':
2152
-					$imapStatusFilter->flag('RECENT', $set=true);
2153
-					$imapStatusFilter->flag('SEEN', $set=false);
2154
-					$queryValid = $statusQueryValid =true;
2152
+					$imapStatusFilter->flag('RECENT', $set = true);
2153
+					$imapStatusFilter->flag('SEEN', $set = false);
2154
+					$queryValid = $statusQueryValid = true;
2155 2155
 					break;
2156 2156
 				case 'OLD':
2157
-					$imapStatusFilter->flag('RECENT', $set=false);
2158
-					$queryValid = $statusQueryValid =true;
2157
+					$imapStatusFilter->flag('RECENT', $set = false);
2158
+					$queryValid = $statusQueryValid = true;
2159 2159
 					break;
2160 2160
 // operate only on system flags
2161 2161
 //        $systemflags = array(
2162 2162
 //            'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'RECENT', 'SEEN'
2163 2163
 //        );
2164 2164
 				case 'UNANSWERED':
2165
-					$imapStatusFilter->flag('ANSWERED', $set=false);
2166
-					$queryValid = $statusQueryValid =true;
2165
+					$imapStatusFilter->flag('ANSWERED', $set = false);
2166
+					$queryValid = $statusQueryValid = true;
2167 2167
 					break;
2168 2168
 				case 'UNDELETED':
2169
-					$imapFilter->flag('DELETED', $set=false);
2169
+					$imapFilter->flag('DELETED', $set = false);
2170 2170
 					$queryValid = true;
2171 2171
 					break;
2172 2172
 				case 'UNFLAGGED':
2173
-					$imapStatusFilter->flag('FLAGGED', $set=false);
2174
-					$queryValid = $statusQueryValid =true;
2173
+					$imapStatusFilter->flag('FLAGGED', $set = false);
2174
+					$queryValid = $statusQueryValid = true;
2175 2175
 					break;
2176 2176
 				case 'UNREAD':
2177 2177
 				case 'UNSEEN':
2178
-					$imapStatusFilter->flag('SEEN', $set=false);
2179
-					$queryValid = $statusQueryValid =true;
2178
+					$imapStatusFilter->flag('SEEN', $set = false);
2179
+					$queryValid = $statusQueryValid = true;
2180 2180
 					break;
2181 2181
 				case 'UNLABEL1':
2182 2182
 				case 'UNKEYWORD1':
@@ -2188,8 +2188,8 @@  discard block
 block discarded – undo
2188 2188
 				case 'UNKEYWORD4':
2189 2189
 				case 'UNLABEL5':
2190 2190
 				case 'UNKEYWORD5':
2191
-					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD','UNLABEL'),'$LABEL',$criteria), $set=false);
2192
-					$queryValid = $statusQueryValid =true;
2191
+					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD', 'UNLABEL'), '$LABEL', $criteria), $set = false);
2192
+					$queryValid = $statusQueryValid = true;
2193 2193
 					break;
2194 2194
 				default:
2195 2195
 					$statusQueryValid = false;
@@ -2205,20 +2205,20 @@  discard block
 block discarded – undo
2205 2205
 		$imapSearchFilter = new Horde_Imap_Client_Search_Query();
2206 2206
 		$imapSearchFilter->charset('UTF-8');
2207 2207
 
2208
-		if(!empty($_criterias['string'])) {
2208
+		if (!empty($_criterias['string'])) {
2209 2209
 			$criteria = strtoupper($_criterias['type']);
2210 2210
 			switch ($criteria) {
2211 2211
 				case 'BYDATE':
2212 2212
 				case 'QUICK':
2213 2213
 				case 'QUICKWITHCC':
2214
-					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not=false);
2214
+					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not = false);
2215 2215
 					//$imapSearchFilter->charset('UTF-8');
2216 2216
 					$imapFilter2 = new Horde_Imap_Client_Search_Query();
2217 2217
 					$imapFilter2->charset('UTF-8');
2218
-					if($this->isSentFolder($_folder)) {
2219
-						$imapFilter2->headerText('TO', $_criterias['string'], $not=false);
2218
+					if ($this->isSentFolder($_folder)) {
2219
+						$imapFilter2->headerText('TO', $_criterias['string'], $not = false);
2220 2220
 					} else {
2221
-						$imapFilter2->headerText('FROM', $_criterias['string'], $not=false);
2221
+						$imapFilter2->headerText('FROM', $_criterias['string'], $not = false);
2222 2222
 					}
2223 2223
 					if ($_supportsOrInQuery)
2224 2224
 					{
@@ -2228,31 +2228,31 @@  discard block
 block discarded – undo
2228 2228
 					{
2229 2229
 						$imapSearchFilter->andSearch($imapFilter2);
2230 2230
 					}
2231
-					if ($_supportsOrInQuery && $criteria=='QUICKWITHCC')
2231
+					if ($_supportsOrInQuery && $criteria == 'QUICKWITHCC')
2232 2232
 					{
2233 2233
 						$imapFilter3 = new Horde_Imap_Client_Search_Query();
2234 2234
 						$imapFilter3->charset('UTF-8');
2235
-						$imapFilter3->headerText('CC', $_criterias['string'], $not=false);
2235
+						$imapFilter3->headerText('CC', $_criterias['string'], $not = false);
2236 2236
 						$imapSearchFilter->orSearch($imapFilter3);
2237 2237
 					}
2238 2238
 					$queryValid = true;
2239 2239
 					break;
2240 2240
 				case 'LARGER':
2241 2241
 				case 'SMALLER':
2242
-					if (strlen(trim($_criterias['string'])) != strlen((float) trim($_criterias['string'])))
2242
+					if (strlen(trim($_criterias['string'])) != strlen((float)trim($_criterias['string'])))
2243 2243
 					{
2244 2244
 						//examine string to evaluate size
2245
-						$unit = strtoupper(trim(substr(trim($_criterias['string']),strlen((float) trim($_criterias['string'])))));
2246
-						$multipleBy = array('KB'=>1024,'K'=>1024,
2247
-											'MB'=>1024*1000,'M'=>1024*1000,
2248
-											'GB'=>1024*1000*1000,'G'=>1024*1000*1000,
2249
-											'TB'=>1024*1000*1000*1000,'T'=>1024*1000*1000*1000);
2250
-						$numberinBytes=(float)$_criterias['string'];
2251
-						if (isset($multipleBy[$unit])) $numberinBytes=(float)$_criterias['string']*$multipleBy[$unit];
2245
+						$unit = strtoupper(trim(substr(trim($_criterias['string']), strlen((float)trim($_criterias['string'])))));
2246
+						$multipleBy = array('KB'=>1024, 'K'=>1024,
2247
+											'MB'=>1024 * 1000, 'M'=>1024 * 1000,
2248
+											'GB'=>1024 * 1000 * 1000, 'G'=>1024 * 1000 * 1000,
2249
+											'TB'=>1024 * 1000 * 1000 * 1000, 'T'=>1024 * 1000 * 1000 * 1000);
2250
+						$numberinBytes = (float)$_criterias['string'];
2251
+						if (isset($multipleBy[$unit])) $numberinBytes = (float)$_criterias['string'] * $multipleBy[$unit];
2252 2252
 						//error_log(__METHOD__.__LINE__.'#'.$_criterias['string'].'->'.(float)$_criterias['string'].'#'.$unit.' ='.$numberinBytes);
2253
-						$_criterias['string']=$numberinBytes;
2253
+						$_criterias['string'] = $numberinBytes;
2254 2254
 					}
2255
-					$imapSearchFilter->size( $_criterias['string'], ($criteria=='LARGER'?true:false), $not=false);
2255
+					$imapSearchFilter->size($_criterias['string'], ($criteria == 'LARGER' ?true:false), $not = false);
2256 2256
 					//$imapSearchFilter->charset('UTF-8');
2257 2257
 					$queryValid = true;
2258 2258
 					break;
@@ -2261,31 +2261,31 @@  discard block
 block discarded – undo
2261 2261
 				case 'CC':
2262 2262
 				case 'BCC':
2263 2263
 				case 'SUBJECT':
2264
-					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not=false);
2264
+					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not = false);
2265 2265
 					//$imapSearchFilter->charset('UTF-8');
2266 2266
 					$queryValid = true;
2267 2267
 					break;
2268 2268
 				case 'BODY':
2269 2269
 				case 'TEXT':
2270
-					$imapSearchFilter->text($_criterias['string'],($criteria=='BODY'?true:false), $not=false);
2270
+					$imapSearchFilter->text($_criterias['string'], ($criteria == 'BODY' ?true:false), $not = false);
2271 2271
 					//$imapSearchFilter->charset('UTF-8');
2272 2272
 					$queryValid = true;
2273 2273
 					break;
2274 2274
 				case 'SINCE':
2275
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2275
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2276 2276
 					$queryValid = true;
2277 2277
 					break;
2278 2278
 				case 'BEFORE':
2279
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2279
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2280 2280
 					$queryValid = true;
2281 2281
 					break;
2282 2282
 				case 'ON':
2283
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2283
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2284 2284
 					$queryValid = true;
2285 2285
 					break;
2286 2286
 			}
2287 2287
 		}
2288
-		if ($statusQueryValid && !$queryValid) $queryValid=true;
2288
+		if ($statusQueryValid && !$queryValid) $queryValid = true;
2289 2289
 		if ($queryValid) $imapFilter->andSearch($imapSearchFilter);
2290 2290
 
2291 2291
 		if (isset($_criterias['range']) && !empty($_criterias['range']))
@@ -2294,12 +2294,12 @@  discard block
 block discarded – undo
2294 2294
 			$imapRangeFilter = new Horde_Imap_Client_Search_Query();
2295 2295
 			$imapRangeFilter->charset('UTF-8');
2296 2296
 			$criteria = strtoupper($_criterias['range']);
2297
-			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since']==$_criterias['before'])
2297
+			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since'] == $_criterias['before'])
2298 2298
 			{
2299
-				$_criterias['date']=$_criterias['since'];
2299
+				$_criterias['date'] = $_criterias['since'];
2300 2300
 				unset($_criterias['since']);
2301 2301
 				unset($_criterias['before']);
2302
-				$criteria=$_criterias['range']='ON';
2302
+				$criteria = $_criterias['range'] = 'ON';
2303 2303
 			}
2304 2304
 			switch ($criteria) {
2305 2305
 				case 'BETWEEN':
@@ -2307,7 +2307,7 @@  discard block
 block discarded – undo
2307 2307
 					//enddate
2308 2308
 					if ($_criterias['since'])
2309 2309
 					{
2310
-						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2310
+						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2311 2311
 						$rangeValid = true;
2312 2312
 					}
2313 2313
 					//startdate
@@ -2316,28 +2316,28 @@  discard block
 block discarded – undo
2316 2316
 						$imapRangeFilter2 = new Horde_Imap_Client_Search_Query();
2317 2317
 						$imapRangeFilter2->charset('UTF-8');
2318 2318
 						//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2319
-						$_criterias['before'] = date("d-M-Y",DateTime::to($_criterias['before'],'ts')+(3600*24));
2320
-						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2319
+						$_criterias['before'] = date("d-M-Y", DateTime::to($_criterias['before'], 'ts') + (3600 * 24));
2320
+						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2321 2321
 						$imapRangeFilter->andSearch($imapRangeFilter2);
2322 2322
 						$rangeValid = true;
2323 2323
 					}
2324 2324
 					break;
2325 2325
 				case 'SINCE'://enddate
2326
-					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since']?$_criterias['since']:$_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2326
+					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since'] ? $_criterias['since'] : $_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2327 2327
 					$rangeValid = true;
2328 2328
 					break;
2329 2329
 				case 'BEFORE'://startdate
2330 2330
 					//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2331
-					$_criterias['before'] = date("d-M-Y",DateTime::to(($_criterias['before']?$_criterias['before']:$_criterias['date']),'ts')+(3600*24));
2332
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2331
+					$_criterias['before'] = date("d-M-Y", DateTime::to(($_criterias['before'] ? $_criterias['before'] : $_criterias['date']), 'ts') + (3600 * 24));
2332
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2333 2333
 					$rangeValid = true;
2334 2334
 					break;
2335 2335
 				case 'ON':
2336
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2336
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2337 2337
 					$rangeValid = true;
2338 2338
 					break;
2339 2339
 			}
2340
-			if ($rangeValid && !$queryValid) $queryValid=true;
2340
+			if ($rangeValid && !$queryValid) $queryValid = true;
2341 2341
 			if ($rangeValid) $imapFilter->andSearch($imapRangeFilter);
2342 2342
 		}
2343 2343
 		if (self::$debug)
@@ -2346,8 +2346,8 @@  discard block
 block discarded – undo
2346 2346
 			$query_str = $imapFilter->build();
2347 2347
 			//error_log(__METHOD__.' ('.__LINE__.') '.' '.$query_str['query'].' created by Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2348 2348
 		}
2349
-		if($queryValid==false) {
2350
-			$imapFilter->flag('DELETED', $set=false);
2349
+		if ($queryValid == false) {
2350
+			$imapFilter->flag('DELETED', $set = false);
2351 2351
 			return $imapFilter;
2352 2352
 		} else {
2353 2353
 			return $imapFilter;
@@ -2361,11 +2361,11 @@  discard block
 block discarded – undo
2361 2361
 	 * @param  boolean|string $_tryIDNConversion (true/false AND 'FORCE'): try IDN Conversion on domainparts of emailADRESSES
2362 2362
 	 * @return mixed - based on the input type
2363 2363
 	 */
2364
-	static function decode_header($_string, $_tryIDNConversion=false)
2364
+	static function decode_header($_string, $_tryIDNConversion = false)
2365 2365
 	{
2366 2366
 		if (is_array($_string))
2367 2367
 		{
2368
-			foreach($_string as $k=>$v)
2368
+			foreach ($_string as $k=>$v)
2369 2369
 			{
2370 2370
 				$_string[$k] = self::decode_header($v, $_tryIDNConversion);
2371 2371
 			}
@@ -2373,18 +2373,18 @@  discard block
 block discarded – undo
2373 2373
 		}
2374 2374
 		else
2375 2375
 		{
2376
-			$_string = Mail\Html::decodeMailHeader($_string,self::$displayCharset);
2376
+			$_string = Mail\Html::decodeMailHeader($_string, self::$displayCharset);
2377 2377
 			$test = @json_encode($_string);
2378 2378
 			//error_log(__METHOD__.__LINE__.' ->'.strlen($singleBodyPart['body']).' Error:'.json_last_error().'<- BodyPart:#'.$test.'#');
2379
-			if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2379
+			if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2380 2380
 			{
2381 2381
 				// try to fix broken utf8
2382 2382
 				$x = utf8_encode($_string);
2383 2383
 				$test = @json_encode($x);
2384
-				if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2384
+				if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2385 2385
 				{
2386 2386
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
2387
-					$_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));
2387
+					$_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));
2388 2388
 				}
2389 2389
 				else
2390 2390
 				{
@@ -2392,7 +2392,7 @@  discard block
 block discarded – undo
2392 2392
 				}
2393 2393
 			}
2394 2394
 
2395
-			if ($_tryIDNConversion===true && stripos($_string,'@')!==false)
2395
+			if ($_tryIDNConversion === true && stripos($_string, '@') !== false)
2396 2396
 			{
2397 2397
 				$rfcAddr = self::parseAddressList($_string);
2398 2398
 				$stringA = array();
@@ -2404,17 +2404,17 @@  discard block
 block discarded – undo
2404 2404
 						break; // skip idna conversion if we encounter an error here
2405 2405
 					}
2406 2406
 					try {
2407
-						$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox,Horde_Idna::decode($_rfcAddr->host),$_rfcAddr->personal);
2407
+						$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox, Horde_Idna::decode($_rfcAddr->host), $_rfcAddr->personal);
2408 2408
 					}
2409 2409
 					// if Idna conversation fails, leave address unchanged
2410
-					catch(\Exception $e) {
2410
+					catch (\Exception $e) {
2411 2411
 						unset($e);
2412 2412
 						$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox, $_rfcAddr->host, $_rfcAddr->personal);
2413 2413
 					}
2414 2414
 				}
2415
-				if (!empty($stringA)) $_string = implode(',',$stringA);
2415
+				if (!empty($stringA)) $_string = implode(',', $stringA);
2416 2416
 			}
2417
-			if ($_tryIDNConversion==='FORCE')
2417
+			if ($_tryIDNConversion === 'FORCE')
2418 2418
 			{
2419 2419
 				//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_string.'='.Horde_Idna::decode($_string));
2420 2420
 				$_string = Horde_Idna::decode($_string);
@@ -2430,17 +2430,17 @@  discard block
 block discarded – undo
2430 2430
 	 * @param  boolean $decode try decoding
2431 2431
 	 * @return mixed - based on the input type
2432 2432
 	 */
2433
-	function decode_subject($_string,$decode=true)
2433
+	function decode_subject($_string, $decode = true)
2434 2434
 	{
2435 2435
 		#$string = $_string;
2436
-		if($_string=='NIL')
2436
+		if ($_string == 'NIL')
2437 2437
 		{
2438 2438
 			return 'No Subject';
2439 2439
 		}
2440 2440
 		if ($decode) $_string = self::decode_header($_string);
2441 2441
 		// make sure its utf-8
2442 2442
 		$test = @json_encode($_string);
2443
-		if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2443
+		if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2444 2444
 		{
2445 2445
 			$_string = utf8_encode($_string);
2446 2446
 		}
@@ -2492,18 +2492,18 @@  discard block
 block discarded – undo
2492 2492
 	function createFolder($_parent, $_folderName, &$_error)
2493 2493
 	{
2494 2494
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."->"."$_parent, $_folderName called from:".function_backtrace());
2495
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2496
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2495
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2496
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2497 2497
 
2498
-		if(empty($parent)) {
2498
+		if (empty($parent)) {
2499 2499
 			$newFolderName = $folderName;
2500 2500
 		} else {
2501 2501
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2502
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2502
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2503 2503
 		}
2504 2504
 		if (empty($newFolderName)) return false;
2505 2505
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.'->'.$newFolderName);
2506
-		if ($this->folderExists($newFolderName,true))
2506
+		if ($this->folderExists($newFolderName, true))
2507 2507
 		{
2508 2508
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." Folder $newFolderName already exists.");
2509 2509
 			return $newFolderName;
@@ -2520,7 +2520,7 @@  discard block
 block discarded – undo
2520 2520
 		}
2521 2521
 		catch (\Exception $e)
2522 2522
 		{
2523
-			$_error = lang('Could not create Folder %1 Reason: %2',$newFolderName,$e->getMessage());
2523
+			$_error = lang('Could not create Folder %1 Reason: %2', $newFolderName, $e->getMessage());
2524 2524
 			error_log(__METHOD__.' ('.__LINE__.') '.' create Folder '.$newFolderName.'->'.$e->getMessage().' ('.$e->details.') Namespace:'.array2string($this->icServer->getNameSpaces()).function_backtrace());
2525 2525
 			return false;
2526 2526
 		}
@@ -2549,15 +2549,15 @@  discard block
 block discarded – undo
2549 2549
 	 */
2550 2550
 	function renameFolder($_oldFolderName, $_parent, $_folderName)
2551 2551
 	{
2552
-		$oldFolderName	= $_oldFolderName;//$this->_encodeFolderName($_oldFolderName);
2553
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2554
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2552
+		$oldFolderName = $_oldFolderName; //$this->_encodeFolderName($_oldFolderName);
2553
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2554
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2555 2555
 
2556
-		if(empty($parent)) {
2556
+		if (empty($parent)) {
2557 2557
 			$newFolderName = $folderName;
2558 2558
 		} else {
2559 2559
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2560
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2560
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2561 2561
 		}
2562 2562
 		if (self::$debug) error_log("create folder: $newFolderName");
2563 2563
 		try
@@ -2566,10 +2566,10 @@  discard block
 block discarded – undo
2566 2566
 		}
2567 2567
 		catch (\Exception $e)
2568 2568
 		{
2569
-			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage());;
2569
+			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage()); ;
2570 2570
 		}
2571 2571
 		// clear FolderExistsInfoCache
2572
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2572
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2573 2573
 
2574 2574
 		return $newFolderName;
2575 2575
 
@@ -2588,15 +2588,15 @@  discard block
 block discarded – undo
2588 2588
 		//$folderName = $this->_encodeFolderName($_folderName);
2589 2589
 		try
2590 2590
 		{
2591
-			$this->icServer->subscribeMailbox($_folderName,false);
2591
+			$this->icServer->subscribeMailbox($_folderName, false);
2592 2592
 			$this->icServer->deleteMailbox($_folderName);
2593 2593
 		}
2594 2594
 		catch (\Exception $e)
2595 2595
 		{
2596
-			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage());;
2596
+			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage()); ;
2597 2597
 		}
2598 2598
 		// clear FolderExistsInfoCache
2599
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2599
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2600 2600
 
2601 2601
 		return true;
2602 2602
 	}
@@ -2631,10 +2631,10 @@  discard block
 block discarded – undo
2631 2631
 	 *
2632 2632
 	 * @return array with folder objects. eg.: INBOX => {inbox object}
2633 2633
 	 */
2634
-	function getFolderObjects($_subscribedOnly=false, $_getCounters=false, $_alwaysGetDefaultFolders=false,$_useCacheIfPossible=true)
2634
+	function getFolderObjects($_subscribedOnly = false, $_getCounters = false, $_alwaysGetDefaultFolders = false, $_useCacheIfPossible = true)
2635 2635
 	{
2636 2636
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' ServerID:'.$this->icServer->ImapServerId.", subscribedOnly:$_subscribedOnly, getCounters:$_getCounters, alwaysGetDefaultFolders:$_alwaysGetDefaultFolders, _useCacheIfPossible:$_useCacheIfPossible");
2637
-		if (self::$debugTimes) $starttime = microtime (true);
2637
+		if (self::$debugTimes) $starttime = microtime(true);
2638 2638
 		static $folders2return;
2639 2639
 		//$_subscribedOnly=false;
2640 2640
 		// always use static on single request if info is available;
@@ -2642,42 +2642,42 @@  discard block
 block discarded – undo
2642 2642
 		// set $_useCacheIfPossible to false !
2643 2643
 		if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2644 2644
 		{
2645
-			if (self::$debugTimes) self::logRunTimes($starttime,null,'using static',__METHOD__.' ('.__LINE__.') ');
2645
+			if (self::$debugTimes) self::logRunTimes($starttime, null, 'using static', __METHOD__.' ('.__LINE__.') ');
2646 2646
 			return $folders2return[$this->icServer->ImapServerId];
2647 2647
 		}
2648 2648
 
2649
-		if ($_subscribedOnly && $_getCounters===false)
2649
+		if ($_subscribedOnly && $_getCounters === false)
2650 2650
 		{
2651
-			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2651
+			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
2652 2652
 			if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2653 2653
 			{
2654 2654
 				//error_log(__METHOD__.' ('.__LINE__.') '.' using Cached folderObjects'.array2string($folders2return[$this->icServer->ImapServerId]));
2655
-				if (self::$debugTimes) self::logRunTimes($starttime,null,'from Cache',__METHOD__.' ('.__LINE__.') ');
2655
+				if (self::$debugTimes) self::logRunTimes($starttime, null, 'from Cache', __METHOD__.' ('.__LINE__.') ');
2656 2656
 				return $folders2return[$this->icServer->ImapServerId];
2657 2657
 			}
2658 2658
 		}
2659 2659
 		// use $folderBasicInfo for holding attributes and other basic folderinfo $folderBasicInfo[$this->icServer->ImapServerId]
2660 2660
 		static $folderBasicInfo;
2661
-		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);
2661
+		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);
2662 2662
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($folderBasicInfo[$this->icServer->ImapServerId])));
2663 2663
 
2664 2664
 		$delimiter = $this->getHierarchyDelimiter();
2665 2665
 
2666 2666
 		$inboxData = new \stdClass;
2667
-		$inboxData->name 		= 'INBOX';
2667
+		$inboxData->name = 'INBOX';
2668 2668
 		$inboxData->folderName		= 'INBOX';
2669
-		$inboxData->displayName		= lang('INBOX');
2669
+		$inboxData->displayName = lang('INBOX');
2670 2670
 		$inboxData->delimiter 		= $delimiter;
2671
-		$inboxData->shortFolderName	= 'INBOX';
2672
-		$inboxData->shortDisplayName	= lang('INBOX');
2671
+		$inboxData->shortFolderName = 'INBOX';
2672
+		$inboxData->shortDisplayName = lang('INBOX');
2673 2673
 		$inboxData->subscribed = true;
2674
-		if($_getCounters == true) {
2674
+		if ($_getCounters == true) {
2675 2675
 			$inboxData->counter = $this->getMailBoxCounters('INBOX');
2676 2676
 		}
2677 2677
 		// force unsubscribed by preference showAllFoldersInFolderPane
2678 2678
 		if ($_subscribedOnly == true &&
2679 2679
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2680
-			$this->mailPreferences['showAllFoldersInFolderPane']==1)
2680
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1)
2681 2681
 		{
2682 2682
 			$_subscribedOnly = false;
2683 2683
 		}
@@ -2690,12 +2690,12 @@  discard block
 block discarded – undo
2690 2690
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2691 2691
 		if (is_array($nameSpace))
2692 2692
 		{
2693
-			foreach($nameSpace as $k => $singleNameSpace) {
2693
+			foreach ($nameSpace as $k => $singleNameSpace) {
2694 2694
 				$type = $singleNameSpace['type'];
2695 2695
 				// the following line (assumption that for the same namespace the delimiter should be equal) may be wrong
2696
-				$foldersNameSpace[$type]['delimiter']  = $singleNameSpace['delimiter'];
2696
+				$foldersNameSpace[$type]['delimiter'] = $singleNameSpace['delimiter'];
2697 2697
 
2698
-				if(is_array($singleNameSpace)&&$fetchedAllInOneGo==false) {
2698
+				if (is_array($singleNameSpace) && $fetchedAllInOneGo == false) {
2699 2699
 					// fetch and sort the subscribed folders
2700 2700
 					// we alway fetch the subscribed, as this provides the only way to tell
2701 2701
 					// if a folder is subscribed or not
@@ -2703,22 +2703,22 @@  discard block
 block discarded – undo
2703 2703
 					{
2704 2704
 						try
2705 2705
 						{
2706
-							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('',0,true);
2706
+							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('', 0, true);
2707 2707
 							if (!empty($subscribedMailboxes))
2708 2708
 							{
2709 2709
 								$fetchedAllInOneGo = true;
2710 2710
 							}
2711 2711
 							else
2712 2712
 							{
2713
-								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'],0,true);
2713
+								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'], 0, true);
2714 2714
 							}
2715 2715
 						}
2716
-						catch(Exception $e)
2716
+						catch (Exception $e)
2717 2717
 						{
2718 2718
 							continue;
2719 2719
 						}
2720 2720
 						//echo "subscribedMailboxes";_debug_array($subscribedMailboxes);
2721
-						$subscribedFoldersPerNS = (!empty($subscribedMailboxes)?array_keys($subscribedMailboxes):array());
2721
+						$subscribedFoldersPerNS = (!empty($subscribedMailboxes) ?array_keys($subscribedMailboxes) : array());
2722 2722
 						//if (is_array($foldersNameSpace[$type]['subscribed'])) sort($foldersNameSpace[$type]['subscribed']);
2723 2723
 						//_debug_array($foldersNameSpace);
2724 2724
 						//error_log(__METHOD__.__LINE__.array2string($singleNameSpace).':#:'.array2string($subscribedFoldersPerNS));
@@ -2728,18 +2728,18 @@  discard block
 block discarded – undo
2728 2728
 							foreach ($subscribedMailboxes as $k => $finfo)
2729 2729
 							{
2730 2730
 								//error_log(__METHOD__.__LINE__.$k.':#:'.array2string($finfo));
2731
-								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k]=
2732
-								$folderBasicInfo[$this->icServer->ImapServerId][$k]=array(
2731
+								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k] =
2732
+								$folderBasicInfo[$this->icServer->ImapServerId][$k] = array(
2733 2733
 									'MAILBOX'=>$finfo['MAILBOX'],
2734 2734
 									'ATTRIBUTES'=>$finfo['ATTRIBUTES'],
2735
-									'delimiter'=>$finfo['delimiter'],//lowercase for some reason???
2736
-									'SUBSCRIBED'=>$finfo['SUBSCRIBED'],//seeded by getMailboxes
2735
+									'delimiter'=>$finfo['delimiter'], //lowercase for some reason???
2736
+									'SUBSCRIBED'=>$finfo['SUBSCRIBED'], //seeded by getMailboxes
2737 2737
 								);
2738
-								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k,$foldersNameSpace[$type]['subscribed']))
2738
+								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k, $foldersNameSpace[$type]['subscribed']))
2739 2739
 								{
2740 2740
 									$foldersNameSpace[$type]['subscribed'][] = $k;
2741 2741
 								}
2742
-								if (empty($foldersNameSpace[$type]['all']) || !in_array($k,$foldersNameSpace[$type]['all']))
2742
+								if (empty($foldersNameSpace[$type]['all']) || !in_array($k, $foldersNameSpace[$type]['all']))
2743 2743
 								{
2744 2744
 									$foldersNameSpace[$type]['all'][] = $k;
2745 2745
 								}
@@ -2762,7 +2762,7 @@  discard block
 block discarded – undo
2762 2762
 						// that may produce problems, when encountering recursions probably
2763 2763
 						// horde is handling that, so we do not; keep that in mind!
2764 2764
 						//$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],2,true);
2765
-						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],0,true);
2765
+						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'], 0, true);
2766 2766
 					}
2767 2767
 					catch (\Exception $e)
2768 2768
 					{
@@ -2780,26 +2780,26 @@  discard block
 block discarded – undo
2780 2780
 					foreach ($allMailboxesExt as $mbx) {
2781 2781
 						if (!isset($folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2782 2782
 						{
2783
-							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]=array(
2783
+							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']] = array(
2784 2784
 								'MAILBOX'=>$mbx['MAILBOX'],
2785 2785
 								'ATTRIBUTES'=>$mbx['ATTRIBUTES'],
2786
-								'delimiter'=>$mbx['delimiter'],//lowercase for some reason???
2787
-								'SUBSCRIBED'=>$mbx['SUBSCRIBED'],//seeded by getMailboxes
2786
+								'delimiter'=>$mbx['delimiter'], //lowercase for some reason???
2787
+								'SUBSCRIBED'=>$mbx['SUBSCRIBED'], //seeded by getMailboxes
2788 2788
 							);
2789 2789
 							if ($mbx['SUBSCRIBED'] && !isset($subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2790 2790
 							{
2791 2791
 								$subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']] = $folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']];
2792 2792
 							}
2793 2793
 						}
2794
-						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'],$foldersNameSpace[$type]['subscribed'])))
2794
+						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'], $foldersNameSpace[$type]['subscribed'])))
2795 2795
 						{
2796 2796
 							$foldersNameSpace[$type]['subscribed'][] = $mbx['MAILBOX'];
2797 2797
 						}
2798 2798
 						//echo __METHOD__;_debug_array($mbx);
2799 2799
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
2800
-						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']])||
2801
-							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']])||
2802
-							(substr($mbx['MAILBOX'],-1)==$foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'],0,-1)]))
2800
+						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']]) ||
2801
+							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']]) ||
2802
+							(substr($mbx['MAILBOX'], -1) == $foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'], 0, -1)]))
2803 2803
 						) continue;
2804 2804
 
2805 2805
 						//echo '#'.$mbx['MAILBOX'].':'.array2string($mbx)."#<br>";
@@ -2809,7 +2809,7 @@  discard block
 block discarded – undo
2809 2809
 					//_debug_array(array_keys($allMailBoxesExtSorted));
2810 2810
 					$allMailboxes = array();
2811 2811
 					foreach ((array)$allMailBoxesExtSorted as $mbx) {
2812
-						if (!in_array($mbx['MAILBOX'],$allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2812
+						if (!in_array($mbx['MAILBOX'], $allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2813 2813
 						//echo "Result:";_debug_array($allMailboxes);
2814 2814
 					}
2815 2815
 					$foldersNameSpace[$type]['all'] = $allMailboxes;
@@ -2818,57 +2818,57 @@  discard block
 block discarded – undo
2818 2818
 			}
2819 2819
 		}
2820 2820
 		//subscribed folders may be used in getFolderStatus
2821
-		Cache::setCache(Cache::INSTANCE,'email','subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$subscribedFoldersForCache,$expiration=60*60*1);
2821
+		Cache::setCache(Cache::INSTANCE, 'email', 'subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $subscribedFoldersForCache, $expiration = 60 * 60 * 1);
2822 2822
 		//echo "<br>FolderNameSpace To Process:";_debug_array($foldersNameSpace);
2823 2823
 		$autoFolderObjects = $folders = array();
2824 2824
 		$autofolder_exists = array();
2825
-		foreach( array('personal', 'others', 'shared') as $type) {
2826
-			if(isset($foldersNameSpace[$type])) {
2827
-				if($_subscribedOnly) {
2828
-					if( !empty($foldersNameSpace[$type]['subscribed']) ) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2825
+		foreach (array('personal', 'others', 'shared') as $type) {
2826
+			if (isset($foldersNameSpace[$type])) {
2827
+				if ($_subscribedOnly) {
2828
+					if (!empty($foldersNameSpace[$type]['subscribed'])) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2829 2829
 				} else {
2830
-					if( !empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2830
+					if (!empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2831 2831
 				}
2832
-				foreach((array)$listOfFolders as $folderName) {
2832
+				foreach ((array)$listOfFolders as $folderName) {
2833 2833
 					//echo "<br>FolderToCheck:$folderName<br>";
2834 2834
 					//error_log(__METHOD__.__LINE__.'#Delimiter:'.$delimiter.':#'.$folderName);
2835
-					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue;//when subscribedonly, we fetch all folders in one go.
2836
-					if($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all'])||in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2835
+					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue; //when subscribedonly, we fetch all folders in one go.
2836
+					if ($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all']) || in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2837 2837
 						#echo "$folderName failed to be here <br>";
2838 2838
 						continue;
2839 2839
 					}
2840 2840
 					if (isset($folders[$folderName])) continue;
2841 2841
 					if (isset($autoFolderObjects[$folderName])) continue;
2842
-					if (empty($delimiter)||$delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2842
+					if (empty($delimiter) || $delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2843 2843
 					$folderParts = explode($delimiter, $folderName);
2844 2844
 					$shortName = array_pop($folderParts);
2845 2845
 
2846 2846
 					$folderObject = new \stdClass;
2847
-					$folderObject->delimiter	= $delimiter;
2848
-					$folderObject->folderName	= $folderName;
2849
-					$folderObject->shortFolderName	= $shortName;
2850
-					if(!$_subscribedOnly) {
2847
+					$folderObject->delimiter = $delimiter;
2848
+					$folderObject->folderName = $folderName;
2849
+					$folderObject->shortFolderName = $shortName;
2850
+					if (!$_subscribedOnly) {
2851 2851
 						#echo $folderName."->".$type."<br>";
2852 2852
 						#_debug_array($foldersNameSpace[$type]['subscribed']);
2853 2853
 						$folderObject->subscribed = in_array($folderName, (array)$foldersNameSpace[$type]['subscribed']);
2854 2854
 					}
2855 2855
 
2856
-					if($_getCounters == true) {
2856
+					if ($_getCounters == true) {
2857 2857
 						//error_log(__METHOD__.' ('.__LINE__.') '.' getCounter forFolder:'.$folderName);
2858 2858
 						$folderObject->counter = $this->getMailBoxCounters($folderName);
2859 2859
 					}
2860
-					if(strtoupper($folderName) == 'INBOX') {
2860
+					if (strtoupper($folderName) == 'INBOX') {
2861 2861
 						$folderName = 'INBOX';
2862
-						$folderObject->folderName	= 'INBOX';
2863
-						$folderObject->shortFolderName	= 'INBOX';
2864
-						$folderObject->displayName	= lang('INBOX');
2862
+						$folderObject->folderName = 'INBOX';
2863
+						$folderObject->shortFolderName = 'INBOX';
2864
+						$folderObject->displayName = lang('INBOX');
2865 2865
 						$folderObject->shortDisplayName = lang('INBOX');
2866
-						$folderObject->subscribed	= true;
2866
+						$folderObject->subscribed = true;
2867 2867
 					// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
2868
-					} elseif (in_array($shortName,self::$autoFolders)) {
2869
-						$tmpfolderparts = explode($delimiter,$folderObject->folderName);
2868
+					} elseif (in_array($shortName, self::$autoFolders)) {
2869
+						$tmpfolderparts = explode($delimiter, $folderObject->folderName);
2870 2870
 						array_pop($tmpfolderparts);
2871
-						$folderObject->displayName = implode($delimiter,$tmpfolderparts).$delimiter.lang($shortName);
2871
+						$folderObject->displayName = implode($delimiter, $tmpfolderparts).$delimiter.lang($shortName);
2872 2872
 						$folderObject->shortDisplayName = lang($shortName);
2873 2873
 						unset($tmpfolderparts);
2874 2874
 					} else {
@@ -2876,13 +2876,13 @@  discard block
 block discarded – undo
2876 2876
 						$folderObject->shortDisplayName = $shortName;
2877 2877
 					}
2878 2878
 					//$folderName = $folderName;
2879
-					if (in_array($shortName,self::$autoFolders)&&self::searchValueInFolderObjects($shortName,$autoFolderObjects)===false) {
2879
+					if (in_array($shortName, self::$autoFolders) && self::searchValueInFolderObjects($shortName, $autoFolderObjects) === false) {
2880 2880
 						$autoFolderObjects[$folderName] = $folderObject;
2881 2881
 					} else {
2882 2882
 						$folders[$folderName] = $folderObject;
2883 2883
 					}
2884 2884
 					//error_log(__METHOD__.' ('.__LINE__.') '.':'.$folderObject->folderName);
2885
-					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders ();
2885
+					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders();
2886 2886
 					if (isset(self::$specialUseFolders[$folderName]))
2887 2887
 					{
2888 2888
 						$autofolder_exists[$folderName] = self::$specialUseFolders[$folderName];
@@ -2891,27 +2891,27 @@  discard block
 block discarded – undo
2891 2891
 			}
2892 2892
 		}
2893 2893
 		if (is_array($autoFolderObjects) && !empty($autoFolderObjects)) {
2894
-			uasort($autoFolderObjects,array($this,"sortByAutoFolderPos"));
2894
+			uasort($autoFolderObjects, array($this, "sortByAutoFolderPos"));
2895 2895
 		}
2896 2896
 		// check if some standard folders are missing and need to be created
2897 2897
 		if (count($autofolder_exists) < count(self::$autoFolders) && $this->check_create_autofolders($autofolder_exists))
2898 2898
 		{
2899 2899
 			// if new folders have been created, re-read folders ignoring the cache
2900
-			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false);	// false = do NOT use cache
2900
+			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false); // false = do NOT use cache
2901 2901
 		}
2902
-		if (is_array($folders)) uasort($folders,array($this,"sortByDisplayName"));
2902
+		if (is_array($folders)) uasort($folders, array($this, "sortByDisplayName"));
2903 2903
 		//$folders2return = array_merge($autoFolderObjects,$folders);
2904 2904
 		//_debug_array($folders2return); #exit;
2905
-		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject,(array)$autoFolderObjects,(array)$folders);
2906
-		if (($_subscribedOnly && $_getCounters===false) ||
2907
-			($_subscribedOnly == false && $_getCounters===false &&
2905
+		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject, (array)$autoFolderObjects, (array)$folders);
2906
+		if (($_subscribedOnly && $_getCounters === false) ||
2907
+			($_subscribedOnly == false && $_getCounters === false &&
2908 2908
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2909
-			$this->mailPreferences['showAllFoldersInFolderPane']==1))
2909
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1))
2910 2910
 		{
2911
-			Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),$folders2return,$expiration=60*60*1);
2911
+			Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), $folders2return, $expiration = 60 * 60 * 1);
2912 2912
 		}
2913
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderBasicInfo,$expiration=60*60*1);
2914
-		if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') ');
2913
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderBasicInfo, $expiration = 60 * 60 * 1);
2914
+		if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') ');
2915 2915
 		return $folders2return[$this->icServer->ImapServerId];
2916 2916
 	}
2917 2917
 
@@ -2932,21 +2932,21 @@  discard block
 block discarded – undo
2932 2932
 	 *
2933 2933
 	 * @return array arrays of folders
2934 2934
 	 */
2935
-	function getFolderArrays ($_nodePath = null, $_onlyTopLevel = false, $_search= 2, $_subscribedOnly = false, $_getCounter = false)
2935
+	function getFolderArrays($_nodePath = null, $_onlyTopLevel = false, $_search = 2, $_subscribedOnly = false, $_getCounter = false)
2936 2936
 	{
2937 2937
 		// delimiter
2938 2938
 		$delimiter = $this->getHierarchyDelimiter();
2939 2939
 
2940
-		$folders = $nameSpace =  array();
2940
+		$folders = $nameSpace = array();
2941 2941
 		$nameSpaceTmp = $this->_getNameSpaces();
2942
-		foreach($nameSpaceTmp as $k => $singleNameSpace) {
2943
-			$nameSpace[$singleNameSpace['type']]=$singleNameSpace;
2942
+		foreach ($nameSpaceTmp as $k => $singleNameSpace) {
2943
+			$nameSpace[$singleNameSpace['type']] = $singleNameSpace;
2944 2944
 		}
2945 2945
 		unset($nameSpaceTmp);
2946 2946
 
2947 2947
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2948 2948
 		// Get special use folders
2949
-		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders (); // Set self::$specialUseFolders
2949
+		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders(); // Set self::$specialUseFolders
2950 2950
 		// topLevelQueries generally ignore the $_search param. Except for Config::examineNamespace
2951 2951
 		if ($_onlyTopLevel) // top level leaves
2952 2952
 		{
@@ -2957,20 +2957,20 @@  discard block
 block discarded – undo
2957 2957
 			if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
2958 2958
 			if (self::$mailConfig['examineNamespace'])
2959 2959
 			{
2960
-				$prefixes=array();
2960
+				$prefixes = array();
2961 2961
 				if (is_array($nameSpace))
2962 2962
 				{
2963
-					foreach($nameSpace as $k => $singleNameSpace) {
2963
+					foreach ($nameSpace as $k => $singleNameSpace) {
2964 2964
 						$type = $singleNameSpace['type'];
2965 2965
 
2966
-						if(is_array($singleNameSpace) && $singleNameSpace['prefix']){
2966
+						if (is_array($singleNameSpace) && $singleNameSpace['prefix']) {
2967 2967
 							$prefixes[$type] = $singleNameSpace['prefix'];
2968 2968
 							//regard extra care for nameSpacequeries when configured AND respect $_search
2969
-							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search==0?0:2, true);
2969
+							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search == 0 ? 0 : 2, true);
2970 2970
 							if (is_array($result))
2971 2971
 							{
2972 2972
 								ksort($result);
2973
-								$topFolders = array_merge($topFolders,$result);
2973
+								$topFolders = array_merge($topFolders, $result);
2974 2974
 							}
2975 2975
 						}
2976 2976
 					}
@@ -2979,7 +2979,7 @@  discard block
 block discarded – undo
2979 2979
 
2980 2980
 			$autofolders = array();
2981 2981
 
2982
-			foreach(self::$specialUseFolders as $path => $folder)
2982
+			foreach (self::$specialUseFolders as $path => $folder)
2983 2983
 			{
2984 2984
 				if ($this->folderExists($path))
2985 2985
 				{
@@ -2987,9 +2987,9 @@  discard block
 block discarded – undo
2987 2987
 				}
2988 2988
 			}
2989 2989
 			// Check if the special use folders are there, otherwise try to create them
2990
-			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders ($autofolders))
2990
+			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders($autofolders))
2991 2991
 			{
2992
-				return $this->getFolderArrays ($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2992
+				return $this->getFolderArrays($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2993 2993
 			}
2994 2994
 
2995 2995
 			// now process topFolders for next level
@@ -2997,13 +2997,13 @@  discard block
 block discarded – undo
2997 2997
 			{
2998 2998
 				$pattern = "/\\".$delimiter."/";
2999 2999
 				$reference = preg_replace($pattern, '', $node['MAILBOX']);
3000
-				if(!empty($prefixes))
3000
+				if (!empty($prefixes))
3001 3001
 				{
3002 3002
 					$reference = '';
3003
-					$tmpArray = explode($delimiter,$node['MAILBOX']);
3004
-					foreach($tmpArray as $p)
3003
+					$tmpArray = explode($delimiter, $node['MAILBOX']);
3004
+					foreach ($tmpArray as $p)
3005 3005
 					{
3006
-						$reference = empty($reference)?$p:$reference.$delimiter.$p;
3006
+						$reference = empty($reference) ? $p : $reference.$delimiter.$p;
3007 3007
 					}
3008 3008
 				}
3009 3009
 				$mainFolder = $subFolders = array();
@@ -3039,19 +3039,19 @@  discard block
 block discarded – undo
3039 3039
 							$nFolders [$path] = $folder;
3040 3040
 						}
3041 3041
 					}
3042
-					if (is_array($aFolders)) uasort ($aFolders, array($this,'sortByAutofolder'));
3042
+					if (is_array($aFolders)) uasort($aFolders, array($this, 'sortByAutofolder'));
3043 3043
 					//ksort($aFolders);
3044 3044
 
3045 3045
 					// Sort none auto folders base on mailbox name
3046
-					uasort($nFolders,array($this,'sortByMailbox'));
3046
+					uasort($nFolders, array($this, 'sortByMailbox'));
3047 3047
 
3048
-					$subFolders = array_merge($aFolders,$nFolders);
3048
+					$subFolders = array_merge($aFolders, $nFolders);
3049 3049
 				}
3050 3050
 				else
3051 3051
 				{
3052 3052
 					if (is_array($subFolders)) ksort($subFolders);
3053 3053
 				}
3054
-				$folders = array_merge($folders,(array)$mainFolder, (array)$subFolders);
3054
+				$folders = array_merge($folders, (array)$mainFolder, (array)$subFolders);
3055 3055
 			}
3056 3056
 		}
3057 3057
 		elseif ($_nodePath) // single node
@@ -3078,9 +3078,9 @@  discard block
 block discarded – undo
3078 3078
 				$folders = $this->icServer->getMailboxes($path, $_search, true);
3079 3079
 			}
3080 3080
 
3081
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
3081
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
3082 3082
 		}
3083
-		elseif(!$_nodePath) // all
3083
+		elseif (!$_nodePath) // all
3084 3084
 		{
3085 3085
 			if ($_subscribedOnly)
3086 3086
 			{
@@ -3096,101 +3096,101 @@  discard block
 block discarded – undo
3096 3096
 		{
3097 3097
 			// SORTING FOLDERS
3098 3098
 			//self::$debugTimes=true;
3099
-			if (self::$debugTimes) $starttime = microtime (true);
3099
+			if (self::$debugTimes) $starttime = microtime(true);
3100 3100
 			// Merge of all auto folders and specialusefolders
3101 3101
 			$autoFoldersTmp = array_unique((array_merge(self::$autoFolders, array_values(self::$specialUseFolders))));
3102
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
3102
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
3103 3103
 			$tmpFolders = $folders;
3104
-			$inboxFolderObject=$inboxSubFolderObjects=$autoFolderObjects=$typeFolderObject=$mySpecialUseFolders=array();
3105
-			$googleMailFolderObject=$googleAutoFolderObjects=$googleSubFolderObjects=array();
3106
-			$isGoogleMail=false;
3107
-			foreach($autoFoldersTmp as $afk=>$aF)
3104
+			$inboxFolderObject = $inboxSubFolderObjects = $autoFolderObjects = $typeFolderObject = $mySpecialUseFolders = array();
3105
+			$googleMailFolderObject = $googleAutoFolderObjects = $googleSubFolderObjects = array();
3106
+			$isGoogleMail = false;
3107
+			foreach ($autoFoldersTmp as $afk=>$aF)
3108 3108
 			{
3109
-				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF]=$this->getFolderByType($aF,false);
3109
+				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF] = $this->getFolderByType($aF, false);
3110 3110
 				//error_log($afk.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3111 3111
 			}
3112 3112
 			//error_log(array2string($mySpecialUseFolders));
3113 3113
 			foreach ($tmpFolders as $k => $f) {
3114
-				$sorted=false;
3115
-				if (strtoupper(substr($k,0,5))=='INBOX') {
3116
-					if (strtoupper($k)=='INBOX') {
3114
+				$sorted = false;
3115
+				if (strtoupper(substr($k, 0, 5)) == 'INBOX') {
3116
+					if (strtoupper($k) == 'INBOX') {
3117 3117
 						//error_log(__METHOD__.__LINE__.':'.strtoupper(substr($k,0,5)).':'.$k);
3118
-						$inboxFolderObject[$k]=$f;
3118
+						$inboxFolderObject[$k] = $f;
3119 3119
 						unset($folders[$k]);
3120
-						$sorted=true;
3120
+						$sorted = true;
3121 3121
 					} else {
3122
-						$isAutoFolder=false;
3123
-						foreach($autoFoldersTmp as $afk=>$aF)
3122
+						$isAutoFolder = false;
3123
+						foreach ($autoFoldersTmp as $afk=>$aF)
3124 3124
 						{
3125 3125
 							//error_log(__METHOD__.__LINE__.$k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3126
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3127
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3128
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3126
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3127
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3128
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3129 3129
 							{
3130 3130
 								//error_log(__METHOD__.__LINE__.$k.'->'.$mySpecialUseFolders[$aF]);
3131
-								$isAutoFolder=true;
3132
-								$autoFolderObjects[$k]=$f;
3131
+								$isAutoFolder = true;
3132
+								$autoFolderObjects[$k] = $f;
3133 3133
 								break;
3134 3134
 							}
3135 3135
 						}
3136
-						if ($isAutoFolder==false) $inboxSubFolderObjects[$k]=$f;
3136
+						if ($isAutoFolder == false) $inboxSubFolderObjects[$k] = $f;
3137 3137
 						unset($folders[$k]);
3138
-						$sorted=true;
3138
+						$sorted = true;
3139 3139
 					}
3140
-				} elseif (strtoupper(substr($k,0,13))=='[GOOGLE MAIL]') {
3141
-					$isGoogleMail=true;
3142
-					if (strtoupper($k)=='[GOOGLE MAIL]') {
3143
-						$googleMailFolderObject[$k]=$f;
3140
+				} elseif (strtoupper(substr($k, 0, 13)) == '[GOOGLE MAIL]') {
3141
+					$isGoogleMail = true;
3142
+					if (strtoupper($k) == '[GOOGLE MAIL]') {
3143
+						$googleMailFolderObject[$k] = $f;
3144 3144
 						unset($folders[$k]);
3145
-						$sorted=true;
3145
+						$sorted = true;
3146 3146
 					} else {
3147
-						$isAutoFolder=false;
3148
-						foreach($autoFoldersTmp as $afk=>$aF)
3147
+						$isAutoFolder = false;
3148
+						foreach ($autoFoldersTmp as $afk=>$aF)
3149 3149
 						{
3150 3150
 							//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3151
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3152
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3153
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3151
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3152
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3153
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3154 3154
 							{
3155 3155
 								//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3156
-								$isAutoFolder=true;
3157
-								$googleAutoFolderObjects[$k]=$f;
3156
+								$isAutoFolder = true;
3157
+								$googleAutoFolderObjects[$k] = $f;
3158 3158
 								break;
3159 3159
 							}
3160 3160
 						}
3161
-						if ($isAutoFolder==false) $googleSubFolderObjects[$k]=$f;
3161
+						if ($isAutoFolder == false) $googleSubFolderObjects[$k] = $f;
3162 3162
 						unset($folders[$k]);
3163
-						$sorted=true;
3163
+						$sorted = true;
3164 3164
 					}
3165 3165
 				} else {
3166
-					$isAutoFolder=false;
3167
-					foreach($autoFoldersTmp as $afk=>$aF)
3166
+					$isAutoFolder = false;
3167
+					foreach ($autoFoldersTmp as $afk=>$aF)
3168 3168
 					{
3169 3169
 						//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3170
-						if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3171
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3172
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3170
+						if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3171
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3172
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3173 3173
 						{
3174 3174
 							//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3175
-							$isAutoFolder=true;
3176
-							$autoFolderObjects[$k]=$f;
3175
+							$isAutoFolder = true;
3176
+							$autoFolderObjects[$k] = $f;
3177 3177
 							unset($folders[$k]);
3178
-							$sorted=true;
3178
+							$sorted = true;
3179 3179
 							break;
3180 3180
 						}
3181 3181
 					}
3182 3182
 				}
3183 3183
 
3184
-				if ($sorted==false)
3184
+				if ($sorted == false)
3185 3185
 				{
3186
-					foreach(array('others','shared') as $type)
3186
+					foreach (array('others', 'shared') as $type)
3187 3187
 					{
3188
-						if ($nameSpace[$type]['prefix_present']&&$nameSpace[$type]['prefix'])
3188
+						if ($nameSpace[$type]['prefix_present'] && $nameSpace[$type]['prefix'])
3189 3189
 						{
3190
-							if (substr($k,0,strlen($nameSpace[$type]['prefix']))==$nameSpace[$type]['prefix']||
3191
-								substr($k,0,strlen($nameSpace[$type]['prefix'])-strlen($nameSpace[$type]['delimiter']))==substr($nameSpace[$type]['prefix'],0,strlen($nameSpace[$type]['delimiter'])*-1)) {
3190
+							if (substr($k, 0, strlen($nameSpace[$type]['prefix'])) == $nameSpace[$type]['prefix'] ||
3191
+								substr($k, 0, strlen($nameSpace[$type]['prefix']) - strlen($nameSpace[$type]['delimiter'])) == substr($nameSpace[$type]['prefix'], 0, strlen($nameSpace[$type]['delimiter']) * -1)) {
3192 3192
 								//error_log(__METHOD__.__LINE__.':'.substr($k,0,strlen($nameSpace[$type]['prefix'])).':'.$k);
3193
-								$typeFolderObject[$type][$k]=$f;
3193
+								$typeFolderObject[$type][$k] = $f;
3194 3194
 								unset($folders[$k]);
3195 3195
 							}
3196 3196
 						}
@@ -3201,40 +3201,40 @@  discard block
 block discarded – undo
3201 3201
 			// avoid calling sortByAutoFolder as it is not regarding subfolders
3202 3202
 			$autoFolderObjectsTmp = $autoFolderObjects;
3203 3203
 			unset($autoFolderObjects);
3204
-			uasort($autoFolderObjectsTmp, array($this,'sortByMailbox'));
3205
-			foreach($autoFoldersTmp as $afk=>$aF)
3204
+			uasort($autoFolderObjectsTmp, array($this, 'sortByMailbox'));
3205
+			foreach ($autoFoldersTmp as $afk=>$aF)
3206 3206
 			{
3207
-				foreach($autoFolderObjectsTmp as $k => $f)
3207
+				foreach ($autoFolderObjectsTmp as $k => $f)
3208 3208
 				{
3209
-					if($aF && ($mySpecialUseFolders[$aF]==$k ||
3210
-						substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter ||
3211
-						stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false))
3209
+					if ($aF && ($mySpecialUseFolders[$aF] == $k ||
3210
+						substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter ||
3211
+						stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false))
3212 3212
 					{
3213
-						$autoFolderObjects[$k]=$f;
3213
+						$autoFolderObjects[$k] = $f;
3214 3214
 					}
3215 3215
 				}
3216 3216
 			}
3217 3217
 			//error_log(__METHOD__.__LINE__.array2string($autoFolderObjects));
3218 3218
 			if (!$isGoogleMail) {
3219
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$inboxSubFolderObjects,(array)$folders,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3219
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$inboxSubFolderObjects, (array)$folders, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3220 3220
 			} else {
3221 3221
 				// avoid calling sortByAutoFolder as it is not regarding subfolders
3222 3222
 				$gAutoFolderObjectsTmp = $googleAutoFolderObjects;
3223 3223
 				unset($googleAutoFolderObjects);
3224
-				uasort($gAutoFolderObjectsTmp, array($this,'sortByMailbox'));
3225
-				foreach($autoFoldersTmp as $afk=>$aF)
3224
+				uasort($gAutoFolderObjectsTmp, array($this, 'sortByMailbox'));
3225
+				foreach ($autoFoldersTmp as $afk=>$aF)
3226 3226
 				{
3227
-					foreach($gAutoFolderObjectsTmp as $k => $f)
3227
+					foreach ($gAutoFolderObjectsTmp as $k => $f)
3228 3228
 					{
3229
-						if($aF && ($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter))
3229
+						if ($aF && ($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter))
3230 3230
 						{
3231
-							$googleAutoFolderObjects[$k]=$f;
3231
+							$googleAutoFolderObjects[$k] = $f;
3232 3232
 						}
3233 3233
 					}
3234 3234
 				}
3235
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$folders,(array)$googleMailFolderObject,$googleAutoFolderObjects,$googleSubFolderObjects,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3235
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$folders, (array)$googleMailFolderObject, $googleAutoFolderObjects, $googleSubFolderObjects, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3236 3236
 			}
3237
-			if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') Sorting:');
3237
+			if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') Sorting:');
3238 3238
 			//self::$debugTimes=false;
3239 3239
 		}
3240 3240
 		// Get counter information and add them to each fetched folders array
@@ -3256,10 +3256,10 @@  discard block
 block discarded – undo
3256 3256
 	 * @param array $autofolders_exists existing folders, no need to check their existance again
3257 3257
 	 * @return int number of new folders created
3258 3258
 	 */
3259
-	function check_create_autofolders(array $autofolders_exists=array())
3259
+	function check_create_autofolders(array $autofolders_exists = array())
3260 3260
 	{
3261 3261
 		$num_created = 0;
3262
-		foreach(self::$autoFolders as $folder)
3262
+		foreach (self::$autoFolders as $folder)
3263 3263
 		{
3264 3264
 			$created = false;
3265 3265
 			if (!in_array($folder, $autofolders_exists) && $this->_getSpecialUseFolder($folder, true, $created) &&
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
 		$rv = false;
3285 3285
 		foreach ($haystack as $k => $v)
3286 3286
 		{
3287
-			foreach($v as &$sv) {if (trim($sv)==trim($needle)) return $k;}
3287
+			foreach ($v as &$sv) {if (trim($sv) == trim($needle)) return $k; }
3288 3288
 		}
3289 3289
 		return $rv;
3290 3290
 	}
@@ -3297,9 +3297,9 @@  discard block
 block discarded – undo
3297 3297
 	 * @param array $b array of folders
3298 3298
 	 * @return int expect values (0, 1 or -1)
3299 3299
 	 */
3300
-	function sortByMailbox($a,$b)
3300
+	function sortByMailbox($a, $b)
3301 3301
 	{
3302
-		return strcasecmp($a['MAILBOX'],$b['MAILBOX']);
3302
+		return strcasecmp($a['MAILBOX'], $b['MAILBOX']);
3303 3303
 	}
3304 3304
 
3305 3305
 	/**
@@ -3309,13 +3309,13 @@  discard block
 block discarded – undo
3309 3309
 	 * @param string $_hDelimiter hierarchy delimiter
3310 3310
 	 * @return array returns an array of data extracted from given node path
3311 3311
 	 */
3312
-	static function pathToFolderData ($_path, $_hDelimiter)
3312
+	static function pathToFolderData($_path, $_hDelimiter)
3313 3313
 	{
3314 3314
 		if (!strpos($_path, self::DELIMITER)) $_path = self::DELIMITER.$_path;
3315 3315
 		list(,$path) = explode(self::DELIMITER, $_path);
3316 3316
 		$path_chain = $parts = explode($_hDelimiter, $path);
3317 3317
 		$name = array_pop($parts);
3318
-		return array (
3318
+		return array(
3319 3319
 			'name' => $name,
3320 3320
 			'mailbox' => $path,
3321 3321
 			'parent' => implode($_hDelimiter, $parts),
@@ -3338,8 +3338,8 @@  discard block
 block discarded – undo
3338 3338
 		// 0, 1 und -1
3339 3339
 		$a = self::pathToFolderData($_a['MAILBOX'], $_a['delimiter']);
3340 3340
 		$b = self::pathToFolderData($_b['MAILBOX'], $_b['delimiter']);
3341
-		$pos1 = array_search(trim($a['name']),self::$autoFolders);
3342
-		$pos2 = array_search(trim($b['name']),self::$autoFolders);
3341
+		$pos1 = array_search(trim($a['name']), self::$autoFolders);
3342
+		$pos2 = array_search(trim($b['name']), self::$autoFolders);
3343 3343
 		if ($pos1 == $pos2) return 0;
3344 3344
 		return ($pos1 < $pos2) ? -1 : 1;
3345 3345
 	}
@@ -3352,10 +3352,10 @@  discard block
 block discarded – undo
3352 3352
 	 * @param object $b array of folderobjects
3353 3353
 	 * @return int expect values (0, 1 or -1)
3354 3354
 	 */
3355
-	function sortByDisplayName($a,$b)
3355
+	function sortByDisplayName($a, $b)
3356 3356
 	{
3357 3357
 		// 0, 1 und -1
3358
-		return strcasecmp($a->displayName,$b->displayName);
3358
+		return strcasecmp($a->displayName, $b->displayName);
3359 3359
 	}
3360 3360
 
3361 3361
 	/**
@@ -3366,11 +3366,11 @@  discard block
 block discarded – undo
3366 3366
 	 * @param object $b array of folderobjects
3367 3367
 	 * @return int expect values (0, 1 or -1)
3368 3368
 	 */
3369
-	function sortByAutoFolderPos($a,$b)
3369
+	function sortByAutoFolderPos($a, $b)
3370 3370
 	{
3371 3371
 		// 0, 1 und -1
3372
-		$pos1 = array_search(trim($a->shortFolderName),self::$autoFolders);
3373
-		$pos2 = array_search(trim($b->shortFolderName),self::$autoFolders);
3372
+		$pos1 = array_search(trim($a->shortFolderName), self::$autoFolders);
3373
+		$pos2 = array_search(trim($b->shortFolderName), self::$autoFolders);
3374 3374
 		if ($pos1 == $pos2) return 0;
3375 3375
 		return ($pos1 < $pos2) ? -1 : 1;
3376 3376
 	}
@@ -3383,7 +3383,7 @@  discard block
 block discarded – undo
3383 3383
 	 * @param boolean $_returnObject return the counters as object rather than an array
3384 3384
 	 * @return mixed false or array of counters array(MESSAGES,UNSEEN,RECENT,UIDNEXT,UIDVALIDITY) or object
3385 3385
 	 */
3386
-	function getMailBoxCounters($folderName,$_returnObject=true)
3386
+	function getMailBoxCounters($folderName, $_returnObject = true)
3387 3387
 	{
3388 3388
 		try
3389 3389
 		{
@@ -3395,9 +3395,9 @@  discard block
 block discarded – undo
3395 3395
 			if (self::$debug) error_log(__METHOD__." returned FolderStatus for Folder $folderName:".$e->getMessage());
3396 3396
 			return false;
3397 3397
 		}
3398
-		if(is_array($folderStatus)) {
3399
-			if ($_returnObject===false) return $folderStatus;
3400
-			$status =  new \stdClass;
3398
+		if (is_array($folderStatus)) {
3399
+			if ($_returnObject === false) return $folderStatus;
3400
+			$status = new \stdClass;
3401 3401
 			$status->messages   = $folderStatus['MESSAGES'];
3402 3402
 			$status->unseen     = $folderStatus['UNSEEN'];
3403 3403
 			$status->recent     = $folderStatus['RECENT'];
@@ -3419,42 +3419,42 @@  discard block
 block discarded – undo
3419 3419
 	 * @param string $reclevel 0, counter to keep track of the current recursionlevel
3420 3420
 	 * @return array of mailboxes
3421 3421
 	 */
3422
-	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel=0)
3422
+	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel = 0)
3423 3423
 	{
3424 3424
 		#echo __METHOD__." retrieve SubFolders for $_mailbox$delimiter <br>";
3425
-		$maxreclevel=25;
3425
+		$maxreclevel = 25;
3426 3426
 		if ($reclevel > $maxreclevel) {
3427
-			error_log( __METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3427
+			error_log(__METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3428 3428
 			return array();
3429 3429
 		}
3430 3430
 		$reclevel++;
3431 3431
 		// clean up double delimiters
3432
-		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$_mailbox);
3432
+		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $_mailbox);
3433 3433
 		//get that mailbox in question
3434
-		$mbx = $this->icServer->getMailboxes($_mailbox,1,true);
3434
+		$mbx = $this->icServer->getMailboxes($_mailbox, 1, true);
3435 3435
 		$mbxkeys = array_keys($mbx);
3436 3436
 		#_debug_array($mbx);
3437 3437
 //error_log(__METHOD__.' ('.__LINE__.') '.' Delimiter:'.array2string($delimiter));
3438 3438
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
3439 3439
 		// Example: Array([INBOX/GaGa] => Array([MAILBOX] => INBOX/GaGa[ATTRIBUTES] => Array([0] => \\unmarked)[delimiter] => /))
3440
-		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"]))) {
3440
+		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"]))) {
3441 3441
 			// if there are children fetch them
3442 3442
 			//echo $mbx[$mbxkeys[0]]['MAILBOX']."<br>";
3443 3443
 
3444
-			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '':$delimiter),2,false);
3444
+			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '' : $delimiter), 2, false);
3445 3445
 			//$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'],2,false);
3446 3446
 			//_debug_array($buff);
3447 3447
 			$allMailboxes = array();
3448 3448
 			foreach ($buff as $mbxname) {
3449 3449
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbxname));
3450
-				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$mbxname['MAILBOX']);
3450
+				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $mbxname['MAILBOX']);
3451 3451
 				#echo "About to recur in level $reclevel:".$mbxname."<br>";
3452
-				if ( $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix  && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3452
+				if ($mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3453 3453
 				{
3454 3454
 					$allMailboxes = array_merge($allMailboxes, self::getMailBoxesRecursive($mbxname, $delimiter, $prefix, $reclevel));
3455 3455
 				}
3456 3456
 			}
3457
-			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'];
3457
+			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'];
3458 3458
 			return $allMailboxes;
3459 3459
 		} else {
3460 3460
 			return array($_mailbox);
@@ -3469,18 +3469,18 @@  discard block
 block discarded – undo
3469 3469
 	 * @param boolean& $created =null on return true: if folder was just created, false if not
3470 3470
 	 * @return mixed string or false
3471 3471
 	 */
3472
-	function _getSpecialUseFolder($_type, $_checkexistance=TRUE, &$created=null)
3472
+	function _getSpecialUseFolder($_type, $_checkexistance = TRUE, &$created = null)
3473 3473
 	{
3474 3474
 		static $types = array(
3475
-			'Drafts'   => array('profileKey'=>'acc_folder_draft','autoFolderName'=>'Drafts'),
3476
-			'Template' => array('profileKey'=>'acc_folder_template','autoFolderName'=>'Templates'),
3477
-			'Trash'    => array('profileKey'=>'acc_folder_trash','autoFolderName'=>'Trash'),
3478
-			'Sent'     => array('profileKey'=>'acc_folder_sent','autoFolderName'=>'Sent'),
3479
-			'Junk'     => array('profileKey'=>'acc_folder_junk','autoFolderName'=>'Junk'),
3480
-			'Outbox'   => array('profileKey'=>'acc_folder_outbox','autoFolderName'=>'Outbox'),
3481
-			'Archive'   => array('profileKey'=>'acc_folder_archive','autoFolderName'=>'Archive'),
3475
+			'Drafts'   => array('profileKey'=>'acc_folder_draft', 'autoFolderName'=>'Drafts'),
3476
+			'Template' => array('profileKey'=>'acc_folder_template', 'autoFolderName'=>'Templates'),
3477
+			'Trash'    => array('profileKey'=>'acc_folder_trash', 'autoFolderName'=>'Trash'),
3478
+			'Sent'     => array('profileKey'=>'acc_folder_sent', 'autoFolderName'=>'Sent'),
3479
+			'Junk'     => array('profileKey'=>'acc_folder_junk', 'autoFolderName'=>'Junk'),
3480
+			'Outbox'   => array('profileKey'=>'acc_folder_outbox', 'autoFolderName'=>'Outbox'),
3481
+			'Archive'   => array('profileKey'=>'acc_folder_archive', 'autoFolderName'=>'Archive'),
3482 3482
 		);
3483
-		if ($_type == 'Templates') $_type = 'Template';	// for some reason self::$autofolders uses 'Templates'!
3483
+		if ($_type == 'Templates') $_type = 'Template'; // for some reason self::$autofolders uses 'Templates'!
3484 3484
 		$created = false;
3485 3485
 		if (!isset($types[$_type]))
3486 3486
 		{
@@ -3502,7 +3502,7 @@  discard block
 block discarded – undo
3502 3502
 		}
3503 3503
 		// do not try to autocreate configured Archive-Folder. Return false if configured folder does not exist
3504 3504
 		if ($_type == 'Archive') {
3505
-			if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3505
+			if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3506 3506
 				return false;
3507 3507
 			} else {
3508 3508
 				return $_folderName;
@@ -3510,38 +3510,38 @@  discard block
 block discarded – undo
3510 3510
 
3511 3511
 		}
3512 3512
 		// does the folder exist??? (is configured/preset, but non-existent)
3513
-		if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3513
+		if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3514 3514
 			try
3515 3515
 			{
3516 3516
 				$error = null;
3517 3517
 				if (($_folderName = $this->createFolder('', $_folderName, $error))) $created = true;
3518 3518
 				if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3519 3519
 			}
3520
-			catch(Exception $e)
3520
+			catch (Exception $e)
3521 3521
 			{
3522 3522
 				error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage().':'.function_backtrace());
3523 3523
 				$_folderName = false;
3524 3524
 			}
3525 3525
 		}
3526 3526
 		// not sure yet if false is the correct behavior on none
3527
-		if ($_folderName =='none') return 'none' ; //false;
3527
+		if ($_folderName == 'none') return 'none'; //false;
3528 3528
 		//no (valid) folder found yet; try specialUseFolders
3529
-		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type,self::$specialUseFolders))) $_folderName = $f;
3529
+		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type, self::$specialUseFolders))) $_folderName = $f;
3530 3530
 		//no specialUseFolder; try some Defaults
3531 3531
 		if (empty($_folderName) && isset($types[$_type]))
3532 3532
 		{
3533 3533
 			$nameSpace = $this->_getNameSpaces();
3534
-			$prefix='';
3534
+			$prefix = '';
3535 3535
 			foreach ($nameSpace as $nSp)
3536 3536
 			{
3537
-				if ($nSp['type']=='personal')
3537
+				if ($nSp['type'] == 'personal')
3538 3538
 				{
3539 3539
 					//error_log(__METHOD__.__LINE__.array2string($nSp));
3540 3540
 					$prefix = $nSp['prefix'];
3541 3541
 					break;
3542 3542
 				}
3543 3543
 			}
3544
-			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'],true))
3544
+			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'], true))
3545 3545
 			{
3546 3546
 				$_folderName = $prefix.$types[$_type]['autoFolderName'];
3547 3547
 			}
@@ -3550,11 +3550,11 @@  discard block
 block discarded – undo
3550 3550
 				try
3551 3551
 				{
3552 3552
 					$error = null;
3553
-					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'],$error);
3553
+					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'], $error);
3554 3554
 					$_folderName = $prefix.$types[$_type]['autoFolderName'];
3555 3555
 					if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3556 3556
 				}
3557
-				catch(Exception $e)
3557
+				catch (Exception $e)
3558 3558
 				{
3559 3559
 					error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage());
3560 3560
 					$_folderName = false;
@@ -3570,7 +3570,7 @@  discard block
 block discarded – undo
3570 3570
 	 * @param boolean $_checkexistance trigger check for existance
3571 3571
 	 * @return mixed string or false
3572 3572
 	 */
3573
-	function getFolderByType($type, $_checkexistance=false)
3573
+	function getFolderByType($type, $_checkexistance = false)
3574 3574
 	{
3575 3575
 		return $this->_getSpecialUseFolder($type, $_checkexistance);
3576 3576
 	}
@@ -3580,7 +3580,7 @@  discard block
 block discarded – undo
3580 3580
 	 * @param boolean $_checkexistance trigger check for existance
3581 3581
 	 * @return mixed string or false
3582 3582
 	 */
3583
-	function getJunkFolder($_checkexistance=TRUE)
3583
+	function getJunkFolder($_checkexistance = TRUE)
3584 3584
 	{
3585 3585
 		return $this->_getSpecialUseFolder('Junk', $_checkexistance);
3586 3586
 	}
@@ -3590,7 +3590,7 @@  discard block
 block discarded – undo
3590 3590
 	 * @param boolean $_checkexistance trigger check for existance
3591 3591
 	 * @return mixed string or false
3592 3592
 	 */
3593
-	function getDraftFolder($_checkexistance=TRUE)
3593
+	function getDraftFolder($_checkexistance = TRUE)
3594 3594
 	{
3595 3595
 		return $this->_getSpecialUseFolder('Drafts', $_checkexistance);
3596 3596
 	}
@@ -3600,7 +3600,7 @@  discard block
 block discarded – undo
3600 3600
 	 * @param boolean $_checkexistance trigger check for existance
3601 3601
 	 * @return mixed string or false
3602 3602
 	 */
3603
-	function getTemplateFolder($_checkexistance=TRUE)
3603
+	function getTemplateFolder($_checkexistance = TRUE)
3604 3604
 	{
3605 3605
 		return $this->_getSpecialUseFolder('Template', $_checkexistance);
3606 3606
 	}
@@ -3610,7 +3610,7 @@  discard block
 block discarded – undo
3610 3610
 	 * @param boolean $_checkexistance trigger check for existance
3611 3611
 	 * @return mixed string or false
3612 3612
 	 */
3613
-	function getTrashFolder($_checkexistance=TRUE)
3613
+	function getTrashFolder($_checkexistance = TRUE)
3614 3614
 	{
3615 3615
 		return $this->_getSpecialUseFolder('Trash', $_checkexistance);
3616 3616
 	}
@@ -3620,7 +3620,7 @@  discard block
 block discarded – undo
3620 3620
 	 * @param boolean $_checkexistance trigger check for existance
3621 3621
 	 * @return mixed string or false
3622 3622
 	 */
3623
-	function getSentFolder($_checkexistance=TRUE)
3623
+	function getSentFolder($_checkexistance = TRUE)
3624 3624
 	{
3625 3625
 		return $this->_getSpecialUseFolder('Sent', $_checkexistance);
3626 3626
 	}
@@ -3630,7 +3630,7 @@  discard block
 block discarded – undo
3630 3630
 	 * @param boolean $_checkexistance trigger check for existance
3631 3631
 	 * @return mixed string or false
3632 3632
 	 */
3633
-	function getOutboxFolder($_checkexistance=TRUE)
3633
+	function getOutboxFolder($_checkexistance = TRUE)
3634 3634
 	{
3635 3635
 		return $this->_getSpecialUseFolder('Outbox', $_checkexistance);
3636 3636
 	}
@@ -3640,7 +3640,7 @@  discard block
 block discarded – undo
3640 3640
 	 * @param boolean $_checkexistance trigger check for existance . We do no autocreation for configured Archive folder
3641 3641
 	 * @return mixed string or false
3642 3642
 	 */
3643
-	function getArchiveFolder($_checkexistance=TRUE)
3643
+	function getArchiveFolder($_checkexistance = TRUE)
3644 3644
 	{
3645 3645
 		return $this->_getSpecialUseFolder('Archive', $_checkexistance);
3646 3646
 	}
@@ -3652,10 +3652,10 @@  discard block
 block discarded – undo
3652 3652
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3653 3653
 	 * @return boolean
3654 3654
 	 */
3655
-	function isSentFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3655
+	function isSentFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3656 3656
 	{
3657 3657
 		$sentFolder = $this->getSentFolder($_checkexistance);
3658
-		if(empty($sentFolder)) {
3658
+		if (empty($sentFolder)) {
3659 3659
 			return false;
3660 3660
 		}
3661 3661
 		// does the folder exist???
@@ -3665,13 +3665,13 @@  discard block
 block discarded – undo
3665 3665
 
3666 3666
 		if ($_exactMatch)
3667 3667
 		{
3668
-			if(false !== stripos($_folderName, $sentFolder)&& strlen($_folderName)==strlen($sentFolder)) {
3668
+			if (false !== stripos($_folderName, $sentFolder) && strlen($_folderName) == strlen($sentFolder)) {
3669 3669
 				return true;
3670 3670
 			} else {
3671 3671
 				return false;
3672 3672
 			}
3673 3673
 		} else {
3674
-			if(false !== stripos($_folderName, $sentFolder)) {
3674
+			if (false !== stripos($_folderName, $sentFolder)) {
3675 3675
 				return true;
3676 3676
 			} else {
3677 3677
 				return false;
@@ -3686,9 +3686,9 @@  discard block
 block discarded – undo
3686 3686
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3687 3687
 	 * @return boolean
3688 3688
 	 */
3689
-	function isOutbox($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3689
+	function isOutbox($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3690 3690
 	{
3691
-		if (stripos($_folderName, 'Outbox')===false) {
3691
+		if (stripos($_folderName, 'Outbox') === false) {
3692 3692
 			return false;
3693 3693
 		}
3694 3694
 		// does the folder exist???
@@ -3696,13 +3696,13 @@  discard block
 block discarded – undo
3696 3696
 			$outboxFolder = $this->getOutboxFolder($_checkexistance);
3697 3697
 			if ($_exactMatch)
3698 3698
 			{
3699
-				if(false !== stripos($_folderName, $outboxFolder)&& strlen($_folderName)==strlen($outboxFolder)) {
3699
+				if (false !== stripos($_folderName, $outboxFolder) && strlen($_folderName) == strlen($outboxFolder)) {
3700 3700
 					return true;
3701 3701
 				} else {
3702 3702
 					return false;
3703 3703
 				}
3704 3704
 			} else {
3705
-				if(false !== stripos($_folderName, $outboxFolder)) {
3705
+				if (false !== stripos($_folderName, $outboxFolder)) {
3706 3706
 					return true;
3707 3707
 				} else {
3708 3708
 					return false;
@@ -3719,26 +3719,26 @@  discard block
 block discarded – undo
3719 3719
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3720 3720
 	 * @return boolean
3721 3721
 	 */
3722
-	function isDraftFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3722
+	function isDraftFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3723 3723
 	{
3724 3724
 		$draftFolder = $this->getDraftFolder($_checkexistance);
3725
-		if(empty($draftFolder)) {
3725
+		if (empty($draftFolder)) {
3726 3726
 			return false;
3727 3727
 		}
3728 3728
 		// does the folder exist???
3729 3729
 		if ($_checkexistance && !$this->folderExists($_folderName)) {
3730 3730
 			return false;
3731 3731
 		}
3732
-		if (is_a($_folderName,"Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3732
+		if (is_a($_folderName, "Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3733 3733
 		if ($_exactMatch)
3734 3734
 		{
3735
-			if(false !== stripos($_folderName, $draftFolder)&& strlen($_folderName)==strlen($draftFolder)) {
3735
+			if (false !== stripos($_folderName, $draftFolder) && strlen($_folderName) == strlen($draftFolder)) {
3736 3736
 				return true;
3737 3737
 			} else {
3738 3738
 				return false;
3739 3739
 			}
3740 3740
 		} else {
3741
-			if(false !== stripos($_folderName, $draftFolder)) {
3741
+			if (false !== stripos($_folderName, $draftFolder)) {
3742 3742
 				return true;
3743 3743
 			} else {
3744 3744
 				return false;
@@ -3753,10 +3753,10 @@  discard block
 block discarded – undo
3753 3753
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3754 3754
 	 * @return boolean
3755 3755
 	 */
3756
-	function isTrashFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3756
+	function isTrashFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3757 3757
 	{
3758 3758
 		$trashFolder = $this->getTrashFolder($_checkexistance);
3759
-		if(empty($trashFolder)) {
3759
+		if (empty($trashFolder)) {
3760 3760
 			return false;
3761 3761
 		}
3762 3762
 		// does the folder exist???
@@ -3766,13 +3766,13 @@  discard block
 block discarded – undo
3766 3766
 
3767 3767
 		if ($_exactMatch)
3768 3768
 		{
3769
-			if(false !== stripos($_folderName, $trashFolder)&& strlen($_folderName)==strlen($trashFolder)) {
3769
+			if (false !== stripos($_folderName, $trashFolder) && strlen($_folderName) == strlen($trashFolder)) {
3770 3770
 				return true;
3771 3771
 			} else {
3772 3772
 				return false;
3773 3773
 			}
3774 3774
 		} else {
3775
-			if(false !== stripos($_folderName, $trashFolder)) {
3775
+			if (false !== stripos($_folderName, $trashFolder)) {
3776 3776
 				return true;
3777 3777
 			} else {
3778 3778
 				return false;
@@ -3787,10 +3787,10 @@  discard block
 block discarded – undo
3787 3787
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3788 3788
 	 * @return boolean
3789 3789
 	 */
3790
-	function isTemplateFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3790
+	function isTemplateFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3791 3791
 	{
3792 3792
 		$templateFolder = $this->getTemplateFolder($_checkexistance);
3793
-		if(empty($templateFolder)) {
3793
+		if (empty($templateFolder)) {
3794 3794
 			return false;
3795 3795
 		}
3796 3796
 		// does the folder exist???
@@ -3799,13 +3799,13 @@  discard block
 block discarded – undo
3799 3799
 		}
3800 3800
 		if ($_exactMatch)
3801 3801
 		{
3802
-			if(false !== stripos($_folderName, $templateFolder)&& strlen($_folderName)==strlen($templateFolder)) {
3802
+			if (false !== stripos($_folderName, $templateFolder) && strlen($_folderName) == strlen($templateFolder)) {
3803 3803
 				return true;
3804 3804
 			} else {
3805 3805
 				return false;
3806 3806
 			}
3807 3807
 		} else {
3808
-			if(false !== stripos($_folderName, $templateFolder)) {
3808
+			if (false !== stripos($_folderName, $templateFolder)) {
3809 3809
 				return true;
3810 3810
 			} else {
3811 3811
 				return false;
@@ -3819,24 +3819,24 @@  discard block
 block discarded – undo
3819 3819
 	 * @param boolean $_forceCheck trigger check for existance on icServer
3820 3820
 	 * @return mixed string or false
3821 3821
 	 */
3822
-	function folderExists($_folder, $_forceCheck=false)
3822
+	function folderExists($_folder, $_forceCheck = false)
3823 3823
 	{
3824 3824
 		static $folderInfo;
3825 3825
 		$forceCheck = $_forceCheck;
3826 3826
 		if (empty($_folder))
3827 3827
 		{
3828 3828
 			// this error is more or less without significance, unless we force the check
3829
-			if ($_forceCheck===true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3829
+			if ($_forceCheck === true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3830 3830
 			return false;
3831 3831
 		}
3832 3832
 		// when check is not enforced , we assume a folder represented as Horde_Imap_Client_Mailbox as existing folder
3833
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")&&$_forceCheck===false) return true;
3834
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")) $_folder =  $_folder->utf8;
3833
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox") && $_forceCheck === false) return true;
3834
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox")) $_folder = $_folder->utf8;
3835 3835
 		// reduce traffic within the Instance per User; Expire every 5 hours
3836 3836
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Called with Folder:'.$_folder.function_backtrace());
3837
-		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),$expiration=60*60*5);
3837
+		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), $expiration = 60 * 60 * 5);
3838 3838
 		//error_log(__METHOD__.' ('.__LINE__.') '.'Cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID.($forceCheck?'(forcedCheck)':'').':'.array2string($folderInfo));
3839
-		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck===false)
3839
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck === false)
3840 3840
 		{
3841 3841
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Using cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID);
3842 3842
 			return $folderInfo[$this->profileID][$_folder];
@@ -3852,7 +3852,7 @@  discard block
 block discarded – undo
3852 3852
 
3853 3853
 		// does the folder exist???
3854 3854
 		//error_log(__METHOD__."->Connected?".$this->icServer->_connected.", ".$_folder.", ".($forceCheck?' forceCheck activated':'dont check on server'));
3855
-		if ( $forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3855
+		if ($forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3856 3856
 			//error_log(__METHOD__."->NotConnected and forceCheck with profile:".$this->profileID);
3857 3857
 			//return false;
3858 3858
 			//try to connect
@@ -3863,18 +3863,18 @@  discard block
 block discarded – undo
3863 3863
 		}
3864 3864
 		catch (\Exception $e)
3865 3865
 		{
3866
-			error_log(__METHOD__.__LINE__.$e->getMessage().($e->details?', '.$e->details:''));
3867
-			self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
3866
+			error_log(__METHOD__.__LINE__.$e->getMessage().($e->details ? ', '.$e->details : ''));
3867
+			self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
3868 3868
 			$folderInfo[$this->profileID][$_folder] = false;
3869 3869
 		}
3870 3870
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Folder Exists:'.$folderInfo[$this->profileID][$_folder].function_backtrace());
3871 3871
 
3872
-		if(!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3872
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3873 3873
 			$folderInfo[$this->profileID][$_folder] !== true)
3874 3874
 		{
3875 3875
 			$folderInfo[$this->profileID][$_folder] = false; // set to false, whatever it was (to have a valid returnvalue for the static return)
3876 3876
 		}
3877
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,$expiration=60*60*5);
3877
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, $expiration = 60 * 60 * 5);
3878 3878
 		return (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) ? $folderInfo[$this->profileID][$_folder] : false);
3879 3879
 	}
3880 3880
 
@@ -3887,14 +3887,14 @@  discard block
 block discarded – undo
3887 3887
 	 */
3888 3888
 	function compressFolder($_folderName = false)
3889 3889
 	{
3890
-		$folderName	= ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3891
-		$deleteOptions	= $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3892
-		$trashFolder	= $this->getTrashFolder();
3890
+		$folderName = ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3891
+		$deleteOptions = $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3892
+		$trashFolder = $this->getTrashFolder();
3893 3893
 
3894 3894
 		$this->icServer->openMailbox($folderName);
3895 3895
 
3896
-		if(strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3897
-			$this->deleteMessages('all',$folderName,'remove_immediately');
3896
+		if (strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3897
+			$this->deleteMessages('all', $folderName, 'remove_immediately');
3898 3898
 		} else {
3899 3899
 			$this->icServer->expunge($folderName);
3900 3900
 		}
@@ -3910,19 +3910,19 @@  discard block
 block discarded – undo
3910 3910
 	 * @return bool true, as we do not handle return values yet
3911 3911
 	 * @throws Exception
3912 3912
 	 */
3913
-	function deleteMessages($_messageUID, $_folder=NULL, $_forceDeleteMethod='no')
3913
+	function deleteMessages($_messageUID, $_folder = NULL, $_forceDeleteMethod = 'no')
3914 3914
 	{
3915 3915
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.array2string($_folder).', '.$_forceDeleteMethod);
3916 3916
 		$oldMailbox = '';
3917 3917
 		if (is_null($_folder) || empty($_folder)) $_folder = $this->sessionData['mailbox'];
3918 3918
 		if (empty($_messageUID))
3919 3919
 		{
3920
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
3920
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
3921 3921
 			return false;
3922 3922
 		}
3923
-		elseif ($_messageUID==='all')
3923
+		elseif ($_messageUID === 'all')
3924 3924
 		{
3925
-			$_messageUID= null;
3925
+			$_messageUID = null;
3926 3926
 		}
3927 3927
 		else
3928 3928
 		{
@@ -3931,31 +3931,31 @@  discard block
 block discarded – undo
3931 3931
 			$uidsToDelete->add($_messageUID);
3932 3932
 		}
3933 3933
 		$deleteOptions = $_forceDeleteMethod; // use forceDeleteMethod if not "no", or unknown method
3934
-		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");
3934
+		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");
3935 3935
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3936 3936
 		$trashFolder    = $this->getTrashFolder();
3937
-		$draftFolder	= $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3937
+		$draftFolder = $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3938 3938
 		$templateFolder = $this->getTemplateFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['templateFolder'];
3939
-		if((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash")) {
3939
+		if ((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash")) {
3940 3940
 			$deleteOptions = "remove_immediately";
3941 3941
 		}
3942
-		if($this->icServer->getCurrentMailbox() != $_folder) {
3942
+		if ($this->icServer->getCurrentMailbox() != $_folder) {
3943 3943
 			$oldMailbox = $this->icServer->getCurrentMailbox();
3944 3944
 			$this->icServer->openMailbox($_folder);
3945 3945
 		}
3946 3946
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3947 3947
 		$updateCache = false;
3948
-		switch($deleteOptions) {
3948
+		switch ($deleteOptions) {
3949 3949
 			case "move_to_trash":
3950 3950
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3951 3951
 				$updateCache = true;
3952
-				if(!empty($trashFolder)) {
3952
+				if (!empty($trashFolder)) {
3953 3953
 					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.implode(' : ', $_messageUID));
3954
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ". $this->sessionData['mailbox']);
3954
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ".$this->sessionData['mailbox']);
3955 3955
 					// copy messages
3956 3956
 					try
3957 3957
 					{
3958
-						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete,'move'=>true));
3958
+						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete, 'move'=>true));
3959 3959
 					}
3960 3960
 					catch (\Exception $e)
3961 3961
 					{
@@ -3967,18 +3967,18 @@  discard block
 block discarded – undo
3967 3967
 			case "mark_as_deleted":
3968 3968
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3969 3969
 				// mark messages as deleted
3970
-				if (is_null($_messageUID)) $_messageUID='all';
3971
-				foreach((array)$_messageUID as $key =>$uid)
3970
+				if (is_null($_messageUID)) $_messageUID = 'all';
3971
+				foreach ((array)$_messageUID as $key =>$uid)
3972 3972
 				{
3973 3973
 					//flag messages, that are flagged for deletion as seen too
3974 3974
 					$this->flagMessages('read', $uid, $_folder);
3975 3975
 					$flags = $this->getFlags($uid);
3976 3976
 					$this->flagMessages('delete', $uid, $_folder);
3977 3977
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
3978
-					if (strpos( array2string($flags),'Deleted')!==false) $undelete[] = $uid;
3978
+					if (strpos(array2string($flags), 'Deleted') !== false) $undelete[] = $uid;
3979 3979
 					unset($flags);
3980 3980
 				}
3981
-				foreach((array)$undelete as $key =>$uid)
3981
+				foreach ((array)$undelete as $key =>$uid)
3982 3982
 				{
3983 3983
 					$this->flagMessages('undelete', $uid, $_folder);
3984 3984
 				}
@@ -3987,14 +3987,14 @@  discard block
 block discarded – undo
3987 3987
 			case "remove_immediately":
3988 3988
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3989 3989
 				$updateCache = true;
3990
-				if (is_null($_messageUID)) $_messageUID='all';
3990
+				if (is_null($_messageUID)) $_messageUID = 'all';
3991 3991
 				if (is_object($_messageUID))
3992 3992
 				{
3993 3993
 					$this->flagMessages('delete', $_messageUID, $_folder);
3994 3994
 				}
3995 3995
 				else
3996 3996
 				{
3997
-					foreach((array)$_messageUID as $key =>$uid)
3997
+					foreach ((array)$_messageUID as $key =>$uid)
3998 3998
 					{
3999 3999
 						//flag messages, that are flagged for deletion as seen too
4000 4000
 						$this->flagMessages('delete', $uid, $_folder);
@@ -4005,7 +4005,7 @@  discard block
 block discarded – undo
4005 4005
 				if (is_array($examineMailbox) && $examineMailbox['MESSAGES'] > 0) $this->icServer->expunge($_folder);
4006 4006
 				break;
4007 4007
 		}
4008
-		if($oldMailbox != '') {
4008
+		if ($oldMailbox != '') {
4009 4009
 			$this->icServer->openMailbox($oldMailbox);
4010 4010
 		}
4011 4011
 
@@ -4019,7 +4019,7 @@  discard block
 block discarded – undo
4019 4019
 	 *
4020 4020
 	 * @return null/array flags
4021 4021
 	 */
4022
-	function getFlags ($_messageUID) {
4022
+	function getFlags($_messageUID) {
4023 4023
 		try
4024 4024
 		{
4025 4025
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -4032,7 +4032,7 @@  discard block
 block discarded – undo
4032 4032
 				'ids' => $uidsToFetch,
4033 4033
 			));
4034 4034
 			if (is_object($headersNew)) {
4035
-				foreach($headersNew->ids() as $id) {
4035
+				foreach ($headersNew->ids() as $id) {
4036 4036
 					$_headerObject = $headersNew->get($id);
4037 4037
 					$flags = $_headerObject->getFlags();
4038 4038
 				}
@@ -4055,22 +4055,22 @@  discard block
 block discarded – undo
4055 4055
 	 *
4056 4056
 	 * @return null/boolean
4057 4057
 	 */
4058
-	function getNotifyFlags ($_messageUID, $flags=null)
4058
+	function getNotifyFlags($_messageUID, $flags = null)
4059 4059
 	{
4060 4060
 		if (self::$debug) error_log(__METHOD__.$_messageUID.' Flags:'.array2string($flags));
4061 4061
 		try
4062 4062
 		{
4063
-			if($flags===null) $flags =  $this->getFlags($_messageUID);
4063
+			if ($flags === null) $flags = $this->getFlags($_messageUID);
4064 4064
 		}
4065 4065
 		catch (\Exception $e)
4066 4066
 		{
4067 4067
 			return null;
4068 4068
 		}
4069 4069
 
4070
-		if ( stripos( array2string($flags),'MDNSent')!==false)
4070
+		if (stripos(array2string($flags), 'MDNSent') !== false)
4071 4071
 			return true;
4072 4072
 
4073
-		if ( stripos( array2string($flags),'MDNnotSent')!==false)
4073
+		if (stripos(array2string($flags), 'MDNnotSent') !== false)
4074 4074
 			return false;
4075 4075
 
4076 4076
 		return null;
@@ -4087,45 +4087,45 @@  discard block
 block discarded – undo
4087 4087
 	 *
4088 4088
 	 * @return bool true, as we do not handle icserver->setFlags returnValue
4089 4089
 	 */
4090
-	function flagMessages($_flag, $_messageUID,$_folder=NULL)
4090
+	function flagMessages($_flag, $_messageUID, $_folder = NULL)
4091 4091
 	{
4092 4092
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",$_folder /".$this->sessionData['mailbox']);
4093 4093
 		if (empty($_messageUID))
4094 4094
 		{
4095
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
4095
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
4096 4096
 			return false;
4097 4097
 		}
4098
-		$this->icServer->openMailbox(($_folder?$_folder:$this->sessionData['mailbox']));
4098
+		$this->icServer->openMailbox(($_folder ? $_folder : $this->sessionData['mailbox']));
4099 4099
 		$folder = $this->icServer->getCurrentMailbox();
4100
-		if (is_array($_messageUID)&& count($_messageUID)>50)
4100
+		if (is_array($_messageUID) && count($_messageUID) > 50)
4101 4101
 		{
4102
-			$count = $this->getMailBoxCounters($folder,true);
4103
-			if ($count->messages == count($_messageUID)) $_messageUID='all';
4102
+			$count = $this->getMailBoxCounters($folder, true);
4103
+			if ($count->messages == count($_messageUID)) $_messageUID = 'all';
4104 4104
 		}
4105 4105
 
4106
-		if ($_messageUID==='all')
4106
+		if ($_messageUID === 'all')
4107 4107
 		{
4108 4108
 			$messageUIDs = array('all');
4109 4109
 		}
4110 4110
 		else
4111 4111
 		{
4112 4112
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4113
-			$messageUIDs = array_chunk($_messageUID,50,true);
4113
+			$messageUIDs = array_chunk($_messageUID, 50, true);
4114 4114
 		}
4115 4115
 		try
4116 4116
 		{
4117
-			foreach($messageUIDs as &$uids)
4117
+			foreach ($messageUIDs as &$uids)
4118 4118
 			{
4119
-				if ($uids==='all')
4119
+				if ($uids === 'all')
4120 4120
 				{
4121
-					$uidsToModify=null;
4121
+					$uidsToModify = null;
4122 4122
 				}
4123 4123
 				else
4124 4124
 				{
4125 4125
 					$uidsToModify = new Horde_Imap_Client_Ids();
4126 4126
 					$uidsToModify->add($uids);
4127 4127
 				}
4128
-				switch($_flag) {
4128
+				switch ($_flag) {
4129 4129
 					case "delete":
4130 4130
 						$ret = $this->icServer->store($folder, array('add'=>array('\\Deleted'), 'ids'=> $uidsToModify));
4131 4131
 						break;
@@ -4149,7 +4149,7 @@  discard block
 block discarded – undo
4149 4149
 						break;
4150 4150
 					case "unread":
4151 4151
 					case "unseen":
4152
-						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen','\\Answered','$Forwarded'), 'ids'=> $uidsToModify));
4152
+						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen', '\\Answered', '$Forwarded'), 'ids'=> $uidsToModify));
4153 4153
 						break;
4154 4154
 					case "mdnsent":
4155 4155
 						$ret = $this->icServer->store($folder, array('add'=>array('MDNSent'), 'ids'=> $uidsToModify));
@@ -4207,13 +4207,13 @@  discard block
 block discarded – undo
4207 4207
 				}
4208 4208
 			}
4209 4209
 		}
4210
-		catch(Exception $e)
4210
+		catch (Exception $e)
4211 4211
 		{
4212 4212
 			error_log(__METHOD__.__LINE__.' Error, could not flag messages in folder '.$folder.' Reason:'.$e->getMessage());
4213 4213
 		}
4214 4214
 		if ($folder instanceof Horde_Imap_Client_Mailbox) $_folder = $folder->utf8;
4215 4215
 		//error_log(__METHOD__.__LINE__.'#'.$this->icServer->ImapServerId.'#'.array2string($_folder).'#');
4216
-		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder)?$_folder: $this->sessionData['mailbox'])]['uidValidity'] = 0;
4216
+		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder) ? $_folder : $this->sessionData['mailbox'])]['uidValidity'] = 0;
4217 4217
 
4218 4218
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",".($_folder?$_folder:$this->sessionData['mailbox']));
4219 4219
 		return true; // as we do not catch/examine setFlags returnValue
@@ -4234,19 +4234,19 @@  discard block
 block discarded – undo
4234 4234
 	 * @return mixed/bool true,false or new uid
4235 4235
 	 * @throws Exception
4236 4236
 	 */
4237
-	function moveMessages($_foldername, $_messageUID, $deleteAfterMove=true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4237
+	function moveMessages($_foldername, $_messageUID, $deleteAfterMove = true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4238 4238
 	{
4239
-		$source = Mail\Account::read(($_sourceProfileID?$_sourceProfileID:$this->icServer->ImapServerId))->imapServer();
4239
+		$source = Mail\Account::read(($_sourceProfileID ? $_sourceProfileID : $this->icServer->ImapServerId))->imapServer();
4240 4240
 		//$deleteOptions  = $GLOBALS['egw_info']["user"]["preferences"]["mail"]["deleteOptions"];
4241 4241
 		if (empty($_messageUID))
4242 4242
 		{
4243
-			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',',$_messageUID));
4243
+			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',', $_messageUID));
4244 4244
 			return false;
4245 4245
 		}
4246
-		elseif ($_messageUID==='all')
4246
+		elseif ($_messageUID === 'all')
4247 4247
 		{
4248 4248
 			//error_log(__METHOD__." all Message(s): ".implode(',',$_messageUID));
4249
-			$uidsToMove= null;
4249
+			$uidsToMove = null;
4250 4250
 		}
4251 4251
 		else
4252 4252
 		{
@@ -4255,7 +4255,7 @@  discard block
 block discarded – undo
4255 4255
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4256 4256
 			$uidsToMove->add($_messageUID);
4257 4257
 		}
4258
-		$sourceFolder = (!empty($currentFolder)?$currentFolder: $this->sessionData['mailbox']);
4258
+		$sourceFolder = (!empty($currentFolder) ? $currentFolder : $this->sessionData['mailbox']);
4259 4259
 		//error_log(__METHOD__.__LINE__."$_targetProfileID !== ".array2string($source->ImapServerId));
4260 4260
 		if (!is_null($_targetProfileID) && $_targetProfileID !== $source->ImapServerId)
4261 4261
 		{
@@ -4275,19 +4275,19 @@  discard block
 block discarded – undo
4275 4275
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' mailheaders:'.array2string($headersNew));
4276 4276
 
4277 4277
 			if (is_object($headersNew)) {
4278
-				$c=0;
4278
+				$c = 0;
4279 4279
 				$retUid = new Horde_Imap_Client_Ids();
4280 4280
 				// we copy chunks of 5 to avoid too much memory and/or server stress
4281 4281
 				// some servers seem not to allow/support the appendig of multiple messages. so we are down to one
4282
-				foreach($headersNew as &$_headerObject) {
4282
+				foreach ($headersNew as &$_headerObject) {
4283 4283
 					$c++;
4284 4284
 					$flags = $_headerObject->getFlags(); //unseen status seems to be lost when retrieving the full message
4285 4285
 					$date = $_headerObject->getImapDate();
4286
-					$currentDate =  new Horde_Imap_Client_DateTime();
4286
+					$currentDate = new Horde_Imap_Client_DateTime();
4287 4287
 					// if the internal Date of the message equals the current date; try using the header date
4288
-					if ($date==$currentDate)
4288
+					if ($date == $currentDate)
4289 4289
 					{
4290
-						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4290
+						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4291 4291
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#'.$headerForPrio['DATE']);
4292 4292
 						$date = new Horde_Imap_Client_DateTime($headerForPrio['DATE']);
4293 4293
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#');
@@ -4296,20 +4296,20 @@  discard block
 block discarded – undo
4296 4296
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
4297 4297
 					$body = $_headerObject->getFullMsg();
4298 4298
 					$dataNflags[] = array('data'=>$body, 'flags'=>$flags, 'internaldate'=>$date);
4299
-					if ($c==1)
4299
+					if ($c == 1)
4300 4300
 					{
4301 4301
 						$target = Mail\Account::read($_targetProfileID)->imapServer();
4302 4302
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' TargetServer:'.$_targetProfileID.' TargetFolderObject:'.array2string($_foldername));
4303 4303
 						$foldername = $target->getMailbox($_foldername);
4304 4304
 						// make sure the target folder is open and ready
4305 4305
 						$target->openMailbox($foldername);
4306
-						$ret = $target->append($foldername,$dataNflags);
4306
+						$ret = $target->append($foldername, $dataNflags);
4307 4307
 						$retUid->add($ret);
4308 4308
 						unset($dataNflags);
4309 4309
 						// sleep 500 miliseconds; AS some sERVERs seem not to be capable of the load this is
4310 4310
 						// inflicting in them. they "reply" with an unspecific IMAP Error
4311
-						time_nanosleep(0,500000);
4312
-						$c=0;
4311
+						time_nanosleep(0, 500000);
4312
+						$c = 0;
4313 4313
 					}
4314 4314
 				}
4315 4315
 				if (isset($dataNflags))
@@ -4319,7 +4319,7 @@  discard block
 block discarded – undo
4319 4319
 					$foldername = $target->getMailbox($_foldername);
4320 4320
 					// make sure the target folder is open and ready
4321 4321
 					$target->openMailbox($foldername);
4322
-					$ret = $target->append($foldername,$dataNflags);
4322
+					$ret = $target->append($foldername, $dataNflags);
4323 4323
 					$retUid->add($ret);
4324 4324
 					unset($dataNflags);
4325 4325
 				}
@@ -4330,7 +4330,7 @@  discard block
 block discarded – undo
4330 4330
 				{
4331 4331
 					$remember = $this->icServer;
4332 4332
 					$this->icServer = $source;
4333
-					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod='remove_immediately');
4333
+					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod = 'remove_immediately');
4334 4334
 					$this->icServer = $remember;
4335 4335
 				}
4336 4336
 			}
@@ -4339,7 +4339,7 @@  discard block
 block discarded – undo
4339 4339
 		{
4340 4340
 			try
4341 4341
 			{
4342
-				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove,'move'=>$deleteAfterMove));
4342
+				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove, 'move'=>$deleteAfterMove));
4343 4343
 			}
4344 4344
 			catch (exception $e)
4345 4345
 			{
@@ -4359,22 +4359,22 @@  discard block
 block discarded – undo
4359 4359
 	 * @param string $format ='' if none is passed, use user prefs
4360 4360
 	 * @return string returns the date as it is parseable by strtotime, or current timestamp if everything fails
4361 4361
 	 */
4362
-	static function _strtotime($_date='', $format='', $convert2usertime=false)
4362
+	static function _strtotime($_date = '', $format = '', $convert2usertime = false)
4363 4363
 	{
4364 4364
 		try {
4365
-			$date = new DateTime($_date);	// parse date & time including timezone (throws exception, if not parsable)
4366
-			if ($convert2usertime) $date->setUser();	// convert to user-time
4365
+			$date = new DateTime($_date); // parse date & time including timezone (throws exception, if not parsable)
4366
+			if ($convert2usertime) $date->setUser(); // convert to user-time
4367 4367
 			$date2return = $date->format($format);
4368 4368
 		}
4369
-		catch(\Exception $e)
4369
+		catch (\Exception $e)
4370 4370
 		{
4371
-			unset($e);	// not used
4371
+			unset($e); // not used
4372 4372
 
4373 4373
 			// remove last space-separated part and retry
4374
-			$parts = explode(' ',$_date);
4374
+			$parts = explode(' ', $_date);
4375 4375
 			// try only 10 times to prevent of causing error by reaching
4376 4376
 			// maximum function nesting level.
4377
-			if (count($parts) > 1 && count($parts)<10)
4377
+			if (count($parts) > 1 && count($parts) < 10)
4378 4378
 			{
4379 4379
 				array_pop($parts);
4380 4380
 				$date2return = self::_strtotime(implode(' ', $parts), $format, $convert2usertime);
@@ -4394,12 +4394,12 @@  discard block
 block discarded – undo
4394 4394
 	 * @param mixed $_charset false or string -> Target charset, if false Mail displayCharset will be used
4395 4395
 	 * @return string
4396 4396
 	 */
4397
-	static function htmlentities($_string, $_charset=false)
4397
+	static function htmlentities($_string, $_charset = false)
4398 4398
 	{
4399 4399
 		//setting the charset (if not given)
4400
-		if ($_charset===false) $_charset = self::$displayCharset;
4400
+		if ($_charset === false) $_charset = self::$displayCharset;
4401 4401
 		$string = @htmlentities($_string, ENT_QUOTES, $_charset, false);
4402
-		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string,Translation::detect_encoding($_string),$_charset),ENT_QUOTES | ENT_IGNORE,$_charset, false);
4402
+		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string, Translation::detect_encoding($_string), $_charset), ENT_QUOTES|ENT_IGNORE, $_charset, false);
4403 4403
 		return $string;
4404 4404
 	}
4405 4405
 
@@ -4416,21 +4416,21 @@  discard block
 block discarded – undo
4416 4416
 		//$_html = str_replace("\t",' ',$_html);
4417 4417
 		//error_log(__METHOD__.__LINE__.':'.$_html);
4418 4418
 		//repair doubleencoded ampersands, and some stuff htmLawed stumbles upon with balancing switched on
4419
-		$_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>'),
4420
-							 array('&amp;',    '<BR>',           '<BR>',             '<BR>',             '</font></td>','<td>',    '',         '',           '',  ''),$_html);
4419
+		$_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>'),
4420
+							 array('&amp;', '<BR>', '<BR>', '<BR>', '</font></td>', '<td>', '', '', '', ''), $_html);
4421 4421
 		//$_html = str_replace(array('&amp;amp;'),array('&amp;'),$_html);
4422
-		if (stripos($_html,'style')!==false) Mail\Html::replaceTagsCompletley($_html,'style'); // clean out empty or pagewide style definitions / left over tags
4423
-		if (stripos($_html,'head')!==false) Mail\Html::replaceTagsCompletley($_html,'head'); // Strip out stuff in head
4422
+		if (stripos($_html, 'style') !== false) Mail\Html::replaceTagsCompletley($_html, 'style'); // clean out empty or pagewide style definitions / left over tags
4423
+		if (stripos($_html, 'head') !== false) Mail\Html::replaceTagsCompletley($_html, 'head'); // Strip out stuff in head
4424 4424
 		//if (stripos($_html,'![if')!==false && stripos($_html,'<![endif]>')!==false) Mail\Html::replaceTagsCompletley($_html,'!\[if','<!\[endif\]>',false); // Strip out stuff in ifs
4425 4425
 		//if (stripos($_html,'!--[if')!==false && stripos($_html,'<![endif]-->')!==false) Mail\Html::replaceTagsCompletley($_html,'!--\[if','<!\[endif\]-->',false); // Strip out stuff in ifs
4426 4426
 		//error_log(__METHOD__.' ('.__LINE__.') '.$_html);
4427 4427
 
4428 4428
 		if (get_magic_quotes_gpc() === 1) $_html = stripslashes($_html);
4429 4429
 		// Strip out doctype in head, as htmlLawed cannot handle it TODO: Consider extracting it and adding it afterwards
4430
-		if (stripos($_html,'!doctype')!==false) Mail\Html::replaceTagsCompletley($_html,'!doctype');
4431
-		if (stripos($_html,'?xml:namespace')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml:namespace','/>',false);
4432
-		if (stripos($_html,'?xml version')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml version','\?>',false);
4433
-		if (strpos($_html,'!CURSOR')!==false) Mail\Html::replaceTagsCompletley($_html,'!CURSOR');
4430
+		if (stripos($_html, '!doctype') !== false) Mail\Html::replaceTagsCompletley($_html, '!doctype');
4431
+		if (stripos($_html, '?xml:namespace') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml:namespace', '/>', false);
4432
+		if (stripos($_html, '?xml version') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml version', '\?>', false);
4433
+		if (strpos($_html, '!CURSOR') !== false) Mail\Html::replaceTagsCompletley($_html, '!CURSOR');
4434 4434
 		// htmLawed filter only the 'body'
4435 4435
 		//preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $_html, $matches);
4436 4436
 		//if ($matches[2])
@@ -4441,16 +4441,16 @@  discard block
 block discarded – undo
4441 4441
 		// purify got switched to htmLawed
4442 4442
 		// some testcode to test purifying / htmlawed
4443 4443
 		//$_html = "<BLOCKQUOTE>hi <div> there </div> kram <br> </blockquote>".$_html;
4444
-		$_html = Html\HtmLawed::purify($_html,self::$htmLawed_config,array(),true);
4444
+		$_html = Html\HtmLawed::purify($_html, self::$htmLawed_config, array(), true);
4445 4445
 		//if ($hasOther) $_html = $matches[1]. $_html. $matches[3];
4446 4446
 		// clean out comments , should not be needed as purify should do the job.
4447 4447
 		$search = array(
4448
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
4449
-			'@<!--[\s\S]*?[ \t\n\r]*-->@',         // Strip multi-line comments including CDATA
4448
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
4449
+			'@<!--[\s\S]*?[ \t\n\r]*-->@', // Strip multi-line comments including CDATA
4450 4450
 		);
4451
-		$_html = preg_replace($search,"",$_html);
4451
+		$_html = preg_replace($search, "", $_html);
4452 4452
 		// remove non printable chars
4453
-		$_html = preg_replace('/([\000-\011])/','',$_html);
4453
+		$_html = preg_replace('/([\000-\011])/', '', $_html);
4454 4454
 		//error_log(__METHOD__.':'.__LINE__.':'.$_html);
4455 4455
 	}
4456 4456
 
@@ -4467,12 +4467,12 @@  discard block
 block discarded – undo
4467 4467
 	function getMimePartCharset($_mimePartObject)
4468 4468
 	{
4469 4469
 		//$charSet = 'iso-8859-1';//self::$displayCharset; //'iso-8859-1'; // self::displayCharset seems to be asmarter fallback than iso-8859-1
4470
-		$CharsetFound=false;
4470
+		$CharsetFound = false;
4471 4471
 		//echo "#".$_mimePartObject->encoding.'#<br>';
4472
-		if(is_array($_mimePartObject->parameters)) {
4473
-			if(isset($_mimePartObject->parameters['CHARSET'])) {
4472
+		if (is_array($_mimePartObject->parameters)) {
4473
+			if (isset($_mimePartObject->parameters['CHARSET'])) {
4474 4474
 				$charSet = $_mimePartObject->parameters['CHARSET'];
4475
-				$CharsetFound=true;
4475
+				$CharsetFound = true;
4476 4476
 			}
4477 4477
 		}
4478 4478
 		// this one is dirty, but until I find something that does the trick of detecting the encoding, ....
@@ -4491,7 +4491,7 @@  discard block
 block discarded – undo
4491 4491
 	function decodeMimePart($_mimeMessage, $_encoding, $_charset = '')
4492 4492
 	{
4493 4493
 		// decode the part
4494
-		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage,true));
4494
+		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage, true));
4495 4495
 		switch (strtoupper($_encoding))
4496 4496
 		{
4497 4497
 			case 'BASE64':
@@ -4526,16 +4526,16 @@  discard block
 block discarded – undo
4526 4526
 	 * @param Horde_Mime_Part& $partCalendar =null on return text/calendar part, if one was contained or false
4527 4527
 	 * @return array containing the desired part
4528 4528
 	 */
4529
-	function getMultipartAlternative($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$partCalendar=null)
4529
+	function getMultipartAlternative($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$partCalendar = null)
4530 4530
 	{
4531 4531
 		// a multipart/alternative has exactly 2 parts (text and html  OR  text and something else)
4532 4532
 		// sometimes there are 3 parts, when there is an ics/ical attached/included-> we want to show that
4533 4533
 		// as attachment AND as abstracted ical information (we use our notification style here).
4534 4534
 		$partText = $partCalendar = $partHTML = null;
4535
-		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__,"LINE"=>__LINE__,"STRUCTURE"=>$_structure));
4535
+		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__, "LINE"=>__LINE__, "STRUCTURE"=>$_structure));
4536 4536
 		//error_log(__METHOD__.' ('.__LINE__.') ');
4537 4537
 		$ignore_first_part = true;
4538
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4538
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4539 4539
 		{
4540 4540
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type"." ignoreFirstPart:".$ignore_first_part);
4541 4541
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4543,15 +4543,15 @@  discard block
 block discarded – undo
4543 4543
 			if ($ignore_first_part)
4544 4544
 			{
4545 4545
 				$ignore_first_part = false;
4546
-				continue;	// ignore multipart/alternative itself
4546
+				continue; // ignore multipart/alternative itself
4547 4547
 			}
4548 4548
 
4549 4549
 			$mimePart = $_structure->getPart($mime_id);
4550 4550
 
4551
-			switch($mimePart->getPrimaryType())
4551
+			switch ($mimePart->getPrimaryType())
4552 4552
 			{
4553 4553
 				case 'text':
4554
-					switch($mimePart->getSubType())
4554
+					switch ($mimePart->getSubType())
4555 4555
 					{
4556 4556
 						case 'plain':
4557 4557
 							if ($mimePart->getBytes() > 0) $partText = $mimePart;
@@ -4568,7 +4568,7 @@  discard block
 block discarded – undo
4568 4568
 					break;
4569 4569
 
4570 4570
 				case 'multipart':
4571
-					switch($mimePart->getSubType())
4571
+					switch ($mimePart->getSubType())
4572 4572
 					{
4573 4573
 						case 'related':
4574 4574
 						case 'mixed':
@@ -4590,13 +4590,13 @@  discard block
 block discarded – undo
4590 4590
 			}
4591 4591
 		}
4592 4592
 
4593
-		switch($_htmlMode)
4593
+		switch ($_htmlMode)
4594 4594
 		{
4595 4595
 			case 'html_only':
4596 4596
 			case 'always_display':
4597 4597
 				if ($partHTML)
4598 4598
 				{
4599
-					switch($partHTML->getSubType())
4599
+					switch ($partHTML->getSubType())
4600 4600
 					{
4601 4601
 						case 'related':
4602 4602
 							return $this->getMultipartRelated($_uid, $partHTML, $_htmlMode, $_preserveSeen);
@@ -4608,7 +4608,7 @@  discard block
 block discarded – undo
4608 4608
 							return $this->getTextPart($_uid, $partHTML, $_htmlMode, $_preserveSeen);
4609 4609
 					}
4610 4610
 				}
4611
-				elseif ($partText && $_htmlMode=='always_display')
4611
+				elseif ($partText && $_htmlMode == 'always_display')
4612 4612
 				{
4613 4613
 					return $this->getTextPart($_uid, $partText, $_htmlMode, $_preserveSeen);
4614 4614
 				}
@@ -4655,7 +4655,7 @@  discard block
 block discarded – undo
4655 4655
 	 * @param Horde_Mime_Part& $partCalendar =null on return text/calendar part, if one was contained or false
4656 4656
 	 * @return array containing the desired part
4657 4657
 	 */
4658
-	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts=array(), &$partCalendar=null)
4658
+	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts = array(), &$partCalendar = null)
4659 4659
 	{
4660 4660
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlMode<br>";
4661 4661
 		$bodyPart = array();
@@ -4664,7 +4664,7 @@  discard block
 block discarded – undo
4664 4664
 		$ignore_first_part = true;
4665 4665
 		//$skipParts = array();
4666 4666
 		//error_log(__METHOD__.__LINE__.array2string($_structure->contentTypeMap()));
4667
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4667
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4668 4668
 		{
4669 4669
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type");
4670 4670
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4672,9 +4672,9 @@  discard block
 block discarded – undo
4672 4672
 			{
4673 4673
 				$ignore_first_part = false;
4674 4674
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED FirstPart $mime_id: $mime_type");
4675
-				continue;	// ignore multipart/mixed itself
4675
+				continue; // ignore multipart/mixed itself
4676 4676
 			}
4677
-			if (array_key_exists($mime_id,$skipParts))
4677
+			if (array_key_exists($mime_id, $skipParts))
4678 4678
 			{
4679 4679
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED $mime_id: $mime_type");
4680 4680
 				continue;
@@ -4682,11 +4682,11 @@  discard block
 block discarded – undo
4682 4682
 
4683 4683
 			$part = $_structure->getPart($mime_id);
4684 4684
 
4685
-			switch($part->getPrimaryType())
4685
+			switch ($part->getPrimaryType())
4686 4686
 			{
4687 4687
 				case 'multipart':
4688
-					if ($part->getDisposition() == 'attachment') continue 2;	// +1 for switch
4689
-					switch($part->getSubType())
4688
+					if ($part->getDisposition() == 'attachment') continue 2; // +1 for switch
4689
+					switch ($part->getSubType())
4690 4690
 					{
4691 4691
 						case 'alternative':
4692 4692
 							return array($this->getMultipartAlternative($_uid, $part, $_htmlMode, $_preserveSeen, $partCalendar));
@@ -4702,15 +4702,15 @@  discard block
 block discarded – undo
4702 4702
 					}
4703 4703
 					break;
4704 4704
 				case 'application':
4705
-					switch($part->getSubType())
4705
+					switch ($part->getSubType())
4706 4706
 					{
4707 4707
 						case 'pgp-encrypted':
4708
-							if (($part = $_structure->getPart($mime_id+1)) &&
4708
+							if (($part = $_structure->getPart($mime_id + 1)) &&
4709 4709
 								$part->getType() == 'application/octet-stream')
4710 4710
 							{
4711 4711
 								$this->fetchPartContents($_uid, $part);
4712
-								$skipParts[$mime_id]=$mime_type;
4713
-								$skipParts[$mime_id+1]=$part->getType();
4712
+								$skipParts[$mime_id] = $mime_type;
4713
+								$skipParts[$mime_id + 1] = $part->getType();
4714 4714
 								$bodyPart[] = array(
4715 4715
 									'body'		=> $part->getContents(array(
4716 4716
 										'stream' => false,
@@ -4724,15 +4724,15 @@  discard block
 block discarded – undo
4724 4724
 					break;
4725 4725
 
4726 4726
 				case 'text':
4727
-					switch($part->getSubType())
4727
+					switch ($part->getSubType())
4728 4728
 					{
4729 4729
 						case 'plain':
4730 4730
 						case 'html':
4731 4731
 						case 'calendar': // inline ics/ical files
4732
-							if($part->getDisposition() != 'attachment')
4732
+							if ($part->getDisposition() != 'attachment')
4733 4733
 							{
4734 4734
 								$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4735
-								$skipParts[$mime_id]=$mime_type;
4735
+								$skipParts[$mime_id] = $mime_type;
4736 4736
 							}
4737 4737
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$part->type."/".$part->subType.' -> BodyPart:'.array2string($bodyPart[count($bodyPart)-1]));
4738 4738
 							break;
@@ -4741,16 +4741,16 @@  discard block
 block discarded – undo
4741 4741
 
4742 4742
 				case 'message':
4743 4743
 					//skip attachments
4744
-					if($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4744
+					if ($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4745 4745
 					{
4746 4746
 						$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4747
-						$skipParts[$mime_id]=$mime_type;
4747
+						$skipParts[$mime_id] = $mime_type;
4748 4748
 					}
4749 4749
 					// do not descend into attached Messages
4750
-					if($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4750
+					if ($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4751 4751
 					{
4752 4752
 						$skipParts[$mime_id.'.0'] = $mime_type;
4753
-						foreach($part->contentTypeMap() as $sub_id => $sub_type){ $skipParts[$sub_id] = $sub_type;}
4753
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { $skipParts[$sub_id] = $sub_type; }
4754 4754
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$_uid.' Part:'.$mime_id.':'.array2string($skipParts));
4755 4755
 						//break 2;
4756 4756
 					}
@@ -4775,7 +4775,7 @@  discard block
 block discarded – undo
4775 4775
 	 * @param Horde_Mime_Part& $partCalendar =null on return text/calendar part, if one was contained or false
4776 4776
 	 * @return array containing the desired part
4777 4777
 	 */
4778
-	function getMultipartRelated($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen=false, &$partCalendar=null)
4778
+	function getMultipartRelated($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$partCalendar = null)
4779 4779
 	{
4780 4780
 		$skip = array();
4781 4781
 		return $this->getMultipartMixed($_uid, $_structure, $_htmlMode, $_preserveSeen, $skip, $partCalendar);
@@ -4793,13 +4793,13 @@  discard block
 block discarded – undo
4793 4793
 	 * @param boolean $_tryDecodingServerside = true; wether to try to fetch Data with BINARY instead of BODY
4794 4794
 	 * @return string|resource
4795 4795
 	 */
4796
-	function getBodyPart($_uid, $_partID=null, $_folder=null, $_preserveSeen=false, $_stream=false, &$_encoding=null, $_tryDecodingServerside=true)
4796
+	function getBodyPart($_uid, $_partID = null, $_folder = null, $_preserveSeen = false, $_stream = false, &$_encoding = null, $_tryDecodingServerside = true)
4797 4797
 	{
4798
-		if (self::$debug) error_log( __METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4798
+		if (self::$debug) error_log(__METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4799 4799
 
4800 4800
 		if (empty($_folder))
4801 4801
 		{
4802
-			$_folder = (isset($this->sessionData['mailbox'])&&$this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4802
+			$_folder = (isset($this->sessionData['mailbox']) && $this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4803 4803
 		}
4804 4804
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_folder).'/'.$this->icServer->getCurrentMailbox().'/'. $this->sessionData['mailbox']);
4805 4805
 		// querying contents of body part
@@ -4810,11 +4810,11 @@  discard block
 block discarded – undo
4810 4810
 		$fquery = new Horde_Imap_Client_Fetch_Query();
4811 4811
 		$fetchParams = array(
4812 4812
 			'peek' => $_preserveSeen,
4813
-			'decode' => true,	// try decode on server, does NOT neccessary work
4813
+			'decode' => true, // try decode on server, does NOT neccessary work
4814 4814
 		);
4815
-		if ($_tryDecodingServerside===false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4815
+		if ($_tryDecodingServerside === false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4816 4816
 		{
4817
-			$_tryDecodingServerside=false;
4817
+			$_tryDecodingServerside = false;
4818 4818
 			$fetchParams = array(
4819 4819
 				'peek' => $_preserveSeen,
4820 4820
 			);
@@ -4834,12 +4834,12 @@  discard block
 block discarded – undo
4834 4834
 		}
4835 4835
 		// if we get an empty result, server may have trouble fetching data with UID FETCH $_uid (BINARY.PEEK[$_partID])
4836 4836
 		// thus we trigger a second go with UID FETCH $_uid (BODY.PEEK[$_partID])
4837
-		if (empty($partToReturn)&&$_tryDecodingServerside===true)
4837
+		if (empty($partToReturn) && $_tryDecodingServerside === true)
4838 4838
 		{
4839 4839
 			error_log(__METHOD__.__LINE__.' failed to fetch bodyPart in  BINARY. Try BODY');
4840 4840
 			$partToReturn = $this->getBodyPart($_uid, $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, false);
4841 4841
 		}
4842
-		return ($partToReturn?$partToReturn:null);
4842
+		return ($partToReturn ? $partToReturn : null);
4843 4843
 	}
4844 4844
 
4845 4845
 	/**
@@ -4852,13 +4852,13 @@  discard block
 block discarded – undo
4852 4852
 	 * @param boolean $_stream = false true return a stream, false return string
4853 4853
 	 * @return array containing the desired text part, mimeType and charset
4854 4854
 	 */
4855
-	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode='', $_preserveSeen=false, $_stream=false)
4855
+	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode = '', $_preserveSeen = false, $_stream = false)
4856 4856
 	{
4857 4857
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_uid.':'.array2string($_structure).' '.function_backtrace());
4858 4858
 		$bodyPart = array();
4859
-		if (self::$debug) _debug_array(array($_structure,function_backtrace()));
4859
+		if (self::$debug) _debug_array(array($_structure, function_backtrace()));
4860 4860
 
4861
-		if($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4861
+		if ($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4862 4862
 		{
4863 4863
 			$bodyPart = array(
4864 4864
 				'error'		=> 1,
@@ -4907,10 +4907,10 @@  discard block
 block discarded – undo
4907 4907
 	 * @param Horde_Mime_part& $calendar_part =null on return calendar-part or null, if there is none
4908 4908
 	 * @return array containing the message body, mimeType and charset
4909 4909
 	 */
4910
-	function getMessageBody($_uid, $_htmlOptions='', $_partID=null, Horde_Mime_Part $_structure=null, $_preserveSeen = false, $_folder = '', &$calendar_part=null)
4910
+	function getMessageBody($_uid, $_htmlOptions = '', $_partID = null, Horde_Mime_Part $_structure = null, $_preserveSeen = false, $_folder = '', &$calendar_part = null)
4911 4911
 	{
4912 4912
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlOptions, $_partID<br>";
4913
-		if($_htmlOptions != '') {
4913
+		if ($_htmlOptions != '') {
4914 4914
 			$this->htmlOptions = $_htmlOptions;
4915 4915
 		}
4916 4916
 		if (empty($_folder))
@@ -4931,7 +4931,7 @@  discard block
 block discarded – undo
4931 4931
 			return array(
4932 4932
 				array(
4933 4933
 					'error'		=> 1,
4934
-					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions". 'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4934
+					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions".'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4935 4935
 					'mimeType'	=> 'text/plain',
4936 4936
 					'charSet'	=> self::$displayCharset,
4937 4937
 				)
@@ -4944,7 +4944,7 @@  discard block
 block discarded – undo
4944 4944
 			//_debug_array($_structure->getMimeId()); exit;
4945 4945
 		}
4946 4946
 
4947
-		switch($_structure->getPrimaryType())
4947
+		switch ($_structure->getPrimaryType())
4948 4948
 		{
4949 4949
 			case 'application':
4950 4950
 				return array(
@@ -4956,7 +4956,7 @@  discard block
 block discarded – undo
4956 4956
 				);
4957 4957
 
4958 4958
 			case 'multipart':
4959
-				switch($_structure->getSubType())
4959
+				switch ($_structure->getSubType())
4960 4960
 				{
4961 4961
 					case 'alternative':
4962 4962
 						$bodyParts = array($this->getMultipartAlternative($_uid, $_structure, $this->htmlOptions, $_preserveSeen, $calendar_part));
@@ -4991,7 +4991,7 @@  discard block
 block discarded – undo
4991 4991
 				$bodyPart = array();
4992 4992
 				if ($_structure->getDisposition() != 'attachment')
4993 4993
 				{
4994
-					switch($_structure->getSubType())
4994
+					switch ($_structure->getSubType())
4995 4995
 					{
4996 4996
 						case 'calendar':
4997 4997
 							$calendar_part = $_structure;
@@ -5008,11 +5008,11 @@  discard block
 block discarded – undo
5008 5008
 
5009 5009
 			case 'attachment':
5010 5010
 			case 'message':
5011
-				switch($_structure->getSubType())
5011
+				switch ($_structure->getSubType())
5012 5012
 				{
5013 5013
 					case 'rfc822':
5014 5014
 						$newStructure = $_structure->getParts();
5015
-						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]);}
5015
+						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]); }
5016 5016
 						return self::normalizeBodyParts($this->getMessageBody($_uid, $_htmlOptions, $newStructure[0]->getMimeId(), $newStructure[0], $_preserveSeen, $_folder));
5017 5017
 				}
5018 5018
 				break;
@@ -5040,11 +5040,11 @@  discard block
 block discarded – undo
5040 5040
 	{
5041 5041
 		if (is_array($_bodyParts))
5042 5042
 		{
5043
-			foreach($_bodyParts as $singleBodyPart)
5043
+			foreach ($_bodyParts as $singleBodyPart)
5044 5044
 			{
5045 5045
 				if (!isset($singleBodyPart['body'])) {
5046 5046
 					$buff = self::normalizeBodyParts($singleBodyPart);
5047
-					foreach ((array)$buff as $val) { $body2return[] = $val;}
5047
+					foreach ((array)$buff as $val) { $body2return[] = $val; }
5048 5048
 					continue;
5049 5049
 				}
5050 5050
 				$body2return[] = $singleBodyPart;
@@ -5065,14 +5065,14 @@  discard block
 block discarded – undo
5065 5065
 	 * @param boolean $useTidy  switch to use tidy
5066 5066
 	 * @return string a preformatted string with the mails converted to text
5067 5067
 	 */
5068
-	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false,  $useTidy = true)
5068
+	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false, $useTidy = true)
5069 5069
 	{
5070
-		$message='';
5071
-		for($i=0; $i<count($bodyParts); $i++)
5070
+		$message = '';
5071
+		for ($i = 0; $i < count($bodyParts); $i++)
5072 5072
 		{
5073 5073
 			if (!isset($bodyParts[$i]['body'])) {
5074 5074
 				$bodyParts[$i]['body'] = self::getdisplayableBody($mailClass, $bodyParts[$i], $preserveHTML, $useTidy);
5075
-				$message .= empty($bodyParts[$i]['body'])?'':$bodyParts[$i]['body'];
5075
+				$message .= empty($bodyParts[$i]['body']) ? '' : $bodyParts[$i]['body'];
5076 5076
 				continue;
5077 5077
 			}
5078 5078
 			if (isset($bodyParts[$i]['error'])) continue;
@@ -5097,32 +5097,32 @@  discard block
 block discarded – undo
5097 5097
 				'(R)',
5098 5098
 			);
5099 5099
 
5100
-			if(($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
5100
+			if (($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
5101 5101
 				strtoupper($bodyParts[$i]['charSet']) != 'UTF-8')
5102 5102
 			{
5103
-				$bodyParts[$i]['body'] = preg_replace($sar,$rar,$bodyParts[$i]['body']);
5103
+				$bodyParts[$i]['body'] = preg_replace($sar, $rar, $bodyParts[$i]['body']);
5104 5104
 			}
5105 5105
 
5106
-			if ($bodyParts[$i]['charSet']===false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5106
+			if ($bodyParts[$i]['charSet'] === false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5107 5107
 			// add line breaks to $bodyParts
5108 5108
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
5109
-			$newBody  = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
5109
+			$newBody = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
5110 5110
 			//error_log(__METHOD__.' ('.__LINE__.') '.' MimeType:'.$bodyParts[$i]['mimeType'].'->'.$newBody);
5111 5111
 			$mailClass->activeMimeType = 'text/plain';
5112 5112
 			if ($bodyParts[$i]['mimeType'] == 'text/html') {
5113 5113
 				$mailClass->activeMimeType = $bodyParts[$i]['mimeType'];
5114 5114
 				if (!$preserveHTML)
5115 5115
 				{
5116
-					$alreadyHtmlLawed=false;
5116
+					$alreadyHtmlLawed = false;
5117 5117
 					// as Translation::convert reduces \r\n to \n and purifier eats \n -> peplace it with a single space
5118
-					$newBody = str_replace("\n"," ",$newBody);
5118
+					$newBody = str_replace("\n", " ", $newBody);
5119 5119
 					// convert HTML to text, as we dont want HTML in infologs
5120 5120
 					if ($useTidy && extension_loaded('tidy'))
5121 5121
 					{
5122 5122
 						$tidy = new tidy();
5123
-						$cleaned = $tidy->repairString($newBody, self::$tidy_config,'utf8');
5123
+						$cleaned = $tidy->repairString($newBody, self::$tidy_config, 'utf8');
5124 5124
 						// Found errors. Strip it all so there's some output
5125
-						if($tidy->getStatus() == 2)
5125
+						if ($tidy->getStatus() == 2)
5126 5126
 						{
5127 5127
 							error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$tidy->errorBuffer);
5128 5128
 						}
@@ -5133,7 +5133,7 @@  discard block
 block discarded – undo
5133 5133
 						if (!$preserveHTML)
5134 5134
 						{
5135 5135
 							// filter only the 'body', as we only want that part, if we throw away the html
5136
-							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
5136
+							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
5137 5137
 							if ($matches[2])
5138 5138
 							{
5139 5139
 								$hasOther = true;
@@ -5144,7 +5144,7 @@  discard block
 block discarded – undo
5144 5144
 					else
5145 5145
 					{
5146 5146
 						// htmLawed filter only the 'body'
5147
-						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
5147
+						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
5148 5148
 						if ($matches[2])
5149 5149
 						{
5150 5150
 							$hasOther = true;
@@ -5153,17 +5153,17 @@  discard block
 block discarded – undo
5153 5153
 						$htmLawed = new Html\HtmLawed();
5154 5154
 						// the next line should not be needed, but produces better results on HTML 2 Text conversion,
5155 5155
 						// as we switched off HTMLaweds tidy functionality
5156
-						$newBody = str_replace(array('&amp;amp;','<DIV><BR></DIV>',"<DIV>&nbsp;</DIV>",'<div>&nbsp;</div>'),array('&amp;','<BR>','<BR>','<BR>'),$newBody);
5157
-						$newBody = $htmLawed->run($newBody,self::$htmLawed_config);
5158
-						if ($hasOther && $preserveHTML) $newBody = $matches[1]. $newBody. $matches[3];
5159
-						$alreadyHtmlLawed=true;
5156
+						$newBody = str_replace(array('&amp;amp;', '<DIV><BR></DIV>', "<DIV>&nbsp;</DIV>", '<div>&nbsp;</div>'), array('&amp;', '<BR>', '<BR>', '<BR>'), $newBody);
5157
+						$newBody = $htmLawed->run($newBody, self::$htmLawed_config);
5158
+						if ($hasOther && $preserveHTML) $newBody = $matches[1].$newBody.$matches[3];
5159
+						$alreadyHtmlLawed = true;
5160 5160
 					}
5161 5161
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after purify:'.$newBody);
5162
-					if ($preserveHTML==false) $newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,true,true);
5162
+					if ($preserveHTML == false) $newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, true, true);
5163 5163
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after convertHTMLToText:'.$newBody);
5164
-					if ($preserveHTML==false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
5164
+					if ($preserveHTML == false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
5165 5165
 					/*if (!$alreadyHtmlLawed) */ $mailClass->getCleanHTML($newBody); // remove stuff we regard as unwanted
5166
-					if ($preserveHTML==false) $newBody = str_replace("<br />","\r\n",$newBody);
5166
+					if ($preserveHTML == false) $newBody = str_replace("<br />", "\r\n", $newBody);
5167 5167
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after getClean:'.$newBody);
5168 5168
 				}
5169 5169
 				$message .= $newBody;
@@ -5172,9 +5172,9 @@  discard block
 block discarded – undo
5172 5172
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after specialchars):'.$newBody);
5173 5173
 			//use Mail\Html::convertHTMLToText instead of strip_tags, (even message is plain text) as strip_tags eats away too much
5174 5174
 			//$newBody = strip_tags($newBody); //we need to fix broken tags (or just stuff like "<800 USD/p" )
5175
-			$newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,false,false);
5175
+			$newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, false, false);
5176 5176
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after strip tags):'.$newBody);
5177
-			$newBody = htmlspecialchars_decode($newBody,ENT_QUOTES);
5177
+			$newBody = htmlspecialchars_decode($newBody, ENT_QUOTES);
5178 5178
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body (after hmlspc_decode):'.$newBody);
5179 5179
 			$message .= $newBody;
5180 5180
 			//continue;
@@ -5182,27 +5182,27 @@  discard block
 block discarded – undo
5182 5182
 		return $message;
5183 5183
 	}
5184 5184
 
5185
-	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith=false)
5185
+	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith = false)
5186 5186
 	{
5187 5187
 		$lines = explode("\n", $str);
5188 5188
 		$newStr = '';
5189
-		foreach($lines as $line)
5189
+		foreach ($lines as $line)
5190 5190
 		{
5191 5191
 			// replace tabs by 8 space chars, or any tab only counts one char
5192 5192
 			//$line = str_replace("\t","        ",$line);
5193 5193
 			//$newStr .= wordwrap($line, $cols, $cut);
5194
-			$allowedLength = $cols-strlen($cut);
5194
+			$allowedLength = $cols - strlen($cut);
5195 5195
 			//dont try to break lines with links, chance is we mess up the text is way too big
5196
-			if (strlen($line) > $allowedLength && stripos($line,'href=')===false &&
5197
-				($dontbreaklinesstartingwith==false ||
5196
+			if (strlen($line) > $allowedLength && stripos($line, 'href=') === false &&
5197
+				($dontbreaklinesstartingwith == false ||
5198 5198
 				 ($dontbreaklinesstartingwith &&
5199
-				  strlen($dontbreaklinesstartingwith)>=1 &&
5200
-				  substr($line,0,strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
5199
+				  strlen($dontbreaklinesstartingwith) >= 1 &&
5200
+				  substr($line, 0, strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
5201 5201
 				 )
5202 5202
 				)
5203 5203
 			   )
5204 5204
 			{
5205
-				$s=explode(" ", $line);
5205
+				$s = explode(" ", $line);
5206 5206
 				$line = "";
5207 5207
 				$linecnt = 0;
5208 5208
 				foreach ($s as &$v) {
@@ -5210,22 +5210,22 @@  discard block
 block discarded – undo
5210 5210
 					// only break long words within the wordboundaries,
5211 5211
 					// but it may destroy links, so we check for href and dont do it if we find one
5212 5212
 					// we check for any html within the word, because we do not want to break html by accident
5213
-					if($cnt > $allowedLength && stripos($v,'href=')===false && stripos($v,'onclick=')===false && $cnt == strlen(html_entity_decode($v)))
5213
+					if ($cnt > $allowedLength && stripos($v, 'href=') === false && stripos($v, 'onclick=') === false && $cnt == strlen(html_entity_decode($v)))
5214 5214
 					{
5215
-						$v=wordwrap($v, $allowedLength, $cut, true);
5215
+						$v = wordwrap($v, $allowedLength, $cut, true);
5216 5216
 					}
5217 5217
 					// the rest should be broken at the start of the new word that exceeds the limit
5218
-					if ($linecnt+$cnt > $allowedLength) {
5219
-						$v=$cut.$v;
5218
+					if ($linecnt + $cnt > $allowedLength) {
5219
+						$v = $cut.$v;
5220 5220
 						#$linecnt = 0;
5221
-						$linecnt =strlen($v)-strlen($cut);
5221
+						$linecnt = strlen($v) - strlen($cut);
5222 5222
 					} else {
5223 5223
 						$linecnt += $cnt;
5224 5224
 					}
5225 5225
 					if (strlen($v)) $line .= (strlen($line) ? " " : "").$v;
5226 5226
 				}
5227 5227
 			}
5228
-			$newStr .= $line . "\n";
5228
+			$newStr .= $line."\n";
5229 5229
 		}
5230 5230
 		return $newStr;
5231 5231
 	}
@@ -5240,12 +5240,12 @@  discard block
 block discarded – undo
5240 5240
 	 * @param boolean $_useHeaderInsteadOfEnvelope - force getMessageHeader method to be used for fetching Envelope Information
5241 5241
 	 * @return array the message header
5242 5242
 	 */
5243
-	function getMessageEnvelope($_uid, $_partID = '',$decode=false, $_folder='', $_useHeaderInsteadOfEnvelope=false)
5243
+	function getMessageEnvelope($_uid, $_partID = '', $decode = false, $_folder = '', $_useHeaderInsteadOfEnvelope = false)
5244 5244
 	{
5245 5245
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder".function_backtrace());
5246
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5246
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5247 5247
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder");
5248
-		if((empty($_partID)||$_partID=='null')&&$_useHeaderInsteadOfEnvelope===false) {
5248
+		if ((empty($_partID) || $_partID == 'null') && $_useHeaderInsteadOfEnvelope === false) {
5249 5249
 			$uidsToFetch = new Horde_Imap_Client_Ids();
5250 5250
 			if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5251 5251
 			$uidsToFetch->add($_uid);
@@ -5258,7 +5258,7 @@  discard block
 block discarded – undo
5258 5258
 				'ids' => $uidsToFetch,
5259 5259
 			));
5260 5260
 			if (is_object($headersNew)) {
5261
-				foreach($headersNew as &$_headerObject) {
5261
+				foreach ($headersNew as &$_headerObject) {
5262 5262
 					$env = $_headerObject->getEnvelope();
5263 5263
 					//_debug_array($envFields->singleFields());
5264 5264
 					$singleFields = $envFields->singleFields();
@@ -5273,34 +5273,34 @@  discard block
 block discarded – undo
5273 5273
 							case 'bcc':
5274 5274
 							case 'sender':
5275 5275
 								//error_log(__METHOD__.' ('.__LINE__.') '.$v.'->'.array2string($env->$v->addresses));
5276
-								$envelope[$v]=$env->$v->addresses;
5276
+								$envelope[$v] = $env->$v->addresses;
5277 5277
 								$address = array();
5278 5278
 								if (!is_array($envelope[$v])) break;
5279 5279
 								foreach ($envelope[$v] as $k => $ad)
5280 5280
 								{
5281
-									if (stripos($ad,'@')===false)
5281
+									if (stripos($ad, '@') === false)
5282 5282
 									{
5283
-										$remember=$k;
5283
+										$remember = $k;
5284 5284
 									}
5285 5285
 									else
5286 5286
 									{
5287
-										$address[] = (!is_null($remember)?$envelope[$v][$remember].' ':'').$ad;
5288
-										$remember=null;
5287
+										$address[] = (!is_null($remember) ? $envelope[$v][$remember].' ' : '').$ad;
5288
+										$remember = null;
5289 5289
 									}
5290 5290
 								}
5291 5291
 								$envelope[$v] = $address;
5292 5292
 								break;
5293 5293
 							case 'date':
5294
-								$envelope[$v]=DateTime::to($env->$v);
5294
+								$envelope[$v] = DateTime::to($env->$v);
5295 5295
 								break;
5296 5296
 							default:
5297
-								$envelope[$v]=$env->$v;
5297
+								$envelope[$v] = $env->$v;
5298 5298
 						}
5299 5299
 					}
5300
-					$envelope['size']=$_headerObject->getSize();
5300
+					$envelope['size'] = $_headerObject->getSize();
5301 5301
 				}
5302 5302
 			}
5303
-			$envelope = array_change_key_case($envelope,CASE_UPPER);
5303
+			$envelope = array_change_key_case($envelope, CASE_UPPER);
5304 5304
 			//if ($decode) _debug_array($envelope);
5305 5305
 			//error_log(__METHOD__.' ('.__LINE__.') '.array2string($envelope));
5306 5306
 			if ($decode)
@@ -5308,19 +5308,19 @@  discard block
 block discarded – undo
5308 5308
 				foreach ($envelope as $key => $rvV)
5309 5309
 				{
5310 5310
 					//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5311
-					$envelope[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5311
+					$envelope[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5312 5312
 				}
5313 5313
 			}
5314 5314
 			return $envelope;
5315 5315
 		} else {
5316 5316
 
5317
-			$headers = $this->getMessageHeader($_uid, $_partID, true,true,$_folder);
5317
+			$headers = $this->getMessageHeader($_uid, $_partID, true, true, $_folder);
5318 5318
 
5319 5319
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($headers));
5320 5320
 			//_debug_array($headers);
5321 5321
 			$newData = array(
5322 5322
 				'DATE'		=> $headers['DATE'],
5323
-				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']):$headers['SUBJECT']),
5323
+				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']) : $headers['SUBJECT']),
5324 5324
 				'MESSAGE_ID'	=> $headers['MESSAGE-ID']
5325 5325
 			);
5326 5326
 			if (isset($headers['IN-REPLY-TO'])) $newData['IN-REPLY-TO'] = $headers['IN-REPLY-TO'];
@@ -5331,11 +5331,11 @@  discard block
 block discarded – undo
5331 5331
 			if (isset($headers['SIZE'])) $newData['SIZE'] = $headers['SIZE'];
5332 5332
 			//_debug_array($newData);
5333 5333
 			$recepientList = array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO');
5334
-			foreach($recepientList as $recepientType) {
5335
-				if(isset($headers[$recepientType])) {
5336
-					if ($decode) $headers[$recepientType] =  self::decode_header($headers[$recepientType],true);
5334
+			foreach ($recepientList as $recepientType) {
5335
+				if (isset($headers[$recepientType])) {
5336
+					if ($decode) $headers[$recepientType] = self::decode_header($headers[$recepientType], true);
5337 5337
 					//error_log(__METHOD__.__LINE__." ".$recepientType."->".array2string($headers[$recepientType]));
5338
-					foreach(self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5338
+					foreach (self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5339 5339
 						$addressData = array(
5340 5340
 							'PERSONAL_NAME'		=> $singleAddress->personal ? $singleAddress->personal : 'NIL',
5341 5341
 							'AT_DOMAIN_LIST'	=> $singleAddress->adl ? $singleAddress->adl : 'NIL',
@@ -5343,15 +5343,15 @@  discard block
 block discarded – undo
5343 5343
 							'HOST_NAME'		=> $singleAddress->host ? $singleAddress->host : 'NIL',
5344 5344
 							'EMAIL'			=> $singleAddress->host ? $singleAddress->mailbox.'@'.$singleAddress->host : $singleAddress->mailbox,
5345 5345
 						);
5346
-						if($addressData['PERSONAL_NAME'] != 'NIL') {
5346
+						if ($addressData['PERSONAL_NAME'] != 'NIL') {
5347 5347
 							$addressData['RFC822_EMAIL'] = imap_rfc822_write_address($singleAddress->mailbox, $singleAddress->host, $singleAddress->personal);
5348 5348
 						} else {
5349 5349
 							$addressData['RFC822_EMAIL'] = 'NIL';
5350 5350
 						}
5351
-						$newData[$recepientType][] = ($addressData['RFC822_EMAIL']!='NIL'?$addressData['RFC822_EMAIL']:$addressData['EMAIL']);//$addressData;
5351
+						$newData[$recepientType][] = ($addressData['RFC822_EMAIL'] != 'NIL' ? $addressData['RFC822_EMAIL'] : $addressData['EMAIL']); //$addressData;
5352 5352
 					}
5353 5353
 				} else {
5354
-					if($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5354
+					if ($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5355 5355
 						$newData[$recepientType] = $newData['FROM'];
5356 5356
 					} else {
5357 5357
 						$newData[$recepientType] = array();
@@ -5373,10 +5373,10 @@  discard block
 block discarded – undo
5373 5373
 	 * @param string $_folder folder to work on
5374 5374
 	 * @return array|Horde_Mime_Headers message header as array or object
5375 5375
 	 */
5376
-	function getMessageHeader($_uid, $_partID = '',$decode=false, $preserveUnSeen=false, $_folder='')
5376
+	function getMessageHeader($_uid, $_partID = '', $decode = false, $preserveUnSeen = false, $_folder = '')
5377 5377
 	{
5378 5378
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$_uid.', '.$_partID.', '.$decode.', '.$preserveUnSeen.', '.$_folder);
5379
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5379
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5380 5380
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5381 5381
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5382 5382
 		$uidsToFetch->add($_uid);
@@ -5384,7 +5384,7 @@  discard block
 block discarded – undo
5384 5384
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5385 5385
 		if ($_partID != '')
5386 5386
 		{
5387
-			$fquery->headerText(array('id'=>$_partID,'peek'=>$preserveUnSeen));
5387
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>$preserveUnSeen));
5388 5388
 			$fquery->structure();
5389 5389
 		}
5390 5390
 		else
@@ -5397,18 +5397,18 @@  discard block
 block discarded – undo
5397 5397
 			'ids' => $uidsToFetch,
5398 5398
 		));
5399 5399
 		if (is_object($headersNew)) {
5400
-			foreach($headersNew as $_fetchObject)
5400
+			foreach ($headersNew as $_fetchObject)
5401 5401
 			{
5402
-				$headers = $_fetchObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5402
+				$headers = $_fetchObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5403 5403
 				if ($_partID != '')
5404 5404
 				{
5405 5405
 					$mailStructureObject = $_fetchObject->getStructure();
5406 5406
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5407 5407
 					{
5408
-						if ($mime_id==$_partID)
5408
+						if ($mime_id == $_partID)
5409 5409
 						{
5410 5410
 							//error_log(__METHOD__.' ('.__LINE__.') '."$mime_id == $_partID".array2string($_headerObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray()));
5411
-							$headers = $_fetchObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5411
+							$headers = $_fetchObject->getHeaderText($mime_id, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5412 5412
 							break;
5413 5413
 						}
5414 5414
 					}
@@ -5421,15 +5421,15 @@  discard block
 block discarded – undo
5421 5421
 				if (is_object($headers)) $headers->setUserAgent('EGroupware API '.$GLOBALS['egw_info']['server']['versions']['phpgwapi']);
5422 5422
 				return $headers;
5423 5423
 			}
5424
-			$retValue = is_object($headers) ? $headers->toArray():array();
5424
+			$retValue = is_object($headers) ? $headers->toArray() : array();
5425 5425
 			if ($size) $retValue['size'] = $size;
5426 5426
 		}
5427
-		$retValue = array_change_key_case($retValue,CASE_UPPER);
5427
+		$retValue = array_change_key_case($retValue, CASE_UPPER);
5428 5428
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue));
5429 5429
 		// if SUBJECT is an array, use thelast one, as we assume something with the unfolding for the subject did not work
5430 5430
 		if (is_array($retValue['SUBJECT']))
5431 5431
 		{
5432
-			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT'])-1];
5432
+			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT']) - 1];
5433 5433
 		}
5434 5434
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($decode ? self::decode_header($retValue,true):$retValue));
5435 5435
 		if ($decode)
@@ -5437,7 +5437,7 @@  discard block
 block discarded – undo
5437 5437
 			foreach ($retValue as $key => $rvV)
5438 5438
 			{
5439 5439
 				//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5440
-				$retValue[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5440
+				$retValue[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5441 5441
 			}
5442 5442
 		}
5443 5443
 		return $retValue;
@@ -5454,14 +5454,14 @@  discard block
 block discarded – undo
5454 5454
 	function getMessageRawHeader($_uid, $_partID = '', $_folder = '')
5455 5455
 	{
5456 5456
 		static $rawHeaders;
5457
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5457
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5458 5458
 		//error_log(__METHOD__.' ('.__LINE__.') '." Try Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5459 5459
 
5460
-		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);
5461
-		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5460
+		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);
5461
+		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5462 5462
 		{
5463 5463
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5464
-			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5464
+			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5465 5465
 		}
5466 5466
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5467 5467
 		$uid = $_uid;
@@ -5471,7 +5471,7 @@  discard block
 block discarded – undo
5471 5471
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5472 5472
 		if ($_partID != '')
5473 5473
 		{
5474
-			$fquery->headerText(array('id'=>$_partID,'peek'=>true));
5474
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>true));
5475 5475
 			$fquery->structure();
5476 5476
 		}
5477 5477
 		else
@@ -5482,14 +5482,14 @@  discard block
 block discarded – undo
5482 5482
 			'ids' => $uidsToFetch,
5483 5483
 		));
5484 5484
 		if (is_object($headersNew)) {
5485
-			foreach($headersNew as &$_headerObject) {
5485
+			foreach ($headersNew as &$_headerObject) {
5486 5486
 				$retValue = $_headerObject->getHeaderText();
5487 5487
 				if ($_partID != '')
5488 5488
 				{
5489 5489
 					$mailStructureObject = $_headerObject->getStructure();
5490 5490
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5491 5491
 					{
5492
-						if ($mime_id==$_partID)
5492
+						if ($mime_id == $_partID)
5493 5493
 						{
5494 5494
 							$retValue = $_headerObject->getHeaderText($mime_id);
5495 5495
 						}
@@ -5497,8 +5497,8 @@  discard block
 block discarded – undo
5497 5497
 				}
5498 5498
 			}
5499 5499
 		}
5500
-		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]=$retValue;
5501
-		Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']),$rawHeaders,60*60*1);
5500
+		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $retValue;
5501
+		Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']), $rawHeaders, 60 * 60 * 1);
5502 5502
 		return $retValue;
5503 5503
 	}
5504 5504
 
@@ -5511,25 +5511,25 @@  discard block
 block discarded – undo
5511 5511
 	{
5512 5512
 		$style = '';
5513 5513
 		if (empty($_bodyParts)) return "";
5514
-		foreach((array)$_bodyParts as $singleBodyPart) {
5514
+		foreach ((array)$_bodyParts as $singleBodyPart) {
5515 5515
 			if (!isset($singleBodyPart['body'])) {
5516 5516
 				$singleBodyPart['body'] = self::getStyles($singleBodyPart);
5517 5517
 				$style .= $singleBodyPart['body'];
5518 5518
 				continue;
5519 5519
 			}
5520 5520
 
5521
-			if ($singleBodyPart['charSet']===false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5521
+			if ($singleBodyPart['charSet'] === false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5522 5522
 			$singleBodyPart['body'] = Translation::convert(
5523 5523
 				$singleBodyPart['body'],
5524 5524
 				strtolower($singleBodyPart['charSet'])
5525 5525
 			);
5526 5526
 			$ct = 0;
5527
-			$newStyle=array();
5528
-			if (stripos($singleBodyPart['body'],'<style')!==false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5529
-			if ($ct>0)
5527
+			$newStyle = array();
5528
+			if (stripos($singleBodyPart['body'], '<style') !== false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5529
+			if ($ct > 0)
5530 5530
 			{
5531 5531
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$ct.'#'.array2string($newStyle));
5532
-				$style2buffer = implode('',$newStyle[0]);
5532
+				$style2buffer = implode('', $newStyle[0]);
5533 5533
 			}
5534 5534
 			if ($style2buffer && strtoupper(self::$displayCharset) == 'UTF-8')
5535 5535
 			{
@@ -5537,7 +5537,7 @@  discard block
 block discarded – undo
5537 5537
 				$test = json_encode($style2buffer);
5538 5538
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$test.'# ->'.strlen($style2buffer).' Error:'.json_last_error());
5539 5539
 				//if (json_last_error() != JSON_ERROR_NONE && strlen($style2buffer)>0)
5540
-				if ($test=="null" && strlen($style2buffer)>0)
5540
+				if ($test == "null" && strlen($style2buffer) > 0)
5541 5541
 				{
5542 5542
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
5543 5543
 					error_log(__METHOD__.' ('.__LINE__.') '.' Found Invalid sequence for utf-8 in CSS:'.$style2buffer.' Charset Reported:'.$singleBodyPart['charSet'].' Carset Detected:'.Translation::detect_encoding($style2buffer));
@@ -5548,19 +5548,19 @@  discard block
 block discarded – undo
5548 5548
 		}
5549 5549
 		// clean out comments and stuff
5550 5550
 		$search = array(
5551
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
5551
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
5552 5552
 //			'@<!--[\s\S]*?[ \t\n\r]*-->@',   // Strip multi-line comments including CDATA
5553 5553
 //			'@<!--[\s\S]*?[ \t\n\r]*--@',    // Strip broken multi-line comments including CDATA
5554 5554
 		);
5555
-		$style = preg_replace($search,"",$style);
5555
+		$style = preg_replace($search, "", $style);
5556 5556
 
5557 5557
 		// CSS Security
5558 5558
 		// http://code.google.com/p/browsersec/wiki/Part1#Cascading_stylesheets
5559
-		$css = preg_replace('/(javascript|expression|-moz-binding)/i','',$style);
5560
-		if (stripos($css,'script')!==false) Mail\Html::replaceTagsCompletley($css,'script'); // Strip out script that may be included
5559
+		$css = preg_replace('/(javascript|expression|-moz-binding)/i', '', $style);
5560
+		if (stripos($css, 'script') !== false) Mail\Html::replaceTagsCompletley($css, 'script'); // Strip out script that may be included
5561 5561
 		// 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
5562 5562
 		// as the comments as <!-- styledefinition --> in stylesheet are outdated, and ck-editor does not understand it, we remove it
5563
-		$css = str_replace(array(':','<!--','-->'),array(': ','',''),$css);
5563
+		$css = str_replace(array(':', '<!--', '-->'), array(': ', '', ''), $css);
5564 5564
 		//error_log(__METHOD__.' ('.__LINE__.') '.$css);
5565 5565
 		// TODO: we may have to strip urls and maybe comments and ifs
5566 5566
 		return $css;
@@ -5575,16 +5575,16 @@  discard block
 block discarded – undo
5575 5575
 	 * @param boolean $_stream =false true: return a stream, false: return string, stream suppresses any caching
5576 5576
 	 * @return string the message body
5577 5577
 	 */
5578
-	function getMessageRawBody($_uid, $_partID = '', $_folder='', $_stream=false)
5578
+	function getMessageRawBody($_uid, $_partID = '', $_folder = '', $_stream = false)
5579 5579
 	{
5580 5580
 		//TODO: caching einbauen static!
5581 5581
 		static $rawBody;
5582 5582
 		if (is_null($rawBody)) $rawBody = array();
5583
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5584
-		if (!$_stream && isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5583
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5584
+		if (!$_stream && isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5585 5585
 		{
5586 5586
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Body $_uid, $_partID in Folder $_folder");
5587
-			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5587
+			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5588 5588
 		}
5589 5589
 
5590 5590
 		$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -5597,13 +5597,13 @@  discard block
 block discarded – undo
5597 5597
 		if ($_partID != '')
5598 5598
 		{
5599 5599
 			$fquery->structure();
5600
-			$fquery->bodyPart($_partID,array('peek'=>true));
5600
+			$fquery->bodyPart($_partID, array('peek'=>true));
5601 5601
 		}
5602 5602
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5603 5603
 			'ids' => $uidsToFetch,
5604 5604
 		));
5605 5605
 		if (is_object($headersNew)) {
5606
-			foreach($headersNew as &$_headerObject) {
5606
+			foreach ($headersNew as &$_headerObject) {
5607 5607
 				$body = $_headerObject->getFullMsg($_stream);
5608 5608
 				if ($_partID != '')
5609 5609
 				{
@@ -5611,7 +5611,7 @@  discard block
 block discarded – undo
5611 5611
 					//_debug_array($mailStructureObject->contentTypeMap());
5612 5612
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5613 5613
 					{
5614
-						if ($mime_id==$_partID)
5614
+						if ($mime_id == $_partID)
5615 5615
 						{
5616 5616
 							$body = $_headerObject->getBodyPart($mime_id, $_stream);
5617 5617
 						}
@@ -5622,7 +5622,7 @@  discard block
 block discarded – undo
5622 5622
 		if (!$_stream)
5623 5623
 		{
5624 5624
 			//error_log(__METHOD__.' ('.__LINE__.') '."[{$this->icServer->ImapServerId}][$_folder][$_uid][".(empty($_partID)?'NIL':$_partID)."]");
5625
-			$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)] = $body;
5625
+			$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $body;
5626 5626
 		}
5627 5627
 		return $body;
5628 5628
 	}
@@ -5637,13 +5637,13 @@  discard block
 block discarded – undo
5637 5637
 	 * @param Horde_Imap_Client_Fetch_Query $fquery=null default query just structure
5638 5638
 	 * @return Horde_Mime_Part
5639 5639
 	 */
5640
-	function getStructure($_uid, $_partID=null, $_folder=null, $_preserveSeen=false)
5640
+	function getStructure($_uid, $_partID = null, $_folder = null, $_preserveSeen = false)
5641 5641
 	{
5642
-		if (self::$debug) error_log( __METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5642
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5643 5643
 
5644 5644
 		if (empty($_folder))
5645 5645
 		{
5646
-			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5646
+			$_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5647 5647
 		}
5648 5648
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5649 5649
 		if (!(is_object($_uid) || is_array($_uid))) $uid = (array)$_uid;
@@ -5663,13 +5663,13 @@  discard block
 block discarded – undo
5663 5663
 			if (is_object($mail))
5664 5664
 			{
5665 5665
 				$structure = $mail->getStructure();
5666
-				$isSmime = Mail\Smime::isSmime(($mimeType = $structure->getType())) || Mail\Smime::isSmime(($protocol=$structure->getContentTypeParameter('protocol')));
5666
+				$isSmime = Mail\Smime::isSmime(($mimeType = $structure->getType())) || Mail\Smime::isSmime(($protocol = $structure->getContentTypeParameter('protocol')));
5667 5667
 				if ($isSmime && !class_exists('mail_zpush', false))
5668 5668
 				{
5669 5669
 					return $this->resolveSmimeMessage($structure, array(
5670 5670
 						'uid' => $_uid,
5671 5671
 						'mailbox' => $_folder,
5672
-						'mimeType' => Mail\Smime::isSmime($protocol) ? $protocol: $mimeType
5672
+						'mimeType' => Mail\Smime::isSmime($protocol) ? $protocol : $mimeType
5673 5673
 					));
5674 5674
 				}
5675 5675
 				return $mail->getStructure();
@@ -5705,14 +5705,14 @@  discard block
 block discarded – undo
5705 5705
 	 * @param string $_folder folder to work on
5706 5706
 	 * @return array  an array of information about the attachment: array of array(name, size, mimeType, partID, encoding)
5707 5707
 	 */
5708
-	function getMessageAttachments($_uid, $_partID=null, Horde_Mime_Part $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=false, $resolveTNEF=true, $_folder='')
5708
+	function getMessageAttachments($_uid, $_partID = null, Horde_Mime_Part $_structure = null, $fetchEmbeddedImages = true, $fetchTextCalendar = false, $resolveTNEF = true, $_folder = '')
5709 5709
 	{
5710
-		if (self::$debug) error_log( __METHOD__.":$_uid, $_partID");
5711
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5710
+		if (self::$debug) error_log(__METHOD__.":$_uid, $_partID");
5711
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5712 5712
 		$attachments = array();
5713 5713
 		if (!isset($_structure))
5714 5714
 		{
5715
-			$_structure = $this->getStructure($_uid, $_partID,$_folder,true);
5715
+			$_structure = $this->getStructure($_uid, $_partID, $_folder, true);
5716 5716
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.print_r($_structure->contentTypeMap(),true));
5717 5717
 		}
5718 5718
 		if (!$_structure || !$_structure->contentTypeMap()) return array();
@@ -5720,7 +5720,7 @@  discard block
 block discarded – undo
5720 5720
 		$skipParts = array();
5721 5721
 		$tnefParts = array();
5722 5722
 		$skip = 0;
5723
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
5723
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
5724 5724
 		{
5725 5725
 			// skip multipart/encrypted incl. its two sub-parts, as we show 2. sub-part as body to be decrypted client-side
5726 5726
 			if ($mime_type == 'multipart/encrypted')
@@ -5728,7 +5728,7 @@  discard block
 block discarded – undo
5728 5728
 				$skip = 2;
5729 5729
 				continue;
5730 5730
 			}
5731
-			elseif($skip)
5731
+			elseif ($skip)
5732 5732
 			{
5733 5733
 				$skip--;
5734 5734
 				continue;
@@ -5742,10 +5742,10 @@  discard block
 block discarded – undo
5742 5742
 			$partPrimaryType = $part->getPrimaryType();
5743 5743
 			// we only want to retrieve the attachments of the current mail, not those of possible
5744 5744
 			// attached mails
5745
-			if ($mime_type=='message/rfc822' && $_partID!=$mime_id)
5745
+			if ($mime_type == 'message/rfc822' && $_partID != $mime_id)
5746 5746
 			{
5747 5747
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
5748
-				foreach($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
5748
+				foreach ($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
5749 5749
 			}
5750 5750
 			if (empty($partDisposition) && $partPrimaryType != 'multipart' && $partPrimaryType != 'text')
5751 5751
 			{
@@ -5753,27 +5753,27 @@  discard block
 block discarded – undo
5753 5753
 				// attachment with no link to show the attachment inline.
5754 5754
 				// Considering this: we "list" everything that matches the above criteria
5755 5755
 				// as attachment in order to not loose/miss information on our data
5756
-				$partDisposition='attachment';
5756
+				$partDisposition = 'attachment';
5757 5757
 			}
5758 5758
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($skipParts));
5759
-			if (array_key_exists($mime_id,$skipParts)) continue;
5759
+			if (array_key_exists($mime_id, $skipParts)) continue;
5760 5760
 
5761 5761
 			if ($partDisposition == 'attachment' ||
5762
-				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId()=='') ||
5762
+				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId() == '') ||
5763 5763
 				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType != 'image' && $partPrimaryType != 'text' && $partPrimaryType != 'multipart') ||
5764
-				($mime_type=='image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5764
+				($mime_type == 'image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5765 5765
 				($fetchEmbeddedImages && ($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image') ||
5766 5766
 				($fetchTextCalendar && $partPrimaryType == 'text' && $part->getSubType() == 'calendar'))
5767 5767
 			{
5768 5768
 				// if type is message/rfc822 and _partID is given, and MimeID equals partID
5769 5769
 				// we attempt to fetch "ourselves"
5770
-				if ($_partID==$part->getMimeId() && $part->getPrimaryType()=='message') continue;
5770
+				if ($_partID == $part->getMimeId() && $part->getPrimaryType() == 'message') continue;
5771 5771
 				$attachment = $part->getAllDispositionParameters();
5772 5772
 				$attachment['disposition'] = $part->getDisposition();
5773 5773
 				$attachment['mimeType'] = $mime_type;
5774 5774
 				$attachment['uid'] = $_uid;
5775 5775
 				$attachment['partID'] = $mime_id;
5776
-				if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5776
+				if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5777 5777
 				if ($fetchTextCalendar)
5778 5778
 				{
5779 5779
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part->getAllContentTypeParameters()));
@@ -5783,11 +5783,11 @@  discard block
 block discarded – undo
5783 5783
 				}
5784 5784
 				$attachment['size'] = $part->getBytes();
5785 5785
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5786
-				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);
5786
+				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);
5787 5787
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($attachment));
5788 5788
 				//typical winmail.dat attachment is
5789 5789
 				//Array([size] => 1462762[filename] => winmail.dat[mimeType] => application/ms-tnef[uid] => 100[partID] => 2[name] => winmail.dat)
5790
-				if ($resolveTNEF && ($attachment['mimeType']=='application/ms-tnef' || !strcasecmp($attachment['name'],'winmail.dat')))
5790
+				if ($resolveTNEF && ($attachment['mimeType'] == 'application/ms-tnef' || !strcasecmp($attachment['name'], 'winmail.dat')))
5791 5791
 				{
5792 5792
 					$tnefParts[] = $attachment;
5793 5793
 				}
@@ -5802,31 +5802,31 @@  discard block
 block discarded – undo
5802 5802
 			//error_log(__METHOD__.__LINE__.array2string($tnefParts));
5803 5803
 			foreach ($tnefParts as $k => $tnp)
5804 5804
 			{
5805
-				$tnefResolved=false;
5806
-				$tnef_data = $this->getAttachment($tnp['uid'],$tnp['partID'],$k,false);
5805
+				$tnefResolved = false;
5806
+				$tnef_data = $this->getAttachment($tnp['uid'], $tnp['partID'], $k, false);
5807 5807
 				$myTnef = $this->tnef_decoder($tnef_data['attachment']);
5808 5808
 				//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
5809 5809
 				// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
5810 5810
 				// we need to build Something that meets the needs
5811 5811
 				if ($myTnef)
5812 5812
 				{
5813
-					foreach($myTnef->getParts() as $mime_id => $part)
5813
+					foreach ($myTnef->getParts() as $mime_id => $part)
5814 5814
 					{
5815
-						$tnefResolved=true;
5815
+						$tnefResolved = true;
5816 5816
 						$attachment = $part->getAllDispositionParameters();
5817 5817
 						$attachment['disposition'] = $part->getDisposition();
5818 5818
 						$attachment['mimeType'] = $part->getType();
5819 5819
 						$attachment['uid'] = $tnp['uid'];
5820 5820
 						$attachment['partID'] = $tnp['partID'];
5821 5821
 						$attachment['is_winmail'] = $tnp['uid'].'@'.$tnp['partID'].'@'.$mime_id;
5822
-						if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5822
+						if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5823 5823
 						$attachment['size'] = $part->getBytes();
5824 5824
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5825
-						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']);
5825
+						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']);
5826 5826
 						$attachments[] = $attachment;
5827 5827
 					}
5828 5828
 				}
5829
-				if ($tnefResolved===false) $attachments[]=$tnp;
5829
+				if ($tnefResolved === false) $attachments[] = $tnp;
5830 5830
 			}
5831 5831
 		}
5832 5832
 		//error_log(__METHOD__.__LINE__.array2string($attachments));
@@ -5841,9 +5841,9 @@  discard block
 block discarded – undo
5841 5841
 	 * @return boolean|Horde_Mime_part Multipart/Mixed part decoded attachments |
5842 5842
 	 *	return false if there's no attachments or failure
5843 5843
 	 */
5844
-	public function tnef_decoder( $data )
5844
+	public function tnef_decoder($data)
5845 5845
 	{
5846
-		foreach(array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5846
+		foreach (array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5847 5847
 		{
5848 5848
 			if (!class_exists($class))
5849 5849
 			{
@@ -5875,7 +5875,7 @@  discard block
 block discarded – undo
5875 5875
 				$tmp_part->setContents($data['stream']);
5876 5876
 				$tmp_part->setDescription($data['name']);
5877 5877
 
5878
-				$type = $data['type'] . '/' . $data['subtype'];
5878
+				$type = $data['type'].'/'.$data['subtype'];
5879 5879
 				if (in_array($type, array('application/octet-stream', 'application/base64')))
5880 5880
 				{
5881 5881
 					$type = Horde_Mime_Magic::filenameToMIME($data['name']);
@@ -5919,24 +5919,24 @@  discard block
 block discarded – undo
5919 5919
 	 *
5920 5920
 	 * @return array returns an array of all resolved embeded attachments from winmail.dat
5921 5921
 	 */
5922
-	function getTnefAttachments ($_uid, $_partID, $_stream=false, $_folder=null)
5922
+	function getTnefAttachments($_uid, $_partID, $_stream = false, $_folder = null)
5923 5923
 	{
5924
-		$tnef_data = $this->getAttachment($_uid, $_partID,0,false, false , $_folder);
5924
+		$tnef_data = $this->getAttachment($_uid, $_partID, 0, false, false, $_folder);
5925 5925
 		$tnef_parts = $this->tnef_decoder($tnef_data['attachment']);
5926 5926
 		$attachments = array();
5927 5927
 		if ($tnef_parts)
5928 5928
 		{
5929
-			foreach($tnef_parts->getParts() as $mime_id => $part)
5929
+			foreach ($tnef_parts->getParts() as $mime_id => $part)
5930 5930
 			{
5931 5931
 
5932 5932
 				$attachment = $part->getAllDispositionParameters();
5933 5933
 				$attachment['mimeType'] = $part->getType();
5934
-				if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5934
+				if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5935 5935
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5936 5936
 				if (empty($attachment['filename']))
5937 5937
 				{
5938
-					$attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?
5939
-						$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5938
+					$attachment['filename'] = (isset($attachment['cid']) && !empty($attachment['cid']) ?
5939
+						$attachment['cid'] : lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5940 5940
 				}
5941 5941
 
5942 5942
 				$attachment['attachment'] = $part->getContents(array('stream'=>$_stream));
@@ -5960,10 +5960,10 @@  discard block
 block discarded – undo
5960 5960
 	 *
5961 5961
 	 * @return array
5962 5962
 	 */
5963
-	function getAttachment($_uid, $_partID, $_winmail_nr=0, $_returnPart=true, $_stream=false, $_folder=null)
5963
+	function getAttachment($_uid, $_partID, $_winmail_nr = 0, $_returnPart = true, $_stream = false, $_folder = null)
5964 5964
 	{
5965 5965
 		//error_log(__METHOD__.__LINE__."Uid:$_uid, PartId:$_partID, WinMailNr:$_winmail_nr, ReturnPart:$_returnPart, Stream:$_stream, Folder:$_folder".function_backtrace());
5966
-		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5966
+		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5967 5967
 
5968 5968
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5969 5969
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
@@ -5976,13 +5976,13 @@  discard block
 block discarded – undo
5976 5976
 			'ids' => $uidsToFetch,
5977 5977
 		));
5978 5978
 		if (is_object($headersNew)) {
5979
-			foreach($headersNew as $id=>$_headerObject) {
5979
+			foreach ($headersNew as $id=>$_headerObject) {
5980 5980
 				$body = $_headerObject->getFullMsg();
5981 5981
 				if ($_partID != '')
5982 5982
 				{
5983 5983
 					$mailStructureObject = $_headerObject->getStructure();
5984 5984
 					if (!class_exists('mail_zpush', false) && (Mail\Smime::isSmime(($mimeType = $mailStructureObject->getType())) ||
5985
-							Mail\Smime::isSmime(($protocol=$mailStructureObject->getContentTypeParameter('protocol')))))
5985
+							Mail\Smime::isSmime(($protocol = $mailStructureObject->getContentTypeParameter('protocol')))))
5986 5986
 					{
5987 5987
 						$mailStructureObject = $this->resolveSmimeMessage($mailStructureObject, array(
5988 5988
 							'uid' => $_uid,
@@ -5993,29 +5993,29 @@  discard block
 block discarded – undo
5993 5993
 					}
5994 5994
 					$mailStructureObject->contentTypeMap();
5995 5995
 					$part = $mailStructureObject->getPart($_partID);
5996
-					$partDisposition = ($part?$part->getDisposition():'failed');
5997
-					if ($partDisposition=='failed')
5996
+					$partDisposition = ($part ? $part->getDisposition() : 'failed');
5997
+					if ($partDisposition == 'failed')
5998 5998
 					{
5999 5999
 						error_log(__METHOD__.'('.__LINE__.'):'.array2string($_uid).','.$_partID.' ID:'.$id.' HObject:'.array2string($_headerObject).' StructureObject:'.array2string($mailStructureObject->contentTypeMap()).'->'.function_backtrace());
6000 6000
 					}
6001 6001
 					// if $partDisposition is empty, we assume attachment, and hope that the function
6002 6002
 					// itself is only triggered to fetch attachments
6003
-					if (empty($partDisposition)) $partDisposition='attachment';
6004
-					if ($part && ($partDisposition=='attachment' || $partDisposition=='inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
6003
+					if (empty($partDisposition)) $partDisposition = 'attachment';
6004
+					if ($part && ($partDisposition == 'attachment' || $partDisposition == 'inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
6005 6005
 					{
6006 6006
 						//$headerObject=$part->getAllDispositionParameters();//not used anywhere around here
6007 6007
 						$structure_mime = $part->getType();
6008 6008
 						$filename = $part->getName();
6009 6009
 						$charset = $part->getContentTypeParameter('charset');
6010 6010
 						//$structure_bytes = $part->getBytes(); $structure_partID=$part->getMimeId(); error_log(__METHOD__.__LINE__." fetchPartContents(".array2string($_uid).", $structure_partID, $_stream, $_preserveSeen,$structure_mime)" );
6011
-						if (empty($part->getContents())) $this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen=true,$structure_mime);
6011
+						if (empty($part->getContents())) $this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen = true, $structure_mime);
6012 6012
 						if ($_returnPart) return $part;
6013 6013
 					}
6014 6014
 				}
6015 6015
 			}
6016 6016
 		}
6017 6017
 		$ext = MimeMagic::mime2ext($structure_mime);
6018
-		if ($ext && stripos($filename,'.')===false && stripos($filename,$ext)===false) $filename = trim($filename).'.'.$ext;
6018
+		if ($ext && stripos($filename, '.') === false && stripos($filename, $ext) === false) $filename = trim($filename).'.'.$ext;
6019 6019
 		if (!$part)
6020 6020
 		{
6021 6021
 			throw new Exception\WrongParameter("Error: Could not fetch attachment for Uid=".array2string($_uid).", PartId=$_partID, WinMailNr=$_winmail_nr, folder=$_folder");
@@ -6033,20 +6033,20 @@  discard block
 block discarded – undo
6033 6033
 		// try guessing the mimetype, if we get the application/octet-stream
6034 6034
 		if (strtolower($attachmentData['type']) == 'application/octet-stream') $attachmentData['type'] = MimeMagic::filename2mime($attachmentData['filename']);
6035 6035
 		# if the attachment holds a winmail number and is a winmail.dat then we have to handle that.
6036
-		if ( $filename == 'winmail.dat' && $_winmail_nr)
6036
+		if ($filename == 'winmail.dat' && $_winmail_nr)
6037 6037
 		{
6038 6038
 			//by now _uid is of type array
6039
-			$tnefResolved=false;
6040
-			$wantedPart=$_uid[0].'@'.$_partID;
6039
+			$tnefResolved = false;
6040
+			$wantedPart = $_uid[0].'@'.$_partID;
6041 6041
 			$myTnef = $this->tnef_decoder($attachmentData['attachment']);
6042 6042
 			//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
6043 6043
 			// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
6044 6044
 			// we need to build Something that meets the needs
6045 6045
 			if ($myTnef)
6046 6046
 			{
6047
-				foreach($myTnef->getParts() as $mime_id => $part)
6047
+				foreach ($myTnef->getParts() as $mime_id => $part)
6048 6048
 				{
6049
-					$tnefResolved=true;
6049
+					$tnefResolved = true;
6050 6050
 					$attachment = $part->getAllDispositionParameters();
6051 6051
 					$attachment['mimeType'] = $part->getType();
6052 6052
 					//error_log(__METHOD__.__LINE__.'#'.$mime_id.'#'.$filename.'#'.array2string($attachment));
@@ -6054,9 +6054,9 @@  discard block
 block discarded – undo
6054 6054
 					if ($_winmail_nr == $wantedPart.'@'.$mime_id)
6055 6055
 					{
6056 6056
 						//error_log(__METHOD__.__LINE__.'#'.$structure_mime.'#'.$filename.'#'.array2string($attachment));
6057
-						if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
6057
+						if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
6058 6058
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
6059
-						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']);
6059
+						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']);
6060 6060
 						$wmattach = $attachment;
6061 6061
 						$wmattach['attachment'] = $part->getContents(array('stream'=>$_stream));
6062 6062
 
@@ -6066,7 +6066,7 @@  discard block
 block discarded – undo
6066 6066
 			if ($tnefResolved)
6067 6067
 			{
6068 6068
 				$ext = MimeMagic::mime2ext($wmattach['mimeType']);
6069
-				if ($ext && stripos($wmattach['filename'],'.')===false && stripos($wmattach['filename'],$ext)===false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
6069
+				if ($ext && stripos($wmattach['filename'], '.') === false && stripos($wmattach['filename'], $ext) === false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
6070 6070
 				$attachmentData = array(
6071 6071
 					'type'       => $wmattach['mimeType'],
6072 6072
 					'filename'   => $wmattach['filename'],
@@ -6090,21 +6090,21 @@  discard block
 block discarded – undo
6090 6090
 	 *	true:
6091 6091
 	 * @return Horde_Mime_Part
6092 6092
 	 */
6093
-	function getAttachmentByCID($_uid, $_cid, $_part, $_stream=null)
6093
+	function getAttachmentByCID($_uid, $_cid, $_part, $_stream = null)
6094 6094
 	{
6095 6095
 		// some static variables to avoid fetching the same mail multiple times
6096
-		static $uid=null, $part=null, $structure=null;
6096
+		static $uid = null, $part = null, $structure = null;
6097 6097
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_cid, $_part");
6098 6098
 
6099
-		if(empty($_cid)) return false;
6099
+		if (empty($_cid)) return false;
6100 6100
 
6101 6101
 		if ($_uid != $uid || $_part != $part)
6102 6102
 		{
6103
-			$structure = $this->getStructure($uid=$_uid, $part=$_part);
6103
+			$structure = $this->getStructure($uid = $_uid, $part = $_part);
6104 6104
 		}
6105 6105
 		/** @var Horde_Mime_Part */
6106 6106
 		$attachment = null;
6107
-		foreach($structure->contentTypeMap() as $mime_id => $mime_type)
6107
+		foreach ($structure->contentTypeMap() as $mime_id => $mime_type)
6108 6108
 		{
6109 6109
 			$part = $structure->getPart($mime_id);
6110 6110
 
@@ -6156,16 +6156,16 @@  discard block
 block discarded – undo
6156 6156
 	 * @param string  $_mimetype to decide wether to try to fetch part as binary or not
6157 6157
 	 * @return Horde_Mime_Part
6158 6158
 	 */
6159
-	public function fetchPartContents($_uid, Horde_Mime_Part $part=null, $_stream=false, $_preserveSeen=false, $_mimetype=null)
6159
+	public function fetchPartContents($_uid, Horde_Mime_Part $part = null, $_stream = false, $_preserveSeen = false, $_mimetype = null)
6160 6160
 	{
6161
-		if (is_null($part)) return null;//new Horde_Mime_Part;
6161
+		if (is_null($part)) return null; //new Horde_Mime_Part;
6162 6162
 		$encoding = null;
6163 6163
 		$fetchAsBinary = true;
6164
-		if ($_mimetype && strtolower($_mimetype)=='message/rfc822') $fetchAsBinary = false;
6164
+		if ($_mimetype && strtolower($_mimetype) == 'message/rfc822') $fetchAsBinary = false;
6165 6165
 		// we need to set content on structure to decode transfer encoding
6166 6166
 		$part->setContents(
6167 6167
 			$this->getBodyPart($_uid, $part->getMimeId(), null, $_preserveSeen, $_stream, $encoding, $fetchAsBinary),
6168
-			array('encoding' => (!$fetchAsBinary&&!$encoding?'8bit':$encoding)));
6168
+			array('encoding' => (!$fetchAsBinary && !$encoding ? '8bit' : $encoding)));
6169 6169
 
6170 6170
 		return $part;
6171 6171
 	}
@@ -6183,17 +6183,17 @@  discard block
 block discarded – undo
6183 6183
 	 * @return the id of the message appended or exception
6184 6184
 	 * @throws Exception\WrongUserinput
6185 6185
 	 */
6186
-	function appendMessage($_folderName, $_header, $_body, $_flags='\\Recent')
6186
+	function appendMessage($_folderName, $_header, $_body, $_flags = '\\Recent')
6187 6187
 	{
6188 6188
 		if (!is_resource($_header))
6189 6189
 		{
6190
-			if (stripos($_header,'message-id:')===false)
6190
+			if (stripos($_header, 'message-id:') === false)
6191 6191
 			{
6192 6192
 				$_header = 'Message-ID: <'.self::getRandomString().'@localhost>'."\n".$_header;
6193 6193
 			}
6194 6194
 			//error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_header, $_body, $_flags");
6195
-			$_header = ltrim(str_replace("\n","\r\n",$_header));
6196
-			$_header .= str_replace("\n","\r\n",$_body);
6195
+			$_header = ltrim(str_replace("\n", "\r\n", $_header));
6196
+			$_header .= str_replace("\n", "\r\n", $_body);
6197 6197
 		}
6198 6198
 		// the recent flag is the default enforced here ; as we assume the _flags is always set,
6199 6199
 		// we default it to hordes default (Recent) (, other wise we should not pass the parameter
@@ -6211,7 +6211,7 @@  discard block
 block discarded – undo
6211 6211
 			// searched for the message-id then returning the uid found
6212 6212
 			//$dataNflags[] = array('data'=>array(array('t'=>'text','v'=>"$header"."$body")), 'flags'=>array($_flags));
6213 6213
 			$dataNflags[] = array('data' => $_header, 'flags'=>array($_flags));
6214
-			$messageid = $this->icServer->append($_folderName,$dataNflags);
6214
+			$messageid = $this->icServer->append($_folderName, $dataNflags);
6215 6215
 		}
6216 6216
 		catch (\Exception $e)
6217 6217
 		{
@@ -6223,7 +6223,7 @@  discard block
 block discarded – undo
6223 6223
 		//$messageid = true; // for debug reasons only
6224 6224
 		if ($messageid === true || empty($messageid)) // try to figure out the message uid
6225 6225
 		{
6226
-			$list = $this->getHeaders($_folderName, $_startMessage=1, 1, 'INTERNALDATE', true, array(),null, false);
6226
+			$list = $this->getHeaders($_folderName, $_startMessage = 1, 1, 'INTERNALDATE', true, array(), null, false);
6227 6227
 			if ($list)
6228 6228
 			{
6229 6229
 				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' MessageUid:'.$messageid.' but found:'.array2string($list));
@@ -6263,36 +6263,36 @@  discard block
 block discarded – undo
6263 6263
 	 *				'attachments'=>$attachments,
6264 6264
 	 *				'headers'=>$headers,; boolean false on failure
6265 6265
 	 */
6266
-	static function get_mailcontent(&$mailClass,$uid,$partid='',$mailbox='', $preserveHTML = false, $addHeaderSection=true, $includeAttachments=true)
6266
+	static function get_mailcontent(&$mailClass, $uid, $partid = '', $mailbox = '', $preserveHTML = false, $addHeaderSection = true, $includeAttachments = true)
6267 6267
 	{
6268 6268
 			//echo __METHOD__." called for $uid,$partid <br>";
6269
-			$headers = $mailClass->getMessageHeader($uid,$partid,true,false,$mailbox);
6269
+			$headers = $mailClass->getMessageHeader($uid, $partid, true, false, $mailbox);
6270 6270
 			if (empty($headers)) return false;
6271 6271
 			// dont force retrieval of the textpart, let mailClass preferences decide
6272
-			$bodyParts = $mailClass->getMessageBody($uid,($preserveHTML?'always_display':'only_if_no_text'),$partid,null,false,$mailbox);
6273
-			if(is_null($preserveHTML))
6272
+			$bodyParts = $mailClass->getMessageBody($uid, ($preserveHTML ? 'always_display' : 'only_if_no_text'), $partid, null, false, $mailbox);
6273
+			if (is_null($preserveHTML))
6274 6274
 			{
6275 6275
 				$html = static::getdisplayablebody(
6276 6276
 						$mailClass,
6277
-						$mailClass->getMessageBody($uid,'always_display',$partid,null,false,$mailbox),
6277
+						$mailClass->getMessageBody($uid, 'always_display', $partid, null, false, $mailbox),
6278 6278
 						true
6279 6279
 				);
6280 6280
 
6281 6281
 			}
6282 6282
 			// if we do not want HTML but there is no TextRepresentation with the message itself, try converting
6283
-			if ( !$preserveHTML && $bodyParts[0]['mimeType']=='text/html')
6283
+			if (!$preserveHTML && $bodyParts[0]['mimeType'] == 'text/html')
6284 6284
 			{
6285
-				foreach($bodyParts as $i => $part)
6285
+				foreach ($bodyParts as $i => $part)
6286 6286
 				{
6287
-					if ($bodyParts[$i]['mimeType']=='text/html')
6287
+					if ($bodyParts[$i]['mimeType'] == 'text/html')
6288 6288
 					{
6289
-						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'],$bodyParts[$i]['charSet'],true,$stripalltags=true);
6290
-						$bodyParts[$i]['mimeType']='text/plain';
6289
+						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'], $bodyParts[$i]['charSet'], true, $stripalltags = true);
6290
+						$bodyParts[$i]['mimeType'] = 'text/plain';
6291 6291
 					}
6292 6292
 				}
6293 6293
 			}
6294 6294
 			//error_log(array2string($bodyParts));
6295
-			$attachments = $includeAttachments?$mailClass->getMessageAttachments($uid,$partid,null,true,false,true,$mailbox):array();
6295
+			$attachments = $includeAttachments ? $mailClass->getMessageAttachments($uid, $partid, null, true, false, true, $mailbox) : array();
6296 6296
 
6297 6297
 			if ($mailClass->isSentFolder($mailbox)) $mailaddress = $headers['TO'];
6298 6298
 			elseif (isset($headers['FROM'])) $mailaddress = $headers['FROM'];
@@ -6303,7 +6303,7 @@  discard block
 block discarded – undo
6303 6303
 
6304 6304
 			$message = self::getdisplayableBody($mailClass, $bodyParts, $preserveHTML);
6305 6305
 			if ($preserveHTML && $mailClass->activeMimeType == 'text/plain') $message = '<pre>'.$message.'</pre>';
6306
-			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '',$preserveHTML) : '');
6306
+			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '', $preserveHTML) : '');
6307 6307
 			$message = $headdata.$message;
6308 6308
 			//echo __METHOD__.'<br>';
6309 6309
 			//_debug_array($attachments);
@@ -6319,25 +6319,25 @@  discard block
 block discarded – undo
6319 6319
 						//_debug_array($mailClass->getMessageHeader($uid, $attachment['partID']));
6320 6320
 						//_debug_array($mailClass->getMessageBody($uid,'', $attachment['partID']));
6321 6321
 						//_debug_array($mailClass->getMessageAttachments($uid, $attachment['partID']));
6322
-						$mailcontent = self::get_mailcontent($mailClass,$uid,$attachment['partID'],$mailbox);
6323
-						$headdata ='';
6322
+						$mailcontent = self::get_mailcontent($mailClass, $uid, $attachment['partID'], $mailbox);
6323
+						$headdata = '';
6324 6324
 						if ($mailcontent['headers'])
6325 6325
 						{
6326
-							$headdata = self::createHeaderInfoSection($mailcontent['headers'],'',$preserveHTML);
6326
+							$headdata = self::createHeaderInfoSection($mailcontent['headers'], '', $preserveHTML);
6327 6327
 						}
6328 6328
 						if ($mailcontent['message'])
6329 6329
 						{
6330
-							$tempname =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6330
+							$tempname = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6331 6331
 							$attachedMessages[] = array(
6332 6332
 								'type' => 'TEXT/PLAIN',
6333 6333
 								'name' => $mailcontent['subject'].'.txt',
6334 6334
 								'tmp_name' => $tempname,
6335 6335
 							);
6336
-							$tmpfile = fopen($tempname,'w');
6337
-							fwrite($tmpfile,$headdata.$mailcontent['message']);
6336
+							$tmpfile = fopen($tempname, 'w');
6337
+							fwrite($tmpfile, $headdata.$mailcontent['message']);
6338 6338
 							fclose($tmpfile);
6339 6339
 						}
6340
-						foreach($mailcontent['attachments'] as &$tmpval)
6340
+						foreach ($mailcontent['attachments'] as &$tmpval)
6341 6341
 						{
6342 6342
 							$attachedMessages[] = $tmpval;
6343 6343
 						}
@@ -6345,36 +6345,36 @@  discard block
 block discarded – undo
6345 6345
 					}
6346 6346
 					else
6347 6347
 					{
6348
-						$attachments[$num] = array_merge($attachments[$num],$mailClass->getAttachment($uid, $attachment['partID'],0,false,false));
6348
+						$attachments[$num] = array_merge($attachments[$num], $mailClass->getAttachment($uid, $attachment['partID'], 0, false, false));
6349 6349
 
6350
-						if (empty($attachments[$num]['attachment'])&&$attachments[$num]['cid'])
6350
+						if (empty($attachments[$num]['attachment']) && $attachments[$num]['cid'])
6351 6351
 						{
6352
-							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'],true);
6352
+							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'], true);
6353 6353
 							$attachments[$num]['attachment'] = $c->getContents();
6354 6354
 						}
6355 6355
 						// no attempt to convert, if we dont know about the charset
6356
-						if (isset($attachments[$num]['charset'])&&!empty($attachments[$num]['charset'])) {
6356
+						if (isset($attachments[$num]['charset']) && !empty($attachments[$num]['charset'])) {
6357 6357
 							// we do not try guessing the charset, if it is not set
6358 6358
 							//if ($attachments[$num]['charset']===false) $attachments[$num]['charset'] = Translation::detect_encoding($attachments[$num]['attachment']);
6359
-							Translation::convert($attachments[$num]['attachment'],$attachments[$num]['charset']);
6359
+							Translation::convert($attachments[$num]['attachment'], $attachments[$num]['charset']);
6360 6360
 						}
6361
-						if(in_array($attachments[$num]['name'], $file_list))
6361
+						if (in_array($attachments[$num]['name'], $file_list))
6362 6362
 						{
6363 6363
 							$dupe_count[$attachments[$num]['name']]++;
6364
-							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME) .
6365
-								' ('.($dupe_count[$attachments[$num]['name']] + 1).')' . '.' .
6364
+							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME).
6365
+								' ('.($dupe_count[$attachments[$num]['name']] + 1).')'.'.'.
6366 6366
 								pathinfo($attachments[$num]['name'], PATHINFO_EXTENSION);
6367 6367
 						}
6368 6368
 						$attachments[$num]['type'] = $attachments[$num]['mimeType'];
6369
-						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6370
-						$tmpfile = fopen($attachments[$num]['tmp_name'],'w');
6371
-						fwrite($tmpfile,$attachments[$num]['attachment']);
6369
+						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6370
+						$tmpfile = fopen($attachments[$num]['tmp_name'], 'w');
6371
+						fwrite($tmpfile, $attachments[$num]['attachment']);
6372 6372
 						fclose($tmpfile);
6373 6373
 						$file_list[] = $attachments[$num]['name'];
6374 6374
 						unset($attachments[$num]['attachment']);
6375 6375
 					}
6376 6376
 				}
6377
-				if (is_array($attachedMessages)) $attachments = array_merge($attachments,$attachedMessages);
6377
+				if (is_array($attachedMessages)) $attachments = array_merge($attachments, $attachedMessages);
6378 6378
 			}
6379 6379
 			$return = array(
6380 6380
 					'mailaddress'=>$mailaddress,
@@ -6383,7 +6383,7 @@  discard block
 block discarded – undo
6383 6383
 					'attachments'=>$attachments,
6384 6384
 					'headers'=>$headers,
6385 6385
 			);
6386
-			if($html)
6386
+			if ($html)
6387 6387
 			{
6388 6388
 				$return['html_message'] = $html;
6389 6389
 			}
@@ -6402,10 +6402,10 @@  discard block
 block discarded – undo
6402 6402
 	{
6403 6403
 		$c = 0;
6404 6404
 		// use the standardIdentity
6405
-		foreach($_identities as $key => $acc) {
6406
-			if ($c==0) $identity = $acc;
6405
+		foreach ($_identities as $key => $acc) {
6406
+			if ($c == 0) $identity = $acc;
6407 6407
 			//error_log(__METHOD__.__LINE__." $key == $_profile_id ");
6408
-			if ($key==$_profile_id) $identity = $acc;
6408
+			if ($key == $_profile_id) $identity = $acc;
6409 6409
 			$c++;
6410 6410
 		}
6411 6411
 		return $identity;
@@ -6417,29 +6417,29 @@  discard block
 block discarded – undo
6417 6417
 	 * @param bool createHTML do it with HTML breaks
6418 6418
 	 * @return string a preformatted string with the information of the header worked into it
6419 6419
 	 */
6420
-	static function createHeaderInfoSection($header,$headline='', $createHTML = false)
6420
+	static function createHeaderInfoSection($header, $headline = '', $createHTML = false)
6421 6421
 	{
6422 6422
 		$headdata = null;
6423 6423
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($header).function_backtrace());
6424
-		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML?"<br />":"\n");
6425
-		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML?"<br />":"\n");
6426
-		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML?"<br />":"\n");
6427
-		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML?"<br />":"\n");
6428
-		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML?"<br />":"\n");
6429
-		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML?"<br />":"\n");
6430
-		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML?"<br />":"\n");
6431
-		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML?"<br />":"\n");
6432
-		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] !='normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML?"<br />":"\n");
6424
+		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML ? "<br />" : "\n");
6425
+		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML ? "<br />" : "\n");
6426
+		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML ? "<br />" : "\n");
6427
+		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML ? "<br />" : "\n");
6428
+		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML ? "<br />" : "\n");
6429
+		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML ? "<br />" : "\n");
6430
+		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML ? "<br />" : "\n");
6431
+		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML ? "<br />" : "\n");
6432
+		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] != 'normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML ? "<br />" : "\n");
6433 6433
 		//if ($mailcontent['headers']['ORGANIZATION']) $headdata .= lang('organization').': '.$mailcontent['headers']['ORGANIZATION']."\
6434 6434
 		if (!empty($headdata))
6435 6435
 		{
6436
-			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML?"<br />":"\n").$headdata;
6437
-			if (empty($headline)) $headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'').$headdata;
6438
-			$headdata .= ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6436
+			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML ? "<br />" : "\n").$headdata;
6437
+			if (empty($headline)) $headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '').$headdata;
6438
+			$headdata .= ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6439 6439
 		}
6440 6440
 		else
6441 6441
 		{
6442
-			$headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6442
+			$headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6443 6443
 		}
6444 6444
 		return $headdata;
6445 6445
 	}
@@ -6477,8 +6477,8 @@  discard block
 block discarded – undo
6477 6477
 	 */
6478 6478
 	static function adaptSubjectForImport($subject)
6479 6479
 	{
6480
-		$subject = str_replace('$$','__',($subject?$subject:lang('(no subject)')));
6481
-		$subject = str_ireplace(array('[FWD]','[',']','{','}','<','>'),array('Fwd:',' ',' ',' ',' ',' ',' '),trim($subject));
6480
+		$subject = str_replace('$$', '__', ($subject ? $subject : lang('(no subject)')));
6481
+		$subject = str_ireplace(array('[FWD]', '[', ']', '{', '}', '<', '>'), array('Fwd:', ' ', ' ', ' ', ' ', ' ', ' '), trim($subject));
6482 6482
 		return $subject;
6483 6483
 	}
6484 6484
 
@@ -6490,15 +6490,15 @@  discard block
 block discarded – undo
6490 6490
 	static function convertAddressArrayToString($rfcAddressArray)
6491 6491
 	{
6492 6492
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($rfcAddressArray));
6493
-		$returnAddr ='';
6493
+		$returnAddr = '';
6494 6494
 		if (is_array($rfcAddressArray))
6495 6495
 		{
6496
-			foreach((array)$rfcAddressArray as $addressData) {
6496
+			foreach ((array)$rfcAddressArray as $addressData) {
6497 6497
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($addressData));
6498
-				if($addressData['MAILBOX_NAME'] == 'NIL') {
6498
+				if ($addressData['MAILBOX_NAME'] == 'NIL') {
6499 6499
 					continue;
6500 6500
 				}
6501
-				if(strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6501
+				if (strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6502 6502
 					continue;
6503 6503
 				}
6504 6504
 				if ($addressData['RFC822_EMAIL'])
@@ -6507,7 +6507,7 @@  discard block
 block discarded – undo
6507 6507
 				}
6508 6508
 				else
6509 6509
 				{
6510
-					$emailaddress = ($addressData['PERSONAL_NAME']?$addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>':$addressData['EMAIL']);
6510
+					$emailaddress = ($addressData['PERSONAL_NAME'] ? $addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>' : $addressData['EMAIL']);
6511 6511
 					$addressObjectA = self::parseAddressList($emailaddress);
6512 6512
 				}
6513 6513
 				$addressObject = $addressObjectA[0];
@@ -6516,7 +6516,7 @@  discard block
 block discarded – undo
6516 6516
 				//$mb =(string)$addressObject->mailbox;
6517 6517
 				//$h = (string)$addressObject->host;
6518 6518
 				//$p = (string)$addressObject->personal;
6519
-				$returnAddr .= (strlen($returnAddr)>0?',':'');
6519
+				$returnAddr .= (strlen($returnAddr) > 0 ? ',' : '');
6520 6520
 				//error_log(__METHOD__.' ('.__LINE__.') '.$p.' <'.$mb.'@'.$h.'>');
6521 6521
 				try {
6522 6522
 					$buff = imap_rfc822_write_address($addressObject->mailbox, Horde_Idna::decode($addressObject->host), $addressObject->personal);
@@ -6526,15 +6526,15 @@  discard block
 block discarded – undo
6526 6526
 					unset($e);
6527 6527
 					$buff = imap_rfc822_write_address($addressObject->mailbox, $addressObject->host, $addressObject->personal);
6528 6528
 				}
6529
-				$returnAddr .= str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$buff);
6529
+				$returnAddr .= str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $buff);
6530 6530
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Address: '.$returnAddr);
6531 6531
 			}
6532 6532
 		}
6533 6533
 		else
6534 6534
 		{
6535 6535
 			// do not mess with strings, return them untouched /* ToDo: validate string as Address */
6536
-			$rfcAddressArray = self::decode_header($rfcAddressArray,true);
6537
-			$rfcAddressArray = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$rfcAddressArray);
6536
+			$rfcAddressArray = self::decode_header($rfcAddressArray, true);
6537
+			$rfcAddressArray = str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $rfcAddressArray);
6538 6538
 			if (is_string($rfcAddressArray)) return $rfcAddressArray;
6539 6539
 		}
6540 6540
 		return $returnAddr;
@@ -6548,12 +6548,12 @@  discard block
 block discarded – undo
6548 6548
 	 * @param string &$err error-message on error
6549 6549
 	 * @return string/boolean merged content or false on error
6550 6550
 	 */
6551
-	static function merge($content,$ids,$mimetype='')
6551
+	static function merge($content, $ids, $mimetype = '')
6552 6552
 	{
6553 6553
 		$mergeobj = new Contacts\Merge();
6554 6554
 
6555
-		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ?'text/plain':'text/html');
6556
-		$rv = $mergeobj->merge_string($content,$ids,$err='',$mimetype, array(), self::$displayCharset);
6555
+		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ? 'text/plain' : 'text/html');
6556
+		$rv = $mergeobj->merge_string($content, $ids, $err = '', $mimetype, array(), self::$displayCharset);
6557 6557
 		if (empty($rv) && !empty($content) && !empty($err)) $rv = $content;
6558 6558
 		if (!empty($err) && !empty($content) && !empty($ids)) error_log(__METHOD__.' ('.__LINE__.') '.' Merge failed for Ids:'.array2string($ids).' ContentType:'.$mimetype.' Content:'.$content.' Reason:'.array2string($err));
6559 6559
 		return $rv;
@@ -6595,12 +6595,12 @@  discard block
 block discarded – undo
6595 6595
 		else
6596 6596
 			settype($bytes, 'integer');
6597 6597
 
6598
-		return $bytes . ' ' . $type ;
6598
+		return $bytes.' '.$type;
6599 6599
 	}
6600 6600
 
6601 6601
 	static function detect_qp(&$sting) {
6602 6602
 		$needle = '/(=[0-9][A-F])|(=[A-F][0-9])|(=[A-F][A-F])|(=[0-9][0-9])/';
6603
-		return preg_match("$needle",$string);
6603
+		return preg_match("$needle", $string);
6604 6604
 	}
6605 6605
 
6606 6606
 	/**
@@ -6613,11 +6613,11 @@  discard block
 block discarded – undo
6613 6613
 	 * @param string $_methodNline - Information where the log was taken
6614 6614
 	 * @return void
6615 6615
 	 */
6616
-	static function logRunTimes($_starttime,$_endtime=null,$_message='',$_methodNline='')
6616
+	static function logRunTimes($_starttime, $_endtime = null, $_message = '', $_methodNline = '')
6617 6617
 	{
6618 6618
 		if (is_null($_endtime)) $_endtime = microtime(true);
6619 6619
 		$usagetime = microtime(true) - $_starttime;
6620
-		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime,5).'(s) '.($_message?'Details:'.$_message:''));
6620
+		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime, 5).'(s) '.($_message ? 'Details:'.$_message : ''));
6621 6621
 	}
6622 6622
 
6623 6623
 	/**
@@ -6630,9 +6630,9 @@  discard block
 block discarded – undo
6630 6630
 	 *
6631 6631
 	 * @throws Exception\WrongUserinput
6632 6632
 	 */
6633
-	static function checkFileBasics(&$_formData, $IDtoAddToFileName='', $reqMimeType='message/rfc822')
6633
+	static function checkFileBasics(&$_formData, $IDtoAddToFileName = '', $reqMimeType = 'message/rfc822')
6634 6634
 	{
6635
-		if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6635
+		if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6636 6636
 
6637 6637
 		//error_log(__METHOD__.__FILE__.array2string($_formData).' Id:'.$IDtoAddToFileName.' ReqMimeType:'.$reqMimeType);
6638 6638
 		$importfailed = $tmpFileName = false;
@@ -6642,7 +6642,7 @@  discard block
 block discarded – undo
6642 6642
 			$importfailed = true;
6643 6643
 			$alert_msg .= lang("Empty file %1 ignored.", $_formData['name']);
6644 6644
 		}
6645
-		elseif (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6645
+		elseif (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6646 6646
 			realpath(dirname($_formData['file'])) == realpath($GLOBALS['egw_info']['server']['temp_dir']))
6647 6647
 		{
6648 6648
 			// ensure existance of eGW temp dir
@@ -6650,7 +6650,7 @@  discard block
 block discarded – undo
6650 6650
 			// and different from any other temp file location set in php.ini
6651 6651
 			if (!file_exists($GLOBALS['egw_info']['server']['temp_dir']))
6652 6652
 			{
6653
-				@mkdir($GLOBALS['egw_info']['server']['temp_dir'],0700);
6653
+				@mkdir($GLOBALS['egw_info']['server']['temp_dir'], 0700);
6654 6654
 			}
6655 6655
 
6656 6656
 			// if we were NOT able to create this temp directory, then make an ERROR report
@@ -6677,14 +6677,14 @@  discard block
 block discarded – undo
6677 6677
 			// maybe its application/octet-stream -> this may mean that we could not determine the type
6678 6678
 			// so we check for the suffix too
6679 6679
 			// trust vfs mime-types, trust the mimetype if it contains a method
6680
-			if ((substr($_formData['file'],0,6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'],'method=')===false)
6680
+			if ((substr($_formData['file'], 0, 6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'], 'method=') === false)
6681 6681
 			{
6682
-				$buff = explode('.',$_formData['name']);
6682
+				$buff = explode('.', $_formData['name']);
6683 6683
 				$suffix = '';
6684 6684
 				if (is_array($buff)) $suffix = array_pop($buff); // take the last extension to check with ext2mime
6685 6685
 				if (!empty($suffix)) $sfxMimeType = MimeMagic::ext2mime($suffix);
6686 6686
 				if (!empty($suffix) && !empty($sfxMimeType) &&
6687
-					(strlen(trim($_formData['type']))==0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6687
+					(strlen(trim($_formData['type'])) == 0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6688 6688
 				{
6689 6689
 					error_log(__METHOD__.' ('.__LINE__.') '.' Data:'.array2string($_formData));
6690 6690
 					error_log(__METHOD__.' ('.__LINE__.') '.' Form reported Mimetype:'.$_formData['type'].' but seems to be:'.$sfxMimeType);
@@ -6699,13 +6699,13 @@  discard block
 block discarded – undo
6699 6699
 			if ($reqMimeType)
6700 6700
 			{
6701 6701
 				// so if PHP did not pass any file_type info, then substitute the rfc default value
6702
-				if (substr(strtolower(trim($_formData['type'])),0,strlen($mime_type_default)) != $mime_type_default)
6702
+				if (substr(strtolower(trim($_formData['type'])), 0, strlen($mime_type_default)) != $mime_type_default)
6703 6703
 				{
6704 6704
 					if (!(strtolower(trim($_formData['type'])) == "application/octet-stream" && $sfxMimeType == $reqMimeType))
6705 6705
 					{
6706 6706
 						//error_log("Message rejected, no message/rfc. Is:".$_formData['type']);
6707 6707
 						$importfailed = true;
6708
-						$alert_msg .= lang("File rejected, no %2. Is:%1",$_formData['type'],$reqMimeType);
6708
+						$alert_msg .= lang("File rejected, no %2. Is:%1", $_formData['type'], $reqMimeType);
6709 6709
 					}
6710 6710
 					if ((strtolower(trim($_formData['type'])) != $reqMimeType && $sfxMimeType == $reqMimeType))
6711 6711
 					{
@@ -6714,17 +6714,17 @@  discard block
 block discarded – undo
6714 6714
 				}
6715 6715
 			}
6716 6716
 			// as FreeBSD seems to have problems with the generated temp names we append some more random stuff
6717
-			$randomString = chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90));
6717
+			$randomString = chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90));
6718 6718
 			$tmpFileName = $GLOBALS['egw_info']['user']['account_id'].
6719 6719
 				trim($IDtoAddToFileName).basename($_formData['file']).'_'.$randomString;
6720 6720
 
6721
-			if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs')
6721
+			if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs')
6722 6722
 			{
6723
-				$tmpFileName = $_formData['file'];	// no need to store it somewhere
6723
+				$tmpFileName = $_formData['file']; // no need to store it somewhere
6724 6724
 			}
6725 6725
 			elseif (is_uploaded_file($_formData['file']))
6726 6726
 			{
6727
-				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName);	// requirement for safe_mode!
6727
+				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName); // requirement for safe_mode!
6728 6728
 			}
6729 6729
 			else
6730 6730
 			{
@@ -6733,7 +6733,7 @@  discard block
 block discarded – undo
6733 6733
 		} else {
6734 6734
 			//error_log("Import of message ".$_formData['file']." failes to meet basic restrictions");
6735 6735
 			$importfailed = true;
6736
-			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.",$_formData['name']);
6736
+			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.", $_formData['name']);
6737 6737
 		}
6738 6738
 		if ($importfailed == true)
6739 6739
 		{
@@ -6741,7 +6741,7 @@  discard block
 block discarded – undo
6741 6741
 		}
6742 6742
 		else
6743 6743
 		{
6744
-			if (parse_url($tmpFileName,PHP_URL_SCHEME) == 'vfs')
6744
+			if (parse_url($tmpFileName, PHP_URL_SCHEME) == 'vfs')
6745 6745
 			{
6746 6746
 				Vfs::load_wrapper('vfs');
6747 6747
 			}
@@ -6766,7 +6766,7 @@  discard block
 block discarded – undo
6766 6766
 		$images = null;
6767 6767
 		if (preg_match_all("/(src|background)=\"(.*)\"/Ui", $_html2parse, $images) && isset($images[2]))
6768 6768
 		{
6769
-			foreach($images[2] as $i => $url)
6769
+			foreach ($images[2] as $i => $url)
6770 6770
 			{
6771 6771
 				//$isData = false;
6772 6772
 				$basedir = $data = '';
@@ -6780,20 +6780,20 @@  discard block
 block discarded – undo
6780 6780
 						$filename = basename($url); // need to resolve all sort of url
6781 6781
 						if (($directory = dirname($url)) == '.') $directory = '';
6782 6782
 						$ext = pathinfo($filename, PATHINFO_EXTENSION);
6783
-						$mimeType  = MimeMagic::ext2mime($ext);
6784
-						if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
6783
+						$mimeType = MimeMagic::ext2mime($ext);
6784
+						if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
6785 6785
 						$myUrl = $directory.$filename;
6786
-						if ($myUrl[0]=='/') // local path -> we only allow path's that are available via http/https (or vfs)
6786
+						if ($myUrl[0] == '/') // local path -> we only allow path's that are available via http/https (or vfs)
6787 6787
 						{
6788
-							$basedir = ($_SERVER['HTTPS']?'https://':'http://'.$_SERVER['HTTP_HOST']);
6788
+							$basedir = ($_SERVER['HTTPS'] ? 'https://' : 'http://'.$_SERVER['HTTP_HOST']);
6789 6789
 						}
6790 6790
 						// use vfs instead of url containing webdav.php
6791 6791
 						// ToDo: we should test if the webdav url is of our own scope, as we cannot handle foreign
6792 6792
 						// webdav.php urls as vfs
6793
-						if (strpos($myUrl,'/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6793
+						if (strpos($myUrl, '/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6794 6794
 						{
6795 6795
 							Vfs::load_wrapper('vfs');
6796
-							list(,$myUrl) = explode('/webdav.php',$myUrl,2);
6796
+							list(,$myUrl) = explode('/webdav.php', $myUrl, 2);
6797 6797
 							$basedir = 'vfs://default';
6798 6798
 							$needTempFile = false;
6799 6799
 						}
@@ -6806,11 +6806,11 @@  discard block
 block discarded – undo
6806 6806
 							// Strips the url and store it into a temp for further procss
6807 6807
 							$tmp_url = html_entity_decode($myUrl);
6808 6808
 
6809
-							parse_str(parse_url($tmp_url, PHP_URL_QUERY),$URI_params);
6809
+							parse_str(parse_url($tmp_url, PHP_URL_QUERY), $URI_params);
6810 6810
 							if ($URI_params['mailbox'] && $URI_params['uid'] && $URI_params['cid'])
6811 6811
 							{
6812 6812
 								$mail_bo->reopen(base64_decode($URI_params['mailbox']));
6813
-								$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']),base64_decode($URI_params['partID']),true);
6813
+								$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']), base64_decode($URI_params['partID']), true);
6814 6814
 								$mail_bo->closeConnection();
6815 6815
 								if ($attachment)
6816 6816
 								{
@@ -6821,32 +6821,32 @@  discard block
 block discarded – undo
6821 6821
 							}
6822 6822
 						}
6823 6823
 
6824
-						if ( strlen($basedir) > 1 && substr($basedir,-1) != '/' && $myUrl[0]!='/') { $basedir .= '/'; }
6825
-						if ($needTempFile && !$attachment && substr($myUrl,0,4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6824
+						if (strlen($basedir) > 1 && substr($basedir, -1) != '/' && $myUrl[0] != '/') { $basedir .= '/'; }
6825
+						if ($needTempFile && !$attachment && substr($myUrl, 0, 4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6826 6826
 					}
6827
-					if (substr($url,0,strlen('data:'))=='data:')
6827
+					if (substr($url, 0, strlen('data:')) == 'data:')
6828 6828
 					{
6829 6829
 						//error_log(__METHOD__.' ('.__LINE__.') '.' -> '.$i.': '.array2string($images[$i]));
6830 6830
 						// we only support base64 encoded data
6831
-						$tmp = substr($url,strlen('data:'));
6832
-						list($mimeType,$data_base64) = explode(';base64,',$tmp);
6831
+						$tmp = substr($url, strlen('data:'));
6832
+						list($mimeType, $data_base64) = explode(';base64,', $tmp);
6833 6833
 						$data = base64_decode($data_base64);
6834 6834
 						// FF currently does NOT add any mime-type
6835 6835
 						if (strtolower(substr($mimeType, 0, 6)) != 'image/')
6836 6836
 						{
6837 6837
 							$mimeType = MimeMagic::analyze_data($data);
6838 6838
 						}
6839
-						list($what,$exactly) = explode('/',$mimeType);
6839
+						list($what, $exactly) = explode('/', $mimeType);
6840 6840
 						$needTempFile = true;
6841
-						$filename = ($what?$what:'data').$imageC++.'.'.$exactly;
6841
+						$filename = ($what ? $what : 'data').$imageC++.'.'.$exactly;
6842 6842
 					}
6843 6843
 					if ($data || $needTempFile === false)
6844 6844
 					{
6845 6845
 						if ($needTempFile)
6846 6846
 						{
6847
-							$attachment_file =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6848
-							$tmpfile = fopen($attachment_file,'w');
6849
-							fwrite($tmpfile,$data);
6847
+							$attachment_file = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6848
+							$tmpfile = fopen($attachment_file, 'w');
6849
+							fwrite($tmpfile, $data);
6850 6850
 							fclose($tmpfile);
6851 6851
 						}
6852 6852
 						else
@@ -6857,7 +6857,7 @@  discard block
 block discarded – undo
6857 6857
 						// (or similar) in all cases (when cut&paste). This may lead to more attached files, in case
6858 6858
 						// we use the same image multiple times, but, if we do this, we should try to detect that
6859 6859
 						// on upload. filename itself is not sufficient to determine the sameness of images
6860
-						$cid = 'cid:' . md5($attachment_file);
6860
+						$cid = 'cid:'.md5($attachment_file);
6861 6861
 						if ($_mailObject->AddEmbeddedImage($attachment_file, substr($cid, 4), urldecode($filename), $mimeType) !== null)
6862 6862
 						{
6863 6863
 							//$_html2parse = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $_html2parse);
@@ -6865,10 +6865,10 @@  discard block
 block discarded – undo
6865 6865
 						}
6866 6866
 					}
6867 6867
 				}
6868
-				catch(\Exception $e)
6868
+				catch (\Exception $e)
6869 6869
 				{
6870 6870
 					// Something went wrong with this attachment.  Skip it.
6871
-					error_log("Error adding inline attachment.  " . $e->getMessage());
6871
+					error_log("Error adding inline attachment.  ".$e->getMessage());
6872 6872
 					error_log($e->getTraceAsString());
6873 6873
 				}
6874 6874
 				$attachments [] = array(
@@ -6893,10 +6893,10 @@  discard block
 block discarded – undo
6893 6893
 	 * @param string& $importID ID for the imported message, used by attachments to identify them unambiguously
6894 6894
 	 * @return mixed array of messages with success and failed messages or exception
6895 6895
 	 */
6896
-	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID='')
6896
+	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID = '')
6897 6897
 	{
6898 6898
 		$importfailed = false;
6899
-		$processStats = array('success'=>array(),'failed'=>array());
6899
+		$processStats = array('success'=>array(), 'failed'=>array());
6900 6900
 		if (empty($SendAndMergeTocontacts))
6901 6901
 		{
6902 6902
 			$importfailed = true;
@@ -6937,7 +6937,7 @@  discard block
 block discarded – undo
6937 6937
 				$_folder = $this->getSentFolder();
6938 6938
 			}
6939 6939
 			$delimiter = $this->getHierarchyDelimiter();
6940
-			if($_folder=='INBOX'.$delimiter) $_folder='INBOX';
6940
+			if ($_folder == 'INBOX'.$delimiter) $_folder = 'INBOX';
6941 6941
 			if ($importfailed === false)
6942 6942
 			{
6943 6943
 				$Subject = $mailObject->getHeader('Subject');
@@ -6955,16 +6955,16 @@  discard block
 block discarded – undo
6955 6955
 				{
6956 6956
 					$mailObject->clearReplyTos();
6957 6957
 					$activeMailProfiles = $this->mail->getAccountIdentities($this->profileID);
6958
-					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
6958
+					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
6959 6959
 
6960
-					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']),Mail::generateIdentityString($activeMailProfile,false));
6960
+					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']), Mail::generateIdentityString($activeMailProfile, false));
6961 6961
 				}
6962
-				if(count($SendAndMergeTocontacts) > 1)
6962
+				if (count($SendAndMergeTocontacts) > 1)
6963 6963
 				{
6964
-					foreach(Mailer::$type2header as $type => $h)
6964
+					foreach (Mailer::$type2header as $type => $h)
6965 6965
 					{
6966 6966
 						$header = $mailObject->getHeader(Mailer::$type2header[$type]);
6967
-						if(is_array($header)) $header = implode(', ',$header);
6967
+						if (is_array($header)) $header = implode(', ', $header);
6968 6968
 						$headers[$type] = $header;
6969 6969
 					}
6970 6970
 				}
@@ -6980,13 +6980,13 @@  discard block
 block discarded – undo
6980 6980
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6981 6981
 
6982 6982
 						// Parse destinations for placeholders
6983
-						foreach(Mailer::$type2header as $type => $h)
6983
+						foreach (Mailer::$type2header as $type => $h)
6984 6984
 						{
6985 6985
 							//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));
6986
-							$merged = $bo_merge->merge_string($headers[$type],$val,$e,'text/plain',array(),self::$displayCharset);
6986
+							$merged = $bo_merge->merge_string($headers[$type], $val, $e, 'text/plain', array(), self::$displayCharset);
6987 6987
 							$mailObject->clearAddresses($type);
6988
-							$mailObject->addAddress($merged,'',$type);
6989
-							if($type == 'to')
6988
+							$mailObject->addAddress($merged, '', $type);
6989
+							if ($type == 'to')
6990 6990
 							{
6991 6991
 								$email = $merged;
6992 6992
 							}
@@ -6999,26 +6999,26 @@  discard block
 block discarded – undo
6999 6999
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ID:'.$val.' Data:'.array2string($contact));
7000 7000
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
7001 7001
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
7002
-							if($email)
7002
+							if ($email)
7003 7003
 							{
7004 7004
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
7005 7005
 							}
7006 7006
 						}
7007 7007
 
7008 7008
 						$activeMailProfiles = $this->getAccountIdentities($this->profileID);
7009
-						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
7009
+						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
7010 7010
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($activeMailProfile));
7011 7011
 						$mailObject->setFrom($activeMailProfile['ident_email'],
7012
-							self::generateIdentityString($activeMailProfile,false));
7012
+							self::generateIdentityString($activeMailProfile, false));
7013 7013
 
7014 7014
 						$mailObject->removeHeader('Message-ID');
7015 7015
 						$mailObject->removeHeader('Date');
7016 7016
 						$mailObject->clearCustomHeaders();
7017 7017
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
7018 7018
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
7019
-						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));
7019
+						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));
7020 7020
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
7021
-						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));
7021
+						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));
7022 7022
 
7023 7023
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
7024 7024
 						// set a higher timeout for big messages
@@ -7030,7 +7030,7 @@  discard block
 block discarded – undo
7030 7030
 							$id = $this->appendMessage($_folder, $mailObject->getRaw(), '');
7031 7031
 							$importID = $id->current();
7032 7032
 						}
7033
-						catch(Exception $e) {
7033
+						catch (Exception $e) {
7034 7034
 							$sendOK = false;
7035 7035
 							$errorInfo = $e->getMessage();
7036 7036
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($errorInfo));
@@ -7044,47 +7044,47 @@  discard block
 block discarded – undo
7044 7044
 						$mailObject->clearCustomHeaders();
7045 7045
 
7046 7046
 						// Parse destinations for placeholders
7047
-						foreach(Mailer::$type2header as $type => $h)
7047
+						foreach (Mailer::$type2header as $type => $h)
7048 7048
 						{
7049 7049
 							$header = $mailObject->getHeader(Mailer::$type2header[$type]);
7050
-							if(is_array($header)) $header = implode(', ',$header);
7050
+							if (is_array($header)) $header = implode(', ', $header);
7051 7051
 							$mailObject->clearAddresses($type);
7052
-							$merged = $bo_merge->merge_string($header,$val,$e,'text/plain',array(),self::$displayCharset);
7052
+							$merged = $bo_merge->merge_string($header, $val, $e, 'text/plain', array(), self::$displayCharset);
7053 7053
 							//error_log($type . ': ' . $mailObject->getHeader(Mailer::$type2header[$type]) . ' -> ' .$merged);
7054
-							$mailObject->addAddress(trim($merged,'"'),'',$type);
7054
+							$mailObject->addAddress(trim($merged, '"'), '', $type);
7055 7055
 						}
7056 7056
 						$mailObject->forceBccHeader();
7057 7057
 
7058 7058
 						// No addresses from placeholders?  Treat it as just a contact ID
7059
-						if (count($mailObject->getAddresses('to',true)) == 0 &&
7059
+						if (count($mailObject->getAddresses('to', true)) == 0 &&
7060 7060
 							is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val)) // do the merge
7061 7061
 						{
7062 7062
 							$contact = $bo_merge->contacts->read($val);
7063 7063
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($contact));
7064 7064
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
7065 7065
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
7066
-							if($email)
7066
+							if ($email)
7067 7067
 							{
7068 7068
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
7069 7069
 							}
7070 7070
 						}
7071 7071
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
7072 7072
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
7073
-						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));
7073
+						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));
7074 7074
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
7075
-						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));
7075
+						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));
7076 7076
 						$_folder = $this->getDraftFolder();
7077 7077
 					}
7078 7078
 					if ($sendOK || $openAsDraft)
7079 7079
 					{
7080 7080
 						if ($openAsDraft)
7081 7081
 						{
7082
-							if($this->folderExists($_folder,true))
7082
+							if ($this->folderExists($_folder, true))
7083 7083
 							{
7084
-								if($this->isSentFolder($_folder))
7084
+								if ($this->isSentFolder($_folder))
7085 7085
 								{
7086 7086
 									$flags = '\\Seen';
7087
-								} elseif($this->isDraftFolder($_folder)) {
7087
+								} elseif ($this->isDraftFolder($_folder)) {
7088 7088
 									$flags = '\\Draft';
7089 7089
 								} else {
7090 7090
 									$flags = '';
@@ -7092,7 +7092,7 @@  discard block
 block discarded – undo
7092 7092
 								$savefailed = false;
7093 7093
 								try
7094 7094
 								{
7095
-									$messageUid =$this->appendMessage($_folder,
7095
+									$messageUid = $this->appendMessage($_folder,
7096 7096
 										$mailObject->getRaw(),
7097 7097
 										null,
7098 7098
 										$flags);
@@ -7100,10 +7100,10 @@  discard block
 block discarded – undo
7100 7100
 								catch (\Exception\WrongUserinput $e)
7101 7101
 								{
7102 7102
 									$savefailed = true;
7103
-									$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3",$Subject,$_folder,$e->getMessage());
7103
+									$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3", $Subject, $_folder, $e->getMessage());
7104 7104
 								}
7105 7105
 								// no send, save successful, and message_uid present
7106
-								if ($savefailed===false && $messageUid && is_null($sendOK))
7106
+								if ($savefailed === false && $messageUid && is_null($sendOK))
7107 7107
 								{
7108 7108
 									$importID = $messageUid;
7109 7109
 									$openComposeWindow = true;
@@ -7112,21 +7112,21 @@  discard block
 block discarded – undo
7112 7112
 							else
7113 7113
 							{
7114 7114
 								$savefailed = true;
7115
-								$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.",$Subject,$_folder);
7115
+								$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.", $Subject, $_folder);
7116 7116
 							}
7117 7117
 						}
7118 7118
 						if ($sendOK)
7119 7119
 						{
7120
-							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed?' but failed to store to Folder:'.$_folder:'');
7120
+							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed ? ' but failed to store to Folder:'.$_folder : '');
7121 7121
 						}
7122 7122
 						else
7123 7123
 						{
7124
-							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
7124
+							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
7125 7125
 						}
7126 7126
 					}
7127
-					if (!is_null($sendOK) && $sendOK===false && is_null($openComposeWindow))
7127
+					if (!is_null($sendOK) && $sendOK === false && is_null($openComposeWindow))
7128 7128
 					{
7129
-						$processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
7129
+						$processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
7130 7130
 					}
7131 7131
 				}
7132 7132
 			}
@@ -7205,16 +7205,16 @@  discard block
 block discarded – undo
7205 7205
 
7206 7206
 		if (is_string($message))
7207 7207
 		{
7208
-			$start = substr($message,0, strpos($message, $eol));
7208
+			$start = substr($message, 0, strpos($message, $eol));
7209 7209
 			$body = substr($message, strlen($start));
7210 7210
 			$hlength = strpos($start, $eol) ? strpos($start, $eol) : strlen($start);
7211
-			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0,$hlength));
7212
-			foreach($headers->toArray() as $header => $value)
7211
+			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0, $hlength));
7212
+			foreach ($headers->toArray() as $header => $value)
7213 7213
 			{
7214 7214
 				$needsReplacement = false;
7215
-				foreach((array)$value as $val)
7215
+				foreach ((array)$value as $val)
7216 7216
 				{
7217
-					if (strlen($val)+ strlen($header) > 900)
7217
+					if (strlen($val) + strlen($header) > 900)
7218 7218
 					{
7219 7219
 						$needsReplacement = $needsFix = true;
7220 7220
 					}
@@ -7236,7 +7236,7 @@  discard block
 block discarded – undo
7236 7236
 	 * @param boolean $force8bitOnPrimaryPart (default false. force transferEncoding and charset to 8bit/utf8 if we have a textpart as primaryPart)
7237 7237
 	 * @throws Exception\WrongParameter when the required Horde_Mail_Part not found
7238 7238
 	 */
7239
-	function parseRawMessageIntoMailObject(Mailer $mailer, $message, $force8bitOnPrimaryPart=false)
7239
+	function parseRawMessageIntoMailObject(Mailer $mailer, $message, $force8bitOnPrimaryPart = false)
7240 7240
 	{
7241 7241
 		if (is_string($message) || is_resource($message))
7242 7242
 		{
@@ -7245,7 +7245,7 @@  discard block
 block discarded – undo
7245 7245
 
7246 7246
 			$structure = Horde_Mime_Part::parseMessage($message);
7247 7247
 			//error_log(__METHOD__.__LINE__.'#'.$structure->getPrimaryType().'#');
7248
-			if ($force8bitOnPrimaryPart&&$structure->getPrimaryType()=='text')
7248
+			if ($force8bitOnPrimaryPart && $structure->getPrimaryType() == 'text')
7249 7249
 			{
7250 7250
 				$structure->setTransferEncoding('8bit');
7251 7251
 				$structure->setCharset('utf-8');
@@ -7257,19 +7257,18 @@  discard block
 block discarded – undo
7257 7257
 			// *** increase the header size limit to 32k to make sure most of the mails even with huge headers are
7258 7258
 			// covered. TODO: Not sure if we even need to cut of the header parts and not just passing the whole
7259 7259
 			// message to be parsed in order to get all headers, it needs more invetigation.
7260
-			$start = is_string($message) ? substr($message, 0, 32768) :
7261
-				(fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 32768));
7260
+			$start = is_string($message) ? substr($message, 0, 32768) : (fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 32768));
7262 7261
 
7263 7262
 			$length = strpos($start, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
7264
-			if ($length===false) $length = strlen($start);
7265
-			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0,$length));
7263
+			if ($length === false) $length = strlen($start);
7264
+			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0, $length));
7266 7265
 
7267
-			foreach($headers->toArray(array('nowrap' => true)) as $header => $value)
7266
+			foreach ($headers->toArray(array('nowrap' => true)) as $header => $value)
7268 7267
 			{
7269
-				foreach((array)$value as $n => $val)
7268
+				foreach ((array)$value as $n => $val)
7270 7269
 				{
7271 7270
 					$overwrite = !$n;
7272
-					switch($header)
7271
+					switch ($header)
7273 7272
 					{
7274 7273
 						case 'Content-Transfer-Encoding':
7275 7274
 							//as we parse the message and this sets the part with a Content-Transfer-Encoding, we
@@ -7296,7 +7295,7 @@  discard block
 block discarded – undo
7296 7295
 		}
7297 7296
 		else
7298 7297
 		{
7299
-			if (($type = gettype($message)) == 'object') $type = get_class ($message);
7298
+			if (($type = gettype($message)) == 'object') $type = get_class($message);
7300 7299
 			throw new Exception\WrongParameter('Wrong parameter type for message: '.$type);
7301 7300
 		}
7302 7301
 	}
@@ -7310,33 +7309,33 @@  discard block
 block discarded – undo
7310 7309
 	 * @param string $default_domain
7311 7310
 	 * @return Horde_Mail_Rfc822_List iteratable Horde_Mail_Rfc822_Address objects with attributes mailbox, host, personal and valid
7312 7311
 	 */
7313
-	public static function parseAddressList($addresses, $default_domain=null)
7312
+	public static function parseAddressList($addresses, $default_domain = null)
7314 7313
 	{
7315 7314
 		$rfc822 = new Horde_Mail_Rfc822();
7316 7315
 		$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
7317 7316
 		//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count.function_backtrace());
7318
-		if ((empty($ret) || $ret->count()==0)&& is_string($addresses) && strlen($addresses)>0)
7317
+		if ((empty($ret) || $ret->count() == 0) && is_string($addresses) && strlen($addresses) > 0)
7319 7318
 		{
7320 7319
 			$matches = array();
7321
-			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/",$addresses,$matches);
7320
+			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/", $addresses, $matches);
7322 7321
 			//error_log(__METHOD__.__LINE__.array2string($matches));
7323
-			foreach ($matches[0] as &$match) {$match = trim($match,', ');}
7324
-			$addresses = implode(',',$matches[0]);
7322
+			foreach ($matches[0] as &$match) {$match = trim($match, ', '); }
7323
+			$addresses = implode(',', $matches[0]);
7325 7324
 			//error_log(__METHOD__.__LINE__.array2string($addresses));
7326 7325
 			$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
7327 7326
 			//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count);
7328 7327
 		}
7329
-		$previousFailed=false;
7328
+		$previousFailed = false;
7330 7329
 		$ret2 = new Horde_Mail_Rfc822_List();
7331 7330
 		// handle known problems on emailaddresses
7332
-		foreach($ret as $i => $adr)
7331
+		foreach ($ret as $i => $adr)
7333 7332
 		{
7334 7333
 			//mailaddresses enclosed in single quotes like '[email protected]' show up as 'me as mailbox and you.com' as host
7335
-			if ($adr->mailbox && stripos($adr->mailbox,"'")== 0 &&
7336
-					$adr->host && stripos($adr->host,"'")== (strlen($adr->host) -1))
7334
+			if ($adr->mailbox && stripos($adr->mailbox, "'") == 0 &&
7335
+					$adr->host && stripos($adr->host, "'") == (strlen($adr->host) - 1))
7337 7336
 			{
7338
-				$adr->mailbox = str_replace("'","",$adr->mailbox);
7339
-				$adr->host = str_replace("'","",$adr->host);
7337
+				$adr->mailbox = str_replace("'", "", $adr->mailbox);
7338
+				$adr->host = str_replace("'", "", $adr->host);
7340 7339
 			}
7341 7340
 
7342 7341
 
@@ -7355,17 +7354,17 @@  discard block
 block discarded – undo
7355 7354
 			//#Horde_Mail_Rfc822_List Object([_data:protected] => Array(
7356 7355
 			//[0] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => Xr\xc3\xa4hlyz[_host:protected] => [_personal:protected] => )
7357 7356
 			//[1] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => mailboxpart1.mailboxpart2[_host:protected] => youthost.com[_personal:protected] => User))[_filter:protected] => Array()[_ptr:protected] => )#2#,
7358
-			if (strlen($adr->mailbox)==0||strlen($adr->host)==0)
7357
+			if (strlen($adr->mailbox) == 0 || strlen($adr->host) == 0)
7359 7358
 			{
7360
-				$remember = ($adr->mailbox?$adr->mailbox:($adr->host?$adr->host:''));
7361
-				$previousFailed=true;
7359
+				$remember = ($adr->mailbox ? $adr->mailbox : ($adr->host ? $adr->host : ''));
7360
+				$previousFailed = true;
7362 7361
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
7363 7362
 			}
7364 7363
 			else
7365 7364
 			{
7366
-				if ($previousFailed && $remember) $adr->personal = $remember. ' ' . $adr->personal;
7365
+				if ($previousFailed && $remember) $adr->personal = $remember.' '.$adr->personal;
7367 7366
 				$remember = '';
7368
-				$previousFailed=false;
7367
+				$previousFailed = false;
7369 7368
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
7370 7369
 				$ret2->add($adr);
7371 7370
 			}
@@ -7381,7 +7380,7 @@  discard block
 block discarded – undo
7381 7380
 	 * @param string $_folder
7382 7381
 	 * @return boolean
7383 7382
 	 */
7384
-	function sendMDN($uid,$_folder)
7383
+	function sendMDN($uid, $_folder)
7385 7384
 	{
7386 7385
 		$acc = Mail\Account::read($this->profileID);
7387 7386
 		$identity = Mail\Account::read_identity($acc['ident_id'], true, null, $acc);
@@ -7415,7 +7414,7 @@  discard block
 block discarded – undo
7415 7414
 	 */
7416 7415
 	function addAccount($_hookValues)
7417 7416
 	{
7418
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7417
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7419 7418
 
7420 7419
 	}
7421 7420
 
@@ -7429,7 +7428,7 @@  discard block
 block discarded – undo
7429 7428
 	 */
7430 7429
 	function deleteAccount($_hookValues)
7431 7430
 	{
7432
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7431
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7433 7432
 
7434 7433
 	}
7435 7434
 
@@ -7443,7 +7442,7 @@  discard block
 block discarded – undo
7443 7442
 	 */
7444 7443
 	function updateAccount($_hookValues)
7445 7444
 	{
7446
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7445
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7447 7446
 
7448 7447
 	}
7449 7448
 
@@ -7453,7 +7452,7 @@  discard block
 block discarded – undo
7453 7452
 	 *
7454 7453
 	 * @param array $_addresses Addresses
7455 7454
 	 */
7456
-	static function stripRFC822Addresses ($_addresses)
7455
+	static function stripRFC822Addresses($_addresses)
7457 7456
 	{
7458 7457
 		$matches = array();
7459 7458
 		foreach ($_addresses as &$address)
@@ -7489,18 +7488,18 @@  discard block
 block discarded – undo
7489 7488
  			'passphrase'	=> ''
7490 7489
 		), $_params);
7491 7490
 
7492
-		$metadata = array (
7493
-			 'mimeType' => $params['mimeType']?$params['mimeType']:$_mime_part->getType()
7491
+		$metadata = array(
7492
+			 'mimeType' => $params['mimeType'] ? $params['mimeType'] : $_mime_part->getType()
7494 7493
 		);
7495 7494
 		$this->smime = new Mail\Smime;
7496 7495
 		$message = $this->getMessageRawBody($params['uid'], null, $params['mailbox']);
7497 7496
 		if (!Mail\Smime::isSmimeSignatureOnly(Mail\Smime::getSmimeType($_mime_part)))
7498 7497
 		{
7499
-			try{
7500
-				$message = $this->_decryptSmimeBody($message, $params['passphrase'] !='' ?
7498
+			try {
7499
+				$message = $this->_decryptSmimeBody($message, $params['passphrase'] != '' ?
7501 7500
 						$params['passphrase'] : Api\Cache::getSession('mail', 'smime_passphrase'));
7502 7501
 			}
7503
-			catch(\Horde_Crypt_Exception $e)
7502
+			catch (\Horde_Crypt_Exception $e)
7504 7503
 			{
7505 7504
 				throw new Mail\Smime\PassphraseMissing(lang('Could not decrypt '.
7506 7505
 						'S/MIME data. This message may not be encrypted by your '.
@@ -7534,7 +7533,7 @@  discard block
 block discarded – undo
7534 7533
 			$from = $this->stripRFC822Addresses($envelope['FROM']);
7535 7534
 			$message_parts = $this->smime->extractSignedContents($message);
7536 7535
 			//$f = $message_parts->_headers->getHeader('from');
7537
-			$metadata = array_merge ($metadata, array (
7536
+			$metadata = array_merge($metadata, array(
7538 7537
 				'verify'		=> $cert->verify,
7539 7538
 				'cert'			=> $cert->cert,
7540 7539
 				'certDetails'	=> $this->smime->parseCert($cert->cert),
@@ -7546,7 +7545,7 @@  discard block
 block discarded – undo
7546 7545
 			// check for email address if both signer email address and
7547 7546
 			// email address of sender are the same. It also takes  subjectAltName emails into account.
7548 7547
 			if (is_array($from) && strcasecmp($from[0], $cert->email) != 0
7549
-					&& stripos($metadata['certDetails']['extensions']['subjectAltName'],$from[0]) === false)
7548
+					&& stripos($metadata['certDetails']['extensions']['subjectAltName'], $from[0]) === false)
7550 7549
 			{
7551 7550
 				$metadata['unknownemail'] = true;
7552 7551
 				$metadata['msg'] .= ' '.lang('Email address of signer is different from the email address of sender!');
@@ -7572,20 +7571,20 @@  discard block
 block discarded – undo
7572 7571
 	 * @return array|string return
7573 7572
 	 * @throws Horde_Crypt_Exception
7574 7573
 	 */
7575
-	private function _decryptSmimeBody ($_message, $_passphrase = '')
7574
+	private function _decryptSmimeBody($_message, $_passphrase = '')
7576 7575
 	{
7577 7576
 		$AB_bo   = new \addressbook_bo();
7578 7577
 		$acc_smime = Mail\Smime::get_acc_smime($this->profileID, $_passphrase);
7579 7578
 		$certkey = $AB_bo->get_smime_keys($acc_smime['acc_smime_username']);
7580 7579
 		if (!$this->smime->verifyPassphrase($acc_smime['pkey'], $_passphrase))
7581 7580
 		{
7582
-			return array (
7581
+			return array(
7583 7582
 				'password_required' => true,
7584 7583
 				'msg' => 'Authentication failure!'
7585 7584
 			);
7586 7585
 		}
7587 7586
 
7588
-		$params  = array (
7587
+		$params = array(
7589 7588
 			'type'      => 'message',
7590 7589
 			'pubkey'    => $certkey[$acc_smime['acc_smime_username']],
7591 7590
 			'privkey'   => $acc_smime['pkey'],
Please login to merge, or discard this patch.