Completed
Push — 16.1 ( a77ba1...044556 )
by Ralf
46:28 queued 29:30
created
api/src/Mail.php 1 patch
Spacing   +1157 added lines, -1158 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	 *
122 122
 	 * @array
123 123
 	 */
124
-	static $tidy_config = array('clean'=>false,'output-html'=>true,'join-classes'=>true,'join-styles'=>true,'show-body-only'=>"auto",'word-2000'=>true,'wrap'=>0);
124
+	static $tidy_config = array('clean'=>false, 'output-html'=>true, 'join-classes'=>true, 'join-styles'=>true, 'show-body-only'=>"auto", 'word-2000'=>true, 'wrap'=>0);
125 125
 
126 126
 	/**
127 127
 	 * static used to configure htmLawed, for use with emails
@@ -132,9 +132,9 @@  discard block
 block discarded – undo
132 132
 		'make_tag_strict' => 3, // 3 is a new own config value, to indicate that transformation is to be performed, but don't transform font as size transformation of numeric sizes to keywords alters the intended result too much
133 133
 		'keep_bad'=>2, //remove tags but keep element content (4 and 6 keep element content only if text (pcdata) is valid in parent element as per specs, this may lead to textloss if balance is switched on)
134 134
 		// we switch the balance off because of some broken html mails contents get removed like (td in table), and let browser deal with it
135
-		'balance'=>0,//turn off tag-balancing (config['balance']=>0). That will not introduce any security risk; only standards-compliant tag nesting check/filtering will be turned off (basic tag-balance will remain; i.e., there won't be any unclosed tag, etc., after filtering)
135
+		'balance'=>0, //turn off tag-balancing (config['balance']=>0). That will not introduce any security risk; only standards-compliant tag nesting check/filtering will be turned off (basic tag-balance will remain; i.e., there won't be any unclosed tag, etc., after filtering)
136 136
 		'direct_list_nest' => 1,
137
-		'allow_for_inline' => array('table','div','li','p'),//block elements allowed for nesting when only inline is allowed; Example span does not allow block elements as table; table is the only element tested so far
137
+		'allow_for_inline' => array('table', 'div', 'li', 'p'), //block elements allowed for nesting when only inline is allowed; Example span does not allow block elements as table; table is the only element tested so far
138 138
 		// tidy eats away even some wanted whitespace, so we switch it off;
139 139
 		// we used it for its compacting and beautifying capabilities, which resulted in better html for further processing
140 140
 		'tidy'=>0,
@@ -149,13 +149,13 @@  discard block
 block discarded – undo
149 149
 	 *
150 150
 	 * @array
151 151
 	 */
152
-	static $aclShortCuts = array('' => array('label'=>'none','title'=>'The user has no rights whatsoever.'),
153
-		'lrs'		=> array('label'=>'readable','title'=>'Allows a user to read the contents of the mailbox.'),
154
-		'lprs'		=> array('label'=>'post','title'=>'Allows a user to read the mailbox and post to it through the delivery system by sending mail to the submission address of the mailbox.'),
155
-		'ilprs'		=> array('label'=>'append','title'=>'Allows a user to read the mailbox and append messages to it, either via IMAP or through the delivery system.'),
156
-		'cdilprsw'	=> array('label'=>'write','title'=>'Allows a user to read the maibox, post to it, append messages to it, and delete messages or the mailbox itself. The only right not given is the right to change the ACL of the mailbox.'),
157
-		'acdilprsw'	=> array('label'=>'all','title'=>'The user has all possible rights on the mailbox. This is usually granted to users only on the mailboxes they own.'),
158
-		'custom'	=> array('label'=>'custom','title'=>'User defined combination of rights for the ACL'),
152
+	static $aclShortCuts = array('' => array('label'=>'none', 'title'=>'The user has no rights whatsoever.'),
153
+		'lrs'		=> array('label'=>'readable', 'title'=>'Allows a user to read the contents of the mailbox.'),
154
+		'lprs'		=> array('label'=>'post', 'title'=>'Allows a user to read the mailbox and post to it through the delivery system by sending mail to the submission address of the mailbox.'),
155
+		'ilprs'		=> array('label'=>'append', 'title'=>'Allows a user to read the mailbox and append messages to it, either via IMAP or through the delivery system.'),
156
+		'cdilprsw'	=> array('label'=>'write', 'title'=>'Allows a user to read the maibox, post to it, append messages to it, and delete messages or the mailbox itself. The only right not given is the right to change the ACL of the mailbox.'),
157
+		'acdilprsw'	=> array('label'=>'all', 'title'=>'The user has all possible rights on the mailbox. This is usually granted to users only on the mailboxes they own.'),
158
+		'custom'	=> array('label'=>'custom', 'title'=>'User defined combination of rights for the ACL'),
159 159
 	);
160 160
 
161 161
 	/**
@@ -197,13 +197,13 @@  discard block
 block discarded – undo
197 197
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
198 198
 	 * @return Mail
199 199
 	 */
200
-	public static function getInstance($_restoreSession=true, &$_profileID=0, $_validate=true, $_oldImapServerObject=false, $_reuseCache=null)
200
+	public static function getInstance($_restoreSession = true, &$_profileID = 0, $_validate = true, $_oldImapServerObject = false, $_reuseCache = null)
201 201
 	{
202 202
 		//$_restoreSession=false;
203 203
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
204 204
 		//error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID.'/'.Mail\Account::get_default_acc_id().' for user:'.$GLOBALS['egw_info']['user']['account_lid'].' called from:'.function_backtrace());
205 205
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_oldImapServerObject));
206
-		self::$profileDefunct = Cache::getCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),5*1);
206
+		self::$profileDefunct = Cache::getCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 5 * 1);
207 207
 		if (isset(self::$profileDefunct[$_profileID]) && strlen(self::$profileDefunct[$_profileID]))
208 208
 		{
209 209
 			throw new Exception(__METHOD__." failed to instanciate Mail for Profile #$_profileID Reason:".self::$profileDefunct[$_profileID]);
@@ -212,13 +212,13 @@  discard block
 block discarded – undo
212 212
 		{
213 213
 			if (!is_object(self::$instances[$_profileID]))
214 214
 			{
215
-				self::$instances[$_profileID] = new Mail('utf-8',false,$_profileID,false,$_reuseCache);
215
+				self::$instances[$_profileID] = new Mail('utf-8', false, $_profileID, false, $_reuseCache);
216 216
 			}
217 217
 			self::$instances[$_profileID]->icServer = $_oldImapServerObject;
218
-			self::$instances[$_profileID]->accountid= $_oldImapServerObject->ImapServerId;
219
-			self::$instances[$_profileID]->profileID= $_oldImapServerObject->ImapServerId;
218
+			self::$instances[$_profileID]->accountid = $_oldImapServerObject->ImapServerId;
219
+			self::$instances[$_profileID]->profileID = $_oldImapServerObject->ImapServerId;
220 220
 			self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
221
-			self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
221
+			self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
222 222
 			return self::$instances[$_profileID];
223 223
 		}
224 224
 		if ($_profileID == 0)
@@ -231,14 +231,14 @@  discard block
 block discarded – undo
231 231
 			{
232 232
 				$profileID = Mail\Account::get_default_acc_id();
233 233
 			}
234
-			if ($profileID!=$_profileID) $_restoreSession==false;
235
-			$_profileID=$profileID;
234
+			if ($profileID != $_profileID) $_restoreSession == false;
235
+			$_profileID = $profileID;
236 236
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' called with profileID==0 using '.$profileID.' instead->'.function_backtrace());
237 237
 		}
238 238
 		// no validation or restoreSession for old ImapServer Object, just fetch it and return it
239
-		if ($_oldImapServerObject===true)
239
+		if ($_oldImapServerObject === true)
240 240
 		{
241
-			return new Mail('utf-8',false,$_profileID,true,$_reuseCache);
241
+			return new Mail('utf-8', false, $_profileID, true, $_reuseCache);
242 242
 		}
243 243
 		if ($_profileID != 0 && $_validate)
244 244
 		{
@@ -258,9 +258,9 @@  discard block
 block discarded – undo
258 258
 			//Cache::setSession('mail','activeProfileID',$_profileID);
259 259
 		}
260 260
 		//error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID.' called from:'.function_backtrace());
261
-		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession===false))
261
+		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession === false))
262 262
 		{
263
-			self::$instances[$_profileID] = new Mail('utf-8',$_restoreSession,$_profileID,false,$_reuseCache);
263
+			self::$instances[$_profileID] = new Mail('utf-8', $_restoreSession, $_profileID, false, $_reuseCache);
264 264
 		}
265 265
 		else
266 266
 		{
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 				self::$instances[$_profileID]->ogServer = Mail\Account::read($_profileID)->smtpServer();
272 272
 				// TODO: merge mailprefs into userprefs, for easy treatment
273 273
 				self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
274
-				self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
274
+				self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
275 275
 			} catch (\Exception $e)
276 276
 			{
277 277
 				$newprofileID = Mail\Account::get_default_acc_id();
@@ -279,15 +279,15 @@  discard block
 block discarded – undo
279 279
 				error_log(__METHOD__.' ('.__LINE__.') '." Loading the Profile for ProfileID ".$_profileID.' failed for icServer; '.$e->getMessage().' Trigger new instance for Default-Profile '.$newprofileID.'. called from:'.function_backtrace());
280 280
 				if ($newprofileID)
281 281
 				{
282
-					self::$instances[$newprofileID] = new Mail('utf-8',false,$newprofileID,false,$_reuseCache);
282
+					self::$instances[$newprofileID] = new Mail('utf-8', false, $newprofileID, false, $_reuseCache);
283 283
 					$_profileID = $newprofileID;
284 284
 				}
285 285
 				else
286 286
 				{
287
-					throw new Exception(__METHOD__." failed to load the Profile for ProfileID for $_profileID with error:".$e->getMessage().($e->details?', '.$e->details:''));
287
+					throw new Exception(__METHOD__." failed to load the Profile for ProfileID for $_profileID with error:".$e->getMessage().($e->details ? ', '.$e->details : ''));
288 288
 				}
289 289
 			}
290
-			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate );
290
+			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate);
291 291
 		}
292 292
 		self::$instances[$_profileID]->profileID = $_profileID;
293 293
 		if (!isset(self::$instances[$_profileID]->idna2)) self::$instances[$_profileID]->idna2 = new Horde_Idna;
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 	public static function fixInvalidAliasAddress($refrence, $address)
309 309
 	{
310 310
 		$parts = explode('@', $refrence);
311
-		if (!strpos($address,'@') && !empty($parts[1])) $address .= '@'.$parts[1];
311
+		if (!strpos($address, '@') && !empty($parts[1])) $address .= '@'.$parts[1];
312 312
 		return $address;
313 313
 	}
314 314
 
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
 	 * @param boolean $_testConnection = 0
320 320
 	 * @return mixed $_profileID or false on failed ConnectionTest
321 321
 	 */
322
-	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID=0, $_testConnection=true)
322
+	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID = 0, $_testConnection = true)
323 323
 	{
324 324
 		if (isset($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']) && !empty($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']))
325 325
 		{
@@ -340,12 +340,12 @@  discard block
 block discarded – undo
340 340
 		}
341 341
 		if ($oldProfileID != $_profileID)
342 342
 		{
343
-			if ($oldProfileID && $_profileID==0) $_profileID = $oldProfileID;
344
-			$GLOBALS['egw']->preferences->add('mail','ActiveProfileID',$_profileID,'user');
343
+			if ($oldProfileID && $_profileID == 0) $_profileID = $oldProfileID;
344
+			$GLOBALS['egw']->preferences->add('mail', 'ActiveProfileID', $_profileID, 'user');
345 345
 			// save prefs
346 346
 			$GLOBALS['egw']->preferences->save_repository(true);
347 347
 			$GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $_profileID;
348
-			Cache::setSession('mail','activeProfileID',$_profileID);
348
+			Cache::setSession('mail', 'activeProfileID', $_profileID);
349 349
 		}
350 350
 		return $_profileID;
351 351
 	}
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 	 * @param int $_acc_id = 0
361 361
 	 * @return int validated acc_id -> either acc_id given, or first valid one
362 362
 	 */
363
-	public static function validateProfileID($_acc_id=0)
363
+	public static function validateProfileID($_acc_id = 0)
364 364
 	{
365 365
 		if ($_acc_id)
366 366
 		{
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 		}
380 380
 		// no account specified or specified account not found or not valid
381 381
 		// --> search existing account for first valid one and return that
382
-		foreach(Mail\Account::search($only_current_user=true, 'acc_imap_host') as $acc_id => $imap_host)
382
+		foreach (Mail\Account::search($only_current_user = true, 'acc_imap_host') as $acc_id => $imap_host)
383 383
 		{
384 384
 			if (!empty($imap_host) && ($account = Mail\Account::read($acc_id)) && $account->is_imap())
385 385
 			{
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 	 * @param boolean $_oldImapServerObject = false
402 402
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
403 403
 	 */
404
-	private function __construct($_displayCharset='utf-8',$_restoreSession=true, $_profileID=0, $_oldImapServerObject=false, $_reuseCache=null)
404
+	private function __construct($_displayCharset = 'utf-8', $_restoreSession = true, $_profileID = 0, $_oldImapServerObject = false, $_reuseCache = null)
405 405
 	{
406 406
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
407 407
 		if (!empty($_displayCharset)) self::$displayCharset = $_displayCharset;
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 			$firstMessage = $this->sessionData['previewMessage'];
422 422
 			$this->sessionData = array();
423 423
 		}
424
-		if (!$_reuseCache) $this->forcePrefReload($_profileID,!$_reuseCache);
424
+		if (!$_reuseCache) $this->forcePrefReload($_profileID, !$_reuseCache);
425 425
 		try
426 426
 		{
427 427
 			$this->profileID = self::validateProfileID($_profileID);
@@ -435,11 +435,11 @@  discard block
 block discarded – undo
435 435
 			throw new Exception(__METHOD__." failed to instanciate Mail for $_profileID / ".$this->profileID." with error:".$e->getMessage());
436 436
 		}
437 437
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($acc->imapServer()));
438
-		$this->icServer = ($_oldImapServerObject?$acc->oldImapServer():$acc->imapServer());
438
+		$this->icServer = ($_oldImapServerObject ? $acc->oldImapServer() : $acc->imapServer());
439 439
 		$this->ogServer = $acc->smtpServer();
440 440
 		// TODO: merge mailprefs into userprefs, for easy treatment
441 441
 		$this->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
442
-		$this->htmlOptions  = $this->mailPreferences['htmlOptions'];
442
+		$this->htmlOptions = $this->mailPreferences['htmlOptions'];
443 443
 		if (isset($this->icServer->ImapServerId) && !empty($this->icServer->ImapServerId))
444 444
 		{
445 445
 			$_profileID = $this->profileID = $GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $this->icServer->ImapServerId;
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 	public static function &forceEAProfileLoad($_profile_id)
458 458
 	{
459 459
 		self::unsetCachedObjects($_profile_id);
460
-		$mail = self::getInstance(false, $_profile_id,false);
460
+		$mail = self::getInstance(false, $_profile_id, false);
461 461
 		//_debug_array( $_profile_id);
462 462
 		$mail->icServer = Mail\Account::read($_profile_id)->imapServer();
463 463
 		$mail->ogServer = Mail\Account::read($_profile_id)->smtpServer();
@@ -469,11 +469,11 @@  discard block
 block discarded – undo
469 469
 	 * @param int $_profile_id
470 470
 	 * @param boolean $_resetFolderObjects
471 471
 	 */
472
-	public static function forcePrefReload($_profile_id=null,$_resetFolderObjects=true)
472
+	public static function forcePrefReload($_profile_id = null, $_resetFolderObjects = true)
473 473
 	{
474 474
 		// unset the mail_preferences session object, to force the reload/rebuild
475
-		Cache::setSession('mail','mail_preferences',serialize(array()));
476
-		Cache::setSession('emailadmin','session_data',serialize(array()));
475
+		Cache::setSession('mail', 'mail_preferences', serialize(array()));
476
+		Cache::setSession('emailadmin', 'session_data', serialize(array()));
477 477
 		if ($_resetFolderObjects) self::resetFolderObjectCache($_profile_id);
478 478
 	}
479 479
 
@@ -482,8 +482,8 @@  discard block
 block discarded – undo
482 482
 	 */
483 483
 	function restoreSessionData()
484 484
 	{
485
-		$this->sessionData = array();//Cache::getCache(Cache::SESSION,'mail','session_data',$callback=null,$callback_params=array(),$expiration=60*60*1);
486
-		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
485
+		$this->sessionData = array(); //Cache::getCache(Cache::SESSION,'mail','session_data',$callback=null,$callback_params=array(),$expiration=60*60*1);
486
+		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
487 487
 		if (!empty(self::$activeFolderCache[$this->profileID])) $this->sessionData['mailbox'] = self::$activeFolderCache[$this->profileID];
488 488
 	}
489 489
 
@@ -493,10 +493,10 @@  discard block
 block discarded – undo
493 493
 	function saveSessionData()
494 494
 	{
495 495
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($this->sessionData)));
496
-		if (!empty($this->sessionData['mailbox'])) self::$activeFolderCache[$this->profileID]=$this->sessionData['mailbox'];
496
+		if (!empty($this->sessionData['mailbox'])) self::$activeFolderCache[$this->profileID] = $this->sessionData['mailbox'];
497 497
 		if (isset(self::$activeFolderCache) && is_array(self::$activeFolderCache))
498 498
 		{
499
-			Cache::setCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),self::$activeFolderCache, 60*60*10);
499
+			Cache::setCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), self::$activeFolderCache, 60 * 60 * 10);
500 500
 		}
501 501
 		// no need to block session any longer
502 502
 		$GLOBALS['egw']->session->commit_session();
@@ -514,40 +514,40 @@  discard block
 block discarded – undo
514 514
 	 * @param int $_profileID = null default profile of user as returned by getUserDefaultProfileID
515 515
 	 * @return void
516 516
 	 */
517
-	static function unsetCachedObjects($_profileID=null)
517
+	static function unsetCachedObjects($_profileID = null)
518 518
 	{
519 519
 		if (is_null($_profileID)) $_profileID = Mail\Account::get_default_acc_id();
520 520
 		if (is_array($_profileID) && $_profileID['account_id']) $account_id = $_profileID['account_id'];
521 521
 		//error_log(__METHOD__.__LINE__.' called with ProfileID:'.array2string($_profileID).' from '.function_backtrace());
522
-		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID,'tracker_')===false)))
522
+		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID, 'tracker_') === false)))
523 523
 		{
524 524
 			self::resetConnectionErrorCache($_profileID);
525
-			$rawHeadersCache = Cache::getCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
525
+			$rawHeadersCache = Cache::getCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
526 526
 			if (isset($rawHeadersCache[$_profileID]))
527 527
 			{
528 528
 				unset($rawHeadersCache[$_profileID]);
529
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$rawHeadersCache, $expiration=60*60*1);
529
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $rawHeadersCache, $expiration = 60 * 60 * 1);
530 530
 			}
531
-			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*5);
531
+			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 5);
532 532
 			if (isset($HierarchyDelimiterCache[$_profileID]))
533 533
 			{
534 534
 				unset($HierarchyDelimiterCache[$_profileID]);
535
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$HierarchyDelimiterCache, $expiration=60*60*24*5);
535
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $HierarchyDelimiterCache, $expiration = 60 * 60 * 24 * 5);
536 536
 			}
537 537
 			//reset folderObject cache, to trigger reload
538 538
 			self::resetFolderObjectCache($_profileID);
539 539
 			//reset counter of deleted messages per folder
540
-			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
540
+			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
541 541
 			if (isset($eMailListContainsDeletedMessages[$_profileID]))
542 542
 			{
543 543
 				unset($eMailListContainsDeletedMessages[$_profileID]);
544
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$eMailListContainsDeletedMessages, $expiration=60*60*1);
544
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $eMailListContainsDeletedMessages, $expiration = 60 * 60 * 1);
545 545
 			}
546
-			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*1);
546
+			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 1);
547 547
 			if (isset($vacationCached[$_profileID]))
548 548
 			{
549 549
 				unset($vacationCached[$_profileID]);
550
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),$vacationCached, $expiration=60*60*24*1);
550
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $vacationCached, $expiration = 60 * 60 * 24 * 1);
551 551
 			}
552 552
 
553 553
 			if (isset(self::$instances[$_profileID])) unset(self::$instances[$_profileID]);
@@ -555,17 +555,17 @@  discard block
 block discarded – undo
555 555
 		if (is_array($_profileID) && $_profileID['location'] == 'clear_cache')
556 556
 		{
557 557
 			// called via hook
558
-			foreach($GLOBALS['egw']->accounts->search(array('type' => 'accounts','order' => 'account_lid')) as $account)
558
+			foreach ($GLOBALS['egw']->accounts->search(array('type' => 'accounts', 'order' => 'account_lid')) as $account)
559 559
 			{
560 560
 				//error_log(__METHOD__.__LINE__.array2string($account));
561 561
 				$account_id = $account['account_id'];
562 562
 				$_profileID = null;
563
-				self::resetConnectionErrorCache($_profileID,$account_id);
564
-				self::resetFolderObjectCache($_profileID,$account_id);
565
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),array(), 60*60*1);
566
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),array(), 60*60*24*5);
567
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),array(), 60*60*1);
568
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),array(), 60*60*24*1);
563
+				self::resetConnectionErrorCache($_profileID, $account_id);
564
+				self::resetFolderObjectCache($_profileID, $account_id);
565
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), array(), 60 * 60 * 1);
566
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), array(), 60 * 60 * 24 * 5);
567
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), array(), 60 * 60 * 1);
568
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), array(), 60 * 60 * 24 * 1);
569 569
 			}
570 570
 		}
571 571
 	}
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 	 * @param int $_ImapServerId the profileID to look for
577 577
 	 * @param int $account_id the egw account to look for
578 578
 	 */
579
-	static function resetConnectionErrorCache($_ImapServerId=null,$account_id=null)
579
+	static function resetConnectionErrorCache($_ImapServerId = null, $account_id = null)
580 580
 	{
581 581
 		//error_log(__METHOD__.' ('.__LINE__.') '.' for Profile:'.array2string($_ImapServerId) .' for user:'.trim($account_id));
582 582
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
@@ -594,19 +594,19 @@  discard block
 block discarded – undo
594 594
 		}
595 595
 		else
596 596
 		{
597
-			$isConError = Cache::getCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id));
597
+			$isConError = Cache::getCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id));
598 598
 			if (isset($isConError[$_ImapServerId]))
599 599
 			{
600 600
 				unset($isConError[$_ImapServerId]);
601 601
 			}
602
-			$waitOnFailure = Cache::getCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),null,array(),60*60*2);
602
+			$waitOnFailure = Cache::getCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), null, array(), 60 * 60 * 2);
603 603
 			if (isset($waitOnFailure[$_ImapServerId]))
604 604
 			{
605 605
 				unset($waitOnFailure[$_ImapServerId]);
606 606
 			}
607 607
 		}
608
-		Cache::setCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id),$isConError,60*15);
609
-		Cache::setCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),$waitOnFailure,60*60*2);
608
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id), $isConError, 60 * 15);
609
+		Cache::setCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), $waitOnFailure, 60 * 60 * 2);
610 610
 	}
611 611
 
612 612
 	/**
@@ -615,13 +615,13 @@  discard block
 block discarded – undo
615 615
 	 * @param int $_ImapServerId the profileID to look for
616 616
 	 * @param int $account_id the egw account to look for
617 617
 	 */
618
-	static function resetFolderObjectCache($_ImapServerId=null,$account_id=null)
618
+	static function resetFolderObjectCache($_ImapServerId = null, $account_id = null)
619 619
 	{
620 620
 		//error_log(__METHOD__.' ('.__LINE__.') '.' called for Profile:'.array2string($_ImapServerId).'->'.function_backtrace());
621 621
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
622 622
 		// on [location] => verify_settings we coud either use [prefs] => Array([ActiveProfileID] => 9, .. as $_ImapServerId
623 623
 		// or treat it as not given. we try that path
624
-		if (is_null($_ImapServerId)||is_array($_ImapServerId))
624
+		if (is_null($_ImapServerId) || is_array($_ImapServerId))
625 625
 		{
626 626
 			$folders2return = array();
627 627
 			$folderInfo = array();
@@ -630,12 +630,12 @@  discard block
 block discarded – undo
630 630
 		}
631 631
 		else
632 632
 		{
633
-			$folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),null,array(),60*60*1);
633
+			$folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), null, array(), 60 * 60 * 1);
634 634
 			if (!empty($folders2return) && isset($folders2return[$_ImapServerId]))
635 635
 			{
636 636
 				unset($folders2return[$_ImapServerId]);
637 637
 			}
638
-			$folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),null,array(),60*60*5);
638
+			$folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), null, array(), 60 * 60 * 5);
639 639
 			if (!empty($folderInfo) && isset($folderInfo[$_ImapServerId]))
640 640
 			{
641 641
 				unset($folderInfo[$_ImapServerId]);
@@ -647,23 +647,23 @@  discard block
 block discarded – undo
647 647
 				unset($lastFolderUsedForMove[$_ImapServerId]);
648 648
 			}
649 649
 			*/
650
-			$folderBasicInfo = Cache::getCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),null,array(),60*60*1);
650
+			$folderBasicInfo = Cache::getCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), null, array(), 60 * 60 * 1);
651 651
 			if (!empty($folderBasicInfo) && isset($folderBasicInfo[$_ImapServerId]))
652 652
 			{
653 653
 				unset($folderBasicInfo[$_ImapServerId]);
654 654
 			}
655
-			$_specialUseFolders = Cache::getCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),null,array(),60*60*12);
655
+			$_specialUseFolders = Cache::getCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), null, array(), 60 * 60 * 12);
656 656
 			if (!empty($_specialUseFolders) && isset($_specialUseFolders[$_ImapServerId]))
657 657
 			{
658 658
 				unset($_specialUseFolders[$_ImapServerId]);
659
-				self::$specialUseFolders=null;
659
+				self::$specialUseFolders = null;
660 660
 			}
661 661
 		}
662
-		Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),$folders2return, 60*60*1);
663
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),$folderInfo,60*60*5);
662
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), $folders2return, 60 * 60 * 1);
663
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), $folderInfo, 60 * 60 * 5);
664 664
 		//Cache::setCache(Cache::INSTANCE,'email','lastFolderUsedForMove'.trim($account_id),$lastFolderUsedForMove,$expiration=60*60*1);
665
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),$folderBasicInfo,60*60*1);
666
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),$_specialUseFolders,60*60*12);
665
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), $folderBasicInfo, 60 * 60 * 1);
666
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), $_specialUseFolders, 60 * 60 * 12);
667 667
 	}
668 668
 
669 669
 	/**
@@ -684,15 +684,15 @@  discard block
 block discarded – undo
684 684
 	 * @param string $_profileID the ID of the mailaccount to check for identities, if null current mail-account is used
685 685
 	 * @return array - array(email=>realname)
686 686
 	 */
687
-	function getUserEMailAddresses($_profileID=null)
687
+	function getUserEMailAddresses($_profileID = null)
688 688
 	{
689
-		$acc = Mail\Account::read((!empty($_profileID)?$_profileID:$this->profileID));
689
+		$acc = Mail\Account::read((!empty($_profileID) ? $_profileID : $this->profileID));
690 690
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($acc));
691 691
 		$identities = Mail\Account::identities($acc);
692 692
 
693 693
 		$userEMailAdresses = array($acc['ident_email']=>$acc['ident_realname']);
694 694
 
695
-		foreach($identities as $ik => $ident) {
695
+		foreach ($identities as $ik => $ident) {
696 696
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
697 697
 			$identity = Mail\Account::read_identity($ik);
698 698
 			if (!empty($identity['ident_email']) && !isset($userEMailAdresses[$identity['ident_email']])) $userEMailAdresses[$identity['ident_email']] = $identity['ident_realname'];
@@ -707,19 +707,19 @@  discard block
 block discarded – undo
707 707
 	 * @param boolean $resolve_placeholders wether or not resolve possible placeholders in identities
708 708
 	 * @return array - array(email=>realname)
709 709
 	 */
710
-	static function getAllIdentities($_accountToSearch=null,$resolve_placeholders=false)
710
+	static function getAllIdentities($_accountToSearch = null, $resolve_placeholders = false)
711 711
 	{
712 712
 		$userEMailAdresses = array();
713
-		foreach(Mail\Account::search($only_current_user=($_accountToSearch?$_accountToSearch:true), $just_name=true) as $acc_id => $identity_name)
713
+		foreach (Mail\Account::search($only_current_user = ($_accountToSearch ? $_accountToSearch : true), $just_name = true) as $acc_id => $identity_name)
714 714
 		{
715
-			$acc = Mail\Account::read($acc_id,($_accountToSearch?$_accountToSearch:null));
716
-			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']);
715
+			$acc = Mail\Account::read($acc_id, ($_accountToSearch ? $_accountToSearch : null));
716
+			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']);
717 717
 
718
-			foreach(Mail\Account::identities($acc) as $ik => $ident) {
718
+			foreach (Mail\Account::identities($acc) as $ik => $ident) {
719 719
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
720
-				$identity = Mail\Account::read_identity($ik,$resolve_placeholders);
720
+				$identity = Mail\Account::read_identity($ik, $resolve_placeholders);
721 721
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
722
-				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']);
722
+				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']);
723 723
 			}
724 724
 		}
725 725
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($userEMailAdresses));
@@ -739,9 +739,9 @@  discard block
 block discarded – undo
739 739
 			$account = Mail\Account::read($account);
740 740
 		}
741 741
 		$userEMailAdresses = array();
742
-		foreach(Mail\Account::identities($account, true, 'params') as $ik => $ident) {
742
+		foreach (Mail\Account::identities($account, true, 'params') as $ik => $ident) {
743 743
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
744
-			$identity = Mail\Account::read_identity($ik,true,null,$account);
744
+			$identity = Mail\Account::read_identity($ik, true, null, $account);
745 745
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
746 746
 			// standardIdentity has ident_id==acc_id (as it is done within account->identities)
747 747
 			if (empty($identity['ident_id'])) $identity['ident_id'] = $identity['acc_id'];
@@ -768,9 +768,9 @@  discard block
 block discarded – undo
768 768
 	function getDefaultIdentity()
769 769
 	{
770 770
 		// retrieve the signature accociated with the identity
771
-		$id = $this->getIdentitiesWithAccounts($_accountData=array());
772
-		foreach(Mail\Account::identities($_accountData[$this->profileID] ?
773
-			$this->profileID : $_accountData[$id],false,'ident_id') as $accountData)
771
+		$id = $this->getIdentitiesWithAccounts($_accountData = array());
772
+		foreach (Mail\Account::identities($_accountData[$this->profileID] ?
773
+			$this->profileID : $_accountData[$id], false, 'ident_id') as $accountData)
774 774
 		{
775 775
 			return $accountData;
776 776
 		}
@@ -786,13 +786,13 @@  discard block
 block discarded – undo
786 786
 	{
787 787
 		// account select box
788 788
 		$selectedID = $this->profileID;
789
-		$allAccountData = Mail\Account::search($only_current_user=true, false, null);
789
+		$allAccountData = Mail\Account::search($only_current_user = true, false, null);
790 790
 		if ($allAccountData) {
791
-			$rememberFirst=$selectedFound=null;
791
+			$rememberFirst = $selectedFound = null;
792 792
 			foreach ($allAccountData as $tmpkey => $icServers)
793 793
 			{
794 794
 				if (is_null($rememberFirst)) $rememberFirst = $tmpkey;
795
-				if ($tmpkey == $selectedID) $selectedFound=true;
795
+				if ($tmpkey == $selectedID) $selectedFound = true;
796 796
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($icServers->acc_imap_host));
797 797
 				$host = $icServers->acc_imap_host;
798 798
 				if (empty($host)) continue;
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($identities[$icServers->acc_id]));
801 801
 			}
802 802
 		}
803
-		return ($selectedFound?$selectedID:$rememberFirst);
803
+		return ($selectedFound ? $selectedID : $rememberFirst);
804 804
 	}
805 805
 
806 806
 	/**
@@ -810,7 +810,7 @@  discard block
 block discarded – undo
810 810
 	 * @var boolean $fullString full or false=NamePart only is returned
811 811
 	 * @return string - constructed of identity object data as defined in mailConfig
812 812
 	 */
813
-	static function generateIdentityString($identity, $fullString=true)
813
+	static function generateIdentityString($identity, $fullString = true)
814 814
 	{
815 815
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($identity));
816 816
 		//if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
@@ -821,16 +821,16 @@  discard block
 block discarded – undo
821 821
 		{
822 822
 			case 'email';
823 823
 				//$retData = str_replace('@',' ',$identity->emailAddress).($fullString===true?' <'.$identity->emailAddress.'>':'');
824
-				$retData = $identity['ident_email'].($fullString===true?' <'.$identity['ident_email'].'>':'');
824
+				$retData = $identity['ident_email'].($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
825 825
 				break;
826 826
 			case 'nameNemail';
827
-				$retData = (!empty($identity['ident_realname'])?$identity['ident_realname']:substr_replace($identity['ident_email'],'',strpos($identity['ident_email'],'@'))).($fullString===true?' <'.$identity['ident_email'].'>':'');
827
+				$retData = (!empty($identity['ident_realname']) ? $identity['ident_realname'] : substr_replace($identity['ident_email'], '', strpos($identity['ident_email'], '@'))).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
828 828
 				break;
829 829
 			case 'orgNemail';
830
-				$retData = (!empty($identity['ident_org'])?$identity['ident_org']:substr_replace($identity['ident_email'],'',0,strpos($identity['ident_email'],'@')+1)).($fullString===true?' <'.$identity['ident_email'].'>':'');
830
+				$retData = (!empty($identity['ident_org']) ? $identity['ident_org'] : substr_replace($identity['ident_email'], '', 0, strpos($identity['ident_email'], '@') + 1)).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
831 831
 				break;
832 832
 			default:
833
-				$retData = $identity['ident_realname'].(!empty($identity['ident_org'])?' '.$identity['ident_org']:'').($fullString===true?' <'.$identity['ident_email'].'>':'');
833
+				$retData = $identity['ident_realname'].(!empty($identity['ident_org']) ? ' '.$identity['ident_org'] : '').($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
834 834
 		}
835 835
 		return $retData;
836 836
 	}
@@ -855,7 +855,7 @@  discard block
 block discarded – undo
855 855
 	 */
856 856
 	function reopen($_foldername)
857 857
 	{
858
-		if (self::$debugTimes) $starttime = microtime (true);
858
+		if (self::$debugTimes) $starttime = microtime(true);
859 859
 
860 860
 		//error_log(__METHOD__.' ('.__LINE__.') '."('$_foldername') ".function_backtrace());
861 861
 		// TODO: trying to reduce traffic to the IMAP Server here, introduces problems with fetching the bodies of
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 			}
871 871
 			$folderOpened = $_foldername;
872 872
 		//}
873
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'Folder:'.$_foldername,__METHOD__.' ('.__LINE__.') ');
873
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'Folder:'.$_foldername, __METHOD__.' ('.__LINE__.') ');
874 874
 	}
875 875
 
876 876
 
@@ -881,15 +881,15 @@  discard block
 block discarded – undo
881 881
 	 * @throws Horde_Imap_Client_Exception on connection error or authentication failure
882 882
 	 * @throws InvalidArgumentException on missing credentials
883 883
 	 */
884
-	function openConnection($_icServerID=0)
884
+	function openConnection($_icServerID = 0)
885 885
 	{
886 886
 		//error_log( "-------------------------->open connection ".function_backtrace());
887 887
 		//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.array2string($this->icServer));
888
-		if (self::$debugTimes) $starttime = microtime (true);
889
-		$mailbox=null;
888
+		if (self::$debugTimes) $starttime = microtime(true);
889
+		$mailbox = null;
890 890
 		try
891 891
 		{
892
-			if(isset($this->sessionData['mailbox'])&&$this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
892
+			if (isset($this->sessionData['mailbox']) && $this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
893 893
 			if (empty($mailbox)) $mailbox = $this->icServer->getCurrentMailbox();
894 894
 /*
895 895
 			if (isset(Mail\Imap::$supports_keywords[$_icServerID]))
@@ -916,7 +916,7 @@  discard block
 block discarded – undo
916 916
 			error_log(__METHOD__.' ('.__LINE__.') '."->open connection for Server with profileID:".$_icServerID." trying to examine ($mailbox) failed!".$e->getMessage());
917 917
 			throw new Exception(__METHOD__." failed to ".__METHOD__." on Profile to $_icServerID while trying to examine $mailbox:".$e->getMessage());
918 918
 		}
919
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'ProfileID:'.$_icServerID,__METHOD__.' ('.__LINE__.') ');
919
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'ProfileID:'.$_icServerID, __METHOD__.' ('.__LINE__.') ');
920 920
 	}
921 921
 
922 922
 	/**
@@ -937,7 +937,7 @@  discard block
 block discarded – undo
937 937
 		try
938 938
 		{
939 939
 			$this->icServer->getCurrentMailbox();
940
-			if(!$this->icServer->hasCapability('QUOTA')) {
940
+			if (!$this->icServer->hasCapability('QUOTA')) {
941 941
 				$quota = false;
942 942
 				return false;
943 943
 			}
@@ -947,15 +947,15 @@  discard block
 block discarded – undo
947 947
 		{
948 948
 			//error_log(__METHOD__.array2string($e));
949 949
 			//error_log(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
950
-			if ($e->getCode()==102)
950
+			if ($e->getCode() == 102)
951 951
 			{
952
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
953
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
954
-				throw new Exception(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
952
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
953
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
954
+				throw new Exception(__METHOD__." failed to fetch quota on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : ''));
955 955
 			}
956 956
 		}
957 957
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($quota));
958
-		if(is_array($quota)) {
958
+		if (is_array($quota)) {
959 959
 			$quota = array(
960 960
 				'usage'	=> $quota['USED'],
961 961
 				'limit'	=> $quota['QMAX'],
@@ -973,10 +973,10 @@  discard block
 block discarded – undo
973 973
 	 *
974 974
 	 * @return int - timeout (either set or default 20/10)
975 975
 	 */
976
-	static function getTimeOut($_use='IMAP')
976
+	static function getTimeOut($_use = 'IMAP')
977 977
 	{
978 978
 		$timeout = $GLOBALS['egw_info']['user']['preferences']['mail']['connectionTimeout'];
979
-		if (empty($timeout)) $timeout = ($_use=='SIEVE'?10:20); // this is the default value
979
+		if (empty($timeout)) $timeout = ($_use == 'SIEVE' ? 10 : 20); // this is the default value
980 980
 		return $timeout;
981 981
 	}
982 982
 
@@ -997,18 +997,18 @@  discard block
 block discarded – undo
997 997
 		if (is_null($nameSpace)) $nameSpace = $this->icServer->getNameSpaceArray();
998 998
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($nameSpace));
999 999
 		if (is_array($nameSpace)) {
1000
-			foreach($nameSpace as $type => $singleNameSpaceArray)
1000
+			foreach ($nameSpace as $type => $singleNameSpaceArray)
1001 1001
 			{
1002 1002
 				foreach ($singleNameSpaceArray as $singleNameSpace)
1003 1003
 				{
1004 1004
 					$_foldersNameSpace = array();
1005
-					if($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail')||$this->folderExists('INBOX')))
1005
+					if ($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail') || $this->folderExists('INBOX')))
1006 1006
 					{
1007 1007
 						$_foldersNameSpace['prefix_present'] = 'forced';
1008 1008
 						// uw-imap server with mailbox prefix or dovecot maybe
1009
-						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail')?'Mail':(!empty($singleNameSpace['name'])?$singleNameSpace['name']:''));
1009
+						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail') ? 'Mail' : (!empty($singleNameSpace['name']) ? $singleNameSpace['name'] : ''));
1010 1010
 					}
1011
-					elseif($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
1011
+					elseif ($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
1012 1012
 					{
1013 1013
 						$_foldersNameSpace['prefix_present'] = 'forced';
1014 1014
 						// uw-imap server with mailbox prefix or dovecot maybe
@@ -1017,9 +1017,9 @@  discard block
 block discarded – undo
1017 1017
 						$_foldersNameSpace['prefix_present'] = !empty($singleNameSpace['name']);
1018 1018
 						$_foldersNameSpace['prefix'] = $singleNameSpace['name'];
1019 1019
 					}
1020
-					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter']?$singleNameSpace['delimiter']:$delimiter);
1020
+					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter'] ? $singleNameSpace['delimiter'] : $delimiter);
1021 1021
 					$_foldersNameSpace['type'] = $type;
1022
-					$foldersNameSpace[] =$_foldersNameSpace;
1022
+					$foldersNameSpace[] = $_foldersNameSpace;
1023 1023
 				}
1024 1024
 				//echo "############## $type->".print_r($foldersNameSpace[$type],true)." ###################<br>";
1025 1025
 			}
@@ -1037,10 +1037,10 @@  discard block
 block discarded – undo
1037 1037
 	 */
1038 1038
 	function getFolderPrefixFromNamespace($nameSpace, $folderName)
1039 1039
 	{
1040
-		foreach($nameSpace as &$singleNameSpace)
1040
+		foreach ($nameSpace as &$singleNameSpace)
1041 1041
 		{
1042 1042
 			//if (substr($singleNameSpace['prefix'],0,strlen($folderName))==$folderName) return $singleNameSpace['prefix'];
1043
-			if (substr($folderName,0,strlen($singleNameSpace['prefix']))==$singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1043
+			if (substr($folderName, 0, strlen($singleNameSpace['prefix'])) == $singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1044 1044
 		}
1045 1045
 		return "";
1046 1046
 	}
@@ -1051,12 +1051,12 @@  discard block
 block discarded – undo
1051 1051
 	 * @var boolean $_useCache
1052 1052
 	 * @return string the hierarchyDelimiter
1053 1053
 	 */
1054
-	function getHierarchyDelimiter($_useCache=true)
1054
+	function getHierarchyDelimiter($_useCache = true)
1055 1055
 	{
1056 1056
 		static $HierarchyDelimiter = null;
1057
-		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1058
-		if ($_useCache===false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1059
-		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId])&&!empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1057
+		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 24 * 5);
1058
+		if ($_useCache === false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1059
+		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId]) && !empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1060 1060
 		{
1061 1061
 			return $HierarchyDelimiter[$this->icServer->ImapServerId];
1062 1062
 		}
@@ -1066,17 +1066,17 @@  discard block
 block discarded – undo
1066 1066
 			$this->icServer->getCurrentMailbox();
1067 1067
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = $this->icServer->getDelimiter();
1068 1068
 		}
1069
-		catch(\Exception $e)
1069
+		catch (\Exception $e)
1070 1070
 		{
1071
-			if ($e->getCode()==102)
1071
+			if ($e->getCode() == 102)
1072 1072
 			{
1073
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1074
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1073
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1074
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1075 1075
 			}
1076 1076
 			unset($e);
1077 1077
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = '/';
1078 1078
 		}
1079
-		Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),$HierarchyDelimiter, 60*60*24*5);
1079
+		Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), $HierarchyDelimiter, 60 * 60 * 24 * 5);
1080 1080
 		return $HierarchyDelimiter[$this->icServer->ImapServerId];
1081 1081
 	}
1082 1082
 
@@ -1089,7 +1089,7 @@  discard block
 block discarded – undo
1089 1089
 	{
1090 1090
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$this->icServer->ImapServerId.' Connected:'.$this->icServer->_connected);
1091 1091
 		static $_specialUseFolders = null;
1092
-		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);
1092
+		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);
1093 1093
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_trash));
1094 1094
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_sent));
1095 1095
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_draft));
@@ -1097,20 +1097,20 @@  discard block
 block discarded – undo
1097 1097
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1098 1098
 		if (isset($_specialUseFolders[$this->icServer->ImapServerId]) && !empty($_specialUseFolders[$this->icServer->ImapServerId]))
1099 1099
 			return $_specialUseFolders[$this->icServer->ImapServerId];
1100
-		$_specialUseFolders[$this->icServer->ImapServerId]=array();
1100
+		$_specialUseFolders[$this->icServer->ImapServerId] = array();
1101 1101
 		//if (!empty($this->icServer->acc_folder_trash) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]))
1102
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]='Trash';
1102
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash] = 'Trash';
1103 1103
 		//if (!empty($this->icServer->acc_folder_draft) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]))
1104
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]='Drafts';
1104
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft] = 'Drafts';
1105 1105
 		//if (!empty($this->icServer->acc_folder_sent) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]))
1106
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]='Sent';
1106
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent] = 'Sent';
1107 1107
 		//if (!empty($this->icServer->acc_folder_template) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]))
1108
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]='Templates';
1109
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk]='Junk';
1110
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive]='Archive';
1108
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template] = 'Templates';
1109
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk] = 'Junk';
1110
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive] = 'Archive';
1111 1111
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_specialUseFolders));//.'<->'.array2string($this->icServer));
1112 1112
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1113
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$_specialUseFolders, 60*60*24*5);
1113
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $_specialUseFolders, 60 * 60 * 24 * 5);
1114 1114
 		return $_specialUseFolders[$this->icServer->ImapServerId];
1115 1115
 	}
1116 1116
 
@@ -1124,8 +1124,8 @@  discard block
 block discarded – undo
1124 1124
 	function folderIsSelectable($folderToSelect)
1125 1125
 	{
1126 1126
 		$retval = true;
1127
-		if($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect,false,true))) {
1128
-			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']),'noselect')!==false)
1127
+		if ($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect, false, true))) {
1128
+			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']), 'noselect') !== false)
1129 1129
 			{
1130 1130
 				$retval = false;
1131 1131
 			}
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
 	 *
1146 1146
 	 * @throws Exception
1147 1147
 	 */
1148
-	function _getStatus($folderName,$ignoreStatusCache=false)
1148
+	function _getStatus($folderName, $ignoreStatusCache = false)
1149 1149
 	{
1150 1150
 		static $folderStatus = null;
1151 1151
 		if (!$ignoreStatusCache && isset($folderStatus[$this->icServer->ImapServerId][$folderName]))
@@ -1155,11 +1155,11 @@  discard block
 block discarded – undo
1155 1155
 		}
1156 1156
 		try
1157 1157
 		{
1158
-			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName,$ignoreStatusCache);
1158
+			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName, $ignoreStatusCache);
1159 1159
 		}
1160 1160
 		catch (\Exception $e)
1161 1161
 		{
1162
-			throw new Exception(__METHOD__.' ('.__LINE__.') '." failed for $folderName with error:".$e->getMessage().($e->details?', '.$e->details:''));
1162
+			throw new Exception(__METHOD__.' ('.__LINE__.') '." failed for $folderName with error:".$e->getMessage().($e->details ? ', '.$e->details : ''));
1163 1163
 		}
1164 1164
 		return $folderStatus[$this->icServer->ImapServerId][$folderName];
1165 1165
 	}
@@ -1175,10 +1175,10 @@  discard block
 block discarded – undo
1175 1175
 	 * @param fetchSubscribedInfo bool fetch Subscribed Info on folder
1176 1176
 	 * @return array
1177 1177
 	 */
1178
-	function getFolderStatus($_folderName,$ignoreStatusCache=false,$basicInfoOnly=false,$fetchSubscribedInfo=true)
1178
+	function getFolderStatus($_folderName, $ignoreStatusCache = false, $basicInfoOnly = false, $fetchSubscribedInfo = true)
1179 1179
 	{
1180 1180
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." called with:$_folderName,$ignoreStatusCache,$basicInfoOnly");
1181
-		if (!is_string($_folderName) || empty($_folderName)||(isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID])))
1181
+		if (!is_string($_folderName) || empty($_folderName) || (isset(self::$profileDefunct[$this->profileID]) && strlen(self::$profileDefunct[$this->profileID])))
1182 1182
 		{
1183 1183
 			// something is wrong. Do not proceed. either no folder or profile is marked as defunct for this request
1184 1184
 			return false;
@@ -1189,7 +1189,7 @@  discard block
 block discarded – undo
1189 1189
 		{
1190 1190
 			$folderInfoCache = $folderBasicInfo[$this->profileID];
1191 1191
 		}
1192
-		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache==false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1192
+		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache == false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1193 1193
 		$retValue = array();
1194 1194
 		$retValue['subscribed'] = false;
1195 1195
 /*
@@ -1210,41 +1210,41 @@  discard block
 block discarded – undo
1210 1210
 			{
1211 1211
 				//error_log(__METHOD__.array2string($e));
1212 1212
 				//error_log(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
1213
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1214
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1215
-				throw new Exception(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
1213
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1214
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1215
+				throw new Exception(__METHOD__." failed to fetch Mailbox $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : ''));
1216 1216
 			}
1217 1217
 			//error_log(__METHOD__.' ('.__LINE__.') '.$_folderName.' '.array2string($ret));
1218 1218
 			if (is_array($ret))
1219 1219
 			{
1220 1220
 				$retkeys = array_keys($ret);
1221
-				if ($retkeys[0]==$_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1221
+				if ($retkeys[0] == $_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1222 1222
 			}
1223 1223
 			else
1224 1224
 			{
1225
-				$folderInfoCache[$_folderName]=false;
1225
+				$folderInfoCache[$_folderName] = false;
1226 1226
 			}
1227 1227
 		}
1228 1228
 		$folderInfo = $folderInfoCache[$_folderName];
1229 1229
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($folderInfo).'->'.function_backtrace());
1230
-		if($ignoreStatusCache||!$folderInfo|| !is_array($folderInfo)) {
1230
+		if ($ignoreStatusCache || !$folderInfo || !is_array($folderInfo)) {
1231 1231
 			try
1232 1232
 			{
1233
-				$folderInfo = $this->_getStatus($_folderName,$ignoreStatusCache);
1233
+				$folderInfo = $this->_getStatus($_folderName, $ignoreStatusCache);
1234 1234
 			}
1235 1235
 			catch (\Exception $e)
1236 1236
 			{
1237 1237
 				//error_log(__METHOD__.array2string($e));
1238
-				error_log(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:'')/*.function_backtrace()*/);
1239
-				self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
1240
-				Cache::setCache(Cache::INSTANCE,'email','profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']),self::$profileDefunct, $expiration=5*1);
1238
+				error_log(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details ? ', '.$e->details : '')/*.function_backtrace()*/);
1239
+				self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
1240
+				Cache::setCache(Cache::INSTANCE, 'email', 'profileDefunct'.trim($GLOBALS['egw_info']['user']['account_id']), self::$profileDefunct, $expiration = 5 * 1);
1241 1241
 				//throw new Exception(__METHOD__." failed to fetch status for $_folderName on ".$this->profileID.' Reason:'.$e->getMessage().($e->details?', '.$e->details:''));
1242
-				$folderInfo=null;
1242
+				$folderInfo = null;
1243 1243
 			}
1244 1244
 			if (!is_array($folderInfo))
1245 1245
 			{
1246 1246
 				// no folder info, but there is a status returned for the folder: something is wrong, try to cope with it
1247
-				$folderInfo = is_array($folderInfo)?$folderInfo:array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1247
+				$folderInfo = is_array($folderInfo) ? $folderInfo : array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1248 1248
 					'ATTRIBUTES' => '');
1249 1249
 				if (!isset($folderInfo['HIERACHY_DELIMITER']) || empty($folderInfo['HIERACHY_DELIMITER']) || (isset($folderInfo['delimiter']) && empty($folderInfo['delimiter'])))
1250 1250
 				{
@@ -1256,24 +1256,24 @@  discard block
 block discarded – undo
1256 1256
 		#if(!is_array($folderInfo)) {
1257 1257
 		#	return false;
1258 1258
 		#}
1259
-		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER']?$folderInfo['HIERACHY_DELIMITER']:$folderInfo['delimiter']);
1260
-		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES']?$folderInfo['ATTRIBUTES']:$folderInfo['attributes']);
1261
-		$shortNameParts			= explode($retValue['delimiter'], $_folderName);
1259
+		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER'] ? $folderInfo['HIERACHY_DELIMITER'] : $folderInfo['delimiter']);
1260
+		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES'] ? $folderInfo['ATTRIBUTES'] : $folderInfo['attributes']);
1261
+		$shortNameParts = explode($retValue['delimiter'], $_folderName);
1262 1262
 		$retValue['shortName']		= array_pop($shortNameParts);
1263 1263
 		$retValue['displayName']	= $_folderName;
1264
-		$retValue['shortDisplayName']	= $retValue['shortName'];
1265
-		if(strtoupper($retValue['shortName']) == 'INBOX') {
1266
-			$retValue['displayName']	= lang('INBOX');
1267
-			$retValue['shortDisplayName']	= lang('INBOX');
1264
+		$retValue['shortDisplayName'] = $retValue['shortName'];
1265
+		if (strtoupper($retValue['shortName']) == 'INBOX') {
1266
+			$retValue['displayName'] = lang('INBOX');
1267
+			$retValue['shortDisplayName'] = lang('INBOX');
1268 1268
 		}
1269 1269
 		// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
1270
-		elseif (in_array($retValue['shortName'],self::$autoFolders))
1270
+		elseif (in_array($retValue['shortName'], self::$autoFolders))
1271 1271
 		{
1272 1272
 			$retValue['displayName'] = $retValue['shortDisplayName'] = lang($retValue['shortName']);
1273 1273
 		}
1274
-		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName]=$retValue;
1274
+		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName] = $retValue;
1275 1275
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.$_folderName.array2string($retValue['attributes']));
1276
-		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']),'noselect')!==false))
1276
+		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']), 'noselect') !== false))
1277 1277
 		{
1278 1278
 			return $retValue;
1279 1279
 		}
@@ -1286,12 +1286,12 @@  discard block
 block discarded – undo
1286 1286
 		if (is_null($nameSpace) || empty($nameSpace[$this->profileID])) $nameSpace[$this->profileID] = $this->_getNameSpaces();
1287 1287
 		if (!empty($nameSpace[$this->profileID]))
1288 1288
 		{
1289
-			$nsNoPersonal=array();
1290
-			foreach($nameSpace[$this->profileID] as &$ns)
1289
+			$nsNoPersonal = array();
1290
+			foreach ($nameSpace[$this->profileID] as &$ns)
1291 1291
 			{
1292
-				if ($ns['type']!='personal') $nsNoPersonal[]=$ns;
1292
+				if ($ns['type'] != 'personal') $nsNoPersonal[] = $ns;
1293 1293
 			}
1294
-			$nameSpace[$this->profileID]=$nsNoPersonal;
1294
+			$nameSpace[$this->profileID] = $nsNoPersonal;
1295 1295
 		}
1296 1296
 		if (is_null($prefix) || empty($prefix[$this->profileID]) || empty($prefix[$this->profileID][$_folderName])) $prefix[$this->profileID][$_folderName] = $this->getFolderPrefixFromNamespace($nameSpace[$this->profileID], $_folderName);
1297 1297
 
@@ -1300,34 +1300,34 @@  discard block
 block discarded – undo
1300 1300
 			$subscribedFolders[$this->profileID] = $this->icServer->listSubscribedMailboxes();
1301 1301
 		}
1302 1302
 
1303
-		if($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName,$subscribedFolders[$this->profileID])) {
1303
+		if ($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName, $subscribedFolders[$this->profileID])) {
1304 1304
 			$retValue['subscribed'] = true;
1305 1305
 		}
1306 1306
 
1307 1307
 		try
1308 1308
 		{
1309 1309
 			//$folderStatus = $this->_getStatus($_folderName,$ignoreStatusCache);
1310
-			$folderStatus = $this->getMailBoxCounters($_folderName,false);
1311
-			$retValue['messages']		= $folderStatus['MESSAGES'];
1310
+			$folderStatus = $this->getMailBoxCounters($_folderName, false);
1311
+			$retValue['messages'] = $folderStatus['MESSAGES'];
1312 1312
 			$retValue['recent']		= $folderStatus['RECENT'];
1313
-			$retValue['uidnext']		= $folderStatus['UIDNEXT'];
1314
-			$retValue['uidvalidity']	= $folderStatus['UIDVALIDITY'];
1313
+			$retValue['uidnext'] = $folderStatus['UIDNEXT'];
1314
+			$retValue['uidvalidity'] = $folderStatus['UIDVALIDITY'];
1315 1315
 			$retValue['unseen']		= $folderStatus['UNSEEN'];
1316 1316
 			if (//$retValue['unseen']==0 &&
1317 1317
 				(isset($this->mailPreferences['trustServersUnseenInfo']) && // some servers dont serve the UNSEEN information
1318
-				$this->mailPreferences['trustServersUnseenInfo']==false) ||
1318
+				$this->mailPreferences['trustServersUnseenInfo'] == false) ||
1319 1319
 				(isset($this->mailPreferences['trustServersUnseenInfo']) &&
1320
-				$this->mailPreferences['trustServersUnseenInfo']==2 &&
1321
-				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName,$prefix[$this->profileID][$_folderName]) !== false)
1320
+				$this->mailPreferences['trustServersUnseenInfo'] == 2 &&
1321
+				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName, $prefix[$this->profileID][$_folderName]) !== false)
1322 1322
 			)
1323 1323
 			{
1324 1324
 				//error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($prefix,true).' TS:'.$this->mailPreferences['trustServersUnseenInfo']);
1325 1325
 				// we filter for the combined status of unseen and undeleted, as this is what we show in list
1326 1326
 				try
1327 1327
 				{
1328
-					$byUid=true;
1329
-					$_reverse=1;
1330
-					$sortResult = $this->getSortedList($_folderName, $_sort=0, $_reverse, array('status'=>array('UNSEEN','UNDELETED')),$byUid,false);
1328
+					$byUid = true;
1329
+					$_reverse = 1;
1330
+					$sortResult = $this->getSortedList($_folderName, $_sort = 0, $_reverse, array('status'=>array('UNSEEN', 'UNDELETED')), $byUid, false);
1331 1331
 					$retValue['unseen'] = $sortResult['count'];
1332 1332
 				}
1333 1333
 				catch (\Exception $ee)
@@ -1338,7 +1338,7 @@  discard block
 block discarded – undo
1338 1338
 		}
1339 1339
 		catch (\Exception $e)
1340 1340
 		{
1341
-			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(),true));
1341
+			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(), true));
1342 1342
 		}
1343 1343
 
1344 1344
 		return $retValue;
@@ -1360,7 +1360,7 @@  discard block
 block discarded – undo
1360 1360
 	 * @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))
1361 1361
 	 * @return array result as array(header=>array,total=>int,first=>int,last=>int)
1362 1362
 	 */
1363
-	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly=null, $_cacheResult=true, $_fetchPreviews=false)
1363
+	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly = null, $_cacheResult = true, $_fetchPreviews = false)
1364 1364
 	{
1365 1365
 		//self::$debug=true;
1366 1366
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.function_backtrace());
@@ -1373,7 +1373,7 @@  discard block
 block discarded – undo
1373 1373
 		$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
1374 1374
 		#print "<pre>";
1375 1375
 		#$this->icServer->setDebug(true);
1376
-		$total=0;
1376
+		$total = 0;
1377 1377
 		if ($_thisUIDOnly === null)
1378 1378
 		{
1379 1379
 			if (($_startMessage || $_numberOfMessages) && !isset($_filter['range']))
@@ -1386,24 +1386,24 @@  discard block
 block discarded – undo
1386 1386
 				//$_filter['range'] ="$_startMessage:*";
1387 1387
 			}
1388 1388
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_sort, $reverse, ".array2string($_filter).", $rByUid");
1389
-			if (self::$debug||self::$debugTimes) $starttime = microtime (true);
1389
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1390 1390
 			//see this example below for a 12 week datefilter (since)
1391 1391
 			//$_filter = array('status'=>array('UNDELETED'),'type'=>"SINCE",'string'=> date("d-M-Y", $starttime-(3600*24*7*12)));
1392 1392
 			$_sortResult = $this->getSortedList($_folderName, $_sort, $reverse, $_filter, $rByUid, $_cacheResult);
1393 1393
 			$sortResult = $_sortResult['match']->ids;
1394 1394
 			//$modseq = $_sortResult['modseq'];
1395 1395
 			//error_log(__METHOD__.' ('.__LINE__.') '.'Modsequence:'.$modseq);
1396
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly),__METHOD__.' ('.__LINE__.') ');
1396
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly), __METHOD__.' ('.__LINE__.') ');
1397 1397
 
1398 1398
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1399 1399
 			#$this->icServer->setDebug(false);
1400 1400
 			#print "</pre>";
1401 1401
 			// nothing found
1402
-			if(!is_array($sortResult) || empty($sortResult)) {
1402
+			if (!is_array($sortResult) || empty($sortResult)) {
1403 1403
 				$retValue = array();
1404 1404
 				$retValue['info']['total']	= 0;
1405 1405
 				$retValue['info']['first']	= 0;
1406
-				$retValue['info']['last']	= 0;
1406
+				$retValue['info']['last'] = 0;
1407 1407
 				return $retValue;
1408 1408
 			}
1409 1409
 
@@ -1411,54 +1411,54 @@  discard block
 block discarded – undo
1411 1411
 			#_debug_array($sortResult);
1412 1412
 			#_debug_array(array_slice($sortResult, -5, -2));
1413 1413
 			//error_log("REVERSE: $reverse");
1414
-			if($reverse === true) {
1415
-				if  ($_startMessage<=$total)
1414
+			if ($reverse === true) {
1415
+				if ($_startMessage <= $total)
1416 1416
 				{
1417
-					$startMessage = $_startMessage-1;
1417
+					$startMessage = $_startMessage - 1;
1418 1418
 				}
1419 1419
 				else
1420 1420
 				{
1421 1421
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1422
-					if ($_startMessage+$_numberOfMessages>$total)
1422
+					if ($_startMessage + $_numberOfMessages > $total)
1423 1423
 					{
1424
-						$numberOfMessages = $total%$_numberOfMessages;
1424
+						$numberOfMessages = $total % $_numberOfMessages;
1425 1425
 						//$numberOfMessages = abs($_startMessage-$total-1);
1426
-						if ($numberOfMessages>0 && $numberOfMessages<=$_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1426
+						if ($numberOfMessages > 0 && $numberOfMessages <= $_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1427 1427
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1428 1428
 					}
1429
-					$startMessage=($total-$_numberOfMessages)-1;
1429
+					$startMessage = ($total - $_numberOfMessages) - 1;
1430 1430
 					//$retValue['info']['first'] = $startMessage;
1431 1431
 					//$retValue['info']['last'] = $total;
1432 1432
 
1433 1433
 				}
1434
-				if ($startMessage+$_numberOfMessages>$total)
1434
+				if ($startMessage + $_numberOfMessages > $total)
1435 1435
 				{
1436
-					$_numberOfMessages = $_numberOfMessages-($total-($startMessage+$_numberOfMessages));
1436
+					$_numberOfMessages = $_numberOfMessages - ($total - ($startMessage + $_numberOfMessages));
1437 1437
 					//$retValue['info']['first'] = $startMessage;
1438 1438
 					//$retValue['info']['last'] = $total;
1439 1439
 				}
1440
-				if($startMessage > 0) {
1441
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+$startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1442
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+$startMessage), -$startMessage);
1440
+				if ($startMessage > 0) {
1441
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + $startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1442
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + $startMessage), -$startMessage);
1443 1443
 				} else {
1444
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+($_startMessage-1))).', AllTheRest, Number of Messages:'.count($sortResult));
1445
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+($_startMessage-1)));
1444
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + ($_startMessage - 1))).', AllTheRest, Number of Messages:'.count($sortResult));
1445
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + ($_startMessage - 1)));
1446 1446
 				}
1447 1447
 				$sortResult = array_reverse($sortResult);
1448 1448
 			} else {
1449
-				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage-1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1450
-				$sortResult = array_slice($sortResult, $_startMessage-1, $_numberOfMessages);
1449
+				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage - 1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1450
+				$sortResult = array_slice($sortResult, $_startMessage - 1, $_numberOfMessages);
1451 1451
 			}
1452 1452
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1453 1453
 		}
1454 1454
 		else
1455 1455
 		{
1456
-			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly:(array)$_thisUIDOnly);
1456
+			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly : (array)$_thisUIDOnly);
1457 1457
 		}
1458 1458
 
1459 1459
 
1460 1460
 		// fetch the data for the selected messages
1461
-		if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1461
+		if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1462 1462
 		try
1463 1463
 		{
1464 1464
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -1467,22 +1467,22 @@  discard block
 block discarded – undo
1467 1467
 			$fquery = new Horde_Imap_Client_Fetch_Query();
1468 1468
 
1469 1469
 			// Pre-cache the headers we want, 'fetchHeaders' is a label into the cache
1470
-			$fquery->headers('fetchHeaders',array(
1471
-				'DISPOSITION-NOTIFICATION-TO','RETURN-RECEIPT-TO','X-CONFIRM-READING-TO',
1472
-				'DATE','SUBJECT','FROM','TO','CC','REPLY-TO',
1470
+			$fquery->headers('fetchHeaders', array(
1471
+				'DISPOSITION-NOTIFICATION-TO', 'RETURN-RECEIPT-TO', 'X-CONFIRM-READING-TO',
1472
+				'DATE', 'SUBJECT', 'FROM', 'TO', 'CC', 'REPLY-TO',
1473 1473
 				'X-PRIORITY'
1474
-			),array(
1474
+			), array(
1475 1475
 				// Cache headers, we'll look at them below
1476
-				'cache' => true,//$_cacheResult,
1476
+				'cache' => true, //$_cacheResult,
1477 1477
 				// Set peek so messages are not flagged as read
1478 1478
 				'peek' => true
1479 1479
 			));
1480 1480
 			$fquery->size();
1481 1481
 			$fquery->structure();
1482 1482
 			$fquery->flags();
1483
-			$fquery->imapDate();// needed to ensure getImapDate fetches the internaldate, not the current time
1483
+			$fquery->imapDate(); // needed to ensure getImapDate fetches the internaldate, not the current time
1484 1484
 			// if $_fetchPreviews is activated fetch part of the messages too
1485
-			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true,'length'=>((int)$_fetchPreviews<5000?5000:$_fetchPreviews),'start'=>0));
1485
+			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true, 'length'=>((int)$_fetchPreviews < 5000 ? 5000 : $_fetchPreviews), 'start'=>0));
1486 1486
 			$headersNew = $this->icServer->fetch($_folderName, $fquery, array(
1487 1487
 				'ids' => $uidsToFetch,
1488 1488
 			));
@@ -1493,9 +1493,9 @@  discard block
 block discarded – undo
1493 1493
 			$headersNew = array();
1494 1494
 			$sortResult = array();
1495 1495
 		}
1496
-		if (self::$debug||self::$debugTimes)
1496
+		if (self::$debug || self::$debugTimes)
1497 1497
 		{
1498
-			self::logRunTimes($starttime,null,'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter),__METHOD__.' ('.__LINE__.') ');
1498
+			self::logRunTimes($starttime, null, 'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter), __METHOD__.' ('.__LINE__.') ');
1499 1499
 			if (self::$debug)
1500 1500
 			{
1501 1501
 				$queryString = implode(',', $sortResult);
@@ -1505,27 +1505,27 @@  discard block
 block discarded – undo
1505 1505
 
1506 1506
 		$cnt = 0;
1507 1507
 
1508
-		foreach((array)$sortResult as $uid) {
1508
+		foreach ((array)$sortResult as $uid) {
1509 1509
 			$sortOrder[$uid] = $cnt++;
1510 1510
 		}
1511 1511
 
1512 1512
 		$count = 0;
1513 1513
 		if (is_object($headersNew)) {
1514
-			if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1515
-			foreach($headersNew->ids() as $id) {
1514
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1515
+			foreach ($headersNew->ids() as $id) {
1516 1516
 				$_headerObject = $headersNew->get($id);
1517 1517
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject));
1518 1518
 				$headerObject = array();
1519 1519
 				$bodyPreview = null;
1520
-				$uid = $headerObject['UID']= ($_headerObject->getUid()?$_headerObject->getUid():$id);
1520
+				$uid = $headerObject['UID'] = ($_headerObject->getUid() ? $_headerObject->getUid() : $id);
1521 1521
 				$headerObject['MSG_NUM'] = $_headerObject->getSeq();
1522 1522
 				$headerObject['SIZE'] = $_headerObject->getSize();
1523 1523
 				$headerObject['INTERNALDATE'] = $_headerObject->getImapDate();
1524 1524
 
1525 1525
 				// Get already cached headers, 'fetchHeaders' is a label matchimg above
1526
-				$headerForPrio = $_headerObject->getHeaders('fetchHeaders',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1526
+				$headerForPrio = $_headerObject->getHeaders('fetchHeaders', Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1527 1527
 				// Try to fetch header with key='' as some servers might have no fetchHeaders index. e.g. yandex.com
1528
-				if (empty($headerForPrio)) $headerForPrio = $_headerObject->getHeaders('',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1528
+				if (empty($headerForPrio)) $headerForPrio = $_headerObject->getHeaders('', Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1529 1529
 				//fetch the fullMsg part if all conditions match to be available in case $_headerObject->getHeaders returns
1530 1530
 				//nothing worthwhile (as it does for googlemail accounts, when preview is switched on
1531 1531
 				if ($_fetchPreviews)
@@ -1533,16 +1533,16 @@  discard block
 block discarded – undo
1533 1533
 					// on enabled preview $bodyPreview is needed lateron. fetched here, for fallback-reasons
1534 1534
 					// in case of failed Header-Retrieval
1535 1535
 					$bodyPreview = $_headerObject->getFullMsg();
1536
-					if (empty($headerForPrio)||(is_array($headerForPrio)&&count($headerForPrio)===1&&$headerForPrio['']))
1536
+					if (empty($headerForPrio) || (is_array($headerForPrio) && count($headerForPrio) === 1 && $headerForPrio['']))
1537 1537
 					{
1538 1538
 						$length = strpos($bodyPreview, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
1539
-						if ($length===false) $length = strlen($bodyPreview);
1540
-						$headerForPrio =  Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0,$length))->toArray();
1539
+						if ($length === false) $length = strlen($bodyPreview);
1540
+						$headerForPrio = Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0, $length))->toArray();
1541 1541
 					}
1542 1542
 				}
1543 1543
 				$headerForPrio = array_change_key_case($headerForPrio, CASE_UPPER);
1544 1544
 				if (self::$debug) {
1545
-					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'));
1545
+					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'));
1546 1546
 					error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerForPrio));
1547 1547
 				}
1548 1548
 				// message deleted from server but cache still reporting its existence ; may happen on QRESYNC with No permanent modsequences
@@ -1551,22 +1551,22 @@  discard block
 block discarded – undo
1551 1551
 					$total--;
1552 1552
 					continue;
1553 1553
 				}
1554
-				if ( isset($headerForPrio['DISPOSITION-NOTIFICATION-TO']) ) {
1554
+				if (isset($headerForPrio['DISPOSITION-NOTIFICATION-TO'])) {
1555 1555
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['DISPOSITION-NOTIFICATION-TO']));
1556
-				} else if ( isset($headerForPrio['RETURN-RECEIPT-TO']) ) {
1556
+				} else if (isset($headerForPrio['RETURN-RECEIPT-TO'])) {
1557 1557
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['RETURN-RECEIPT-TO']));
1558
-				} else if ( isset($headerForPrio['X-CONFIRM-READING-TO']) ) {
1558
+				} else if (isset($headerForPrio['X-CONFIRM-READING-TO'])) {
1559 1559
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['X-CONFIRM-READING-TO']));
1560 1560
 				} /*else $sent_not = "";*/
1561 1561
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1562 1562
 				$headerObject['DATE'] = $headerForPrio['DATE'];
1563
-				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT'])?$headerForPrio['SUBJECT'][0]:$headerForPrio['SUBJECT']);
1564
-				$headerObject['FROM'] = (array)($headerForPrio['FROM']?$headerForPrio['FROM']:($headerForPrio['REPLY-TO']?$headerForPrio['REPLY-TO']:$headerForPrio['RETURN-PATH']));
1563
+				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT']) ? $headerForPrio['SUBJECT'][0] : $headerForPrio['SUBJECT']);
1564
+				$headerObject['FROM'] = (array)($headerForPrio['FROM'] ? $headerForPrio['FROM'] : ($headerForPrio['REPLY-TO'] ? $headerForPrio['REPLY-TO'] : $headerForPrio['RETURN-PATH']));
1565 1565
 				$headerObject['TO'] = (array)$headerForPrio['TO'];
1566
-				$headerObject['CC'] = isset($headerForPrio['CC'])?(array)$headerForPrio['CC']:array();
1567
-				$headerObject['REPLY-TO'] = isset($headerForPrio['REPLY-TO'])?(array)$headerForPrio['REPLY-TO']:array();
1568
-				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY'])?$headerForPrio['X-PRIORITY']:null;
1569
-				foreach (array('FROM','TO','CC','REPLY-TO') as $key)
1566
+				$headerObject['CC'] = isset($headerForPrio['CC']) ? (array)$headerForPrio['CC'] : array();
1567
+				$headerObject['REPLY-TO'] = isset($headerForPrio['REPLY-TO']) ? (array)$headerForPrio['REPLY-TO'] : array();
1568
+				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY']) ? $headerForPrio['X-PRIORITY'] : null;
1569
+				foreach (array('FROM', 'TO', 'CC', 'REPLY-TO') as $key)
1570 1570
 				{
1571 1571
 					$address = array();
1572 1572
 					foreach ($headerObject[$key] as $k => $ad)
@@ -1588,13 +1588,13 @@  discard block
 block discarded – undo
1588 1588
 						foreach ($rfcAddr as $_rfcAddr)
1589 1589
 						{
1590 1590
 							if (!$_rfcAddr->valid)	continue; // skip. not a valid address
1591
-							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox,$_rfcAddr->host,$_rfcAddr->personal);
1591
+							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox, $_rfcAddr->host, $_rfcAddr->personal);
1592 1592
 						}
1593 1593
 					}
1594 1594
 					$headerObject[$key] = $address;
1595 1595
 				}
1596 1596
 				$headerObject['FLAGS'] = $_headerObject->getFlags();
1597
-				$headerObject['BODYPREVIEW']=null;
1597
+				$headerObject['BODYPREVIEW'] = null;
1598 1598
 				// this section fetches part of the message-body (if enabled) for some kind of preview
1599 1599
 				// if we fail to succeed, we fall back to the retrieval of the message-body with
1600 1600
 				// fetchPartContents (see below, when we iterate over the structure to determine the
@@ -1606,17 +1606,17 @@  discard block
 block discarded – undo
1606 1606
 					if (empty($bodyPreview)) $bodyPreview = $_headerObject->getFullMsg();
1607 1607
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($bodyPreview));
1608 1608
 					$base = Horde_Mime_Part::parseMessage($bodyPreview);
1609
-					foreach($base->partIterator() as $part)
1609
+					foreach ($base->partIterator() as $part)
1610 1610
 					{
1611 1611
 						//error_log(__METHOD__.__LINE__.'Part:'.$part->getPrimaryType());
1612
-						if (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'text')
1612
+						if (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'text')
1613 1613
 						{
1614 1614
 							$charset = $part->getContentTypeParameter('charset');
1615 1615
 							$buffer = Mail\Html::convertHTMLToText($part->toString(array(
1616
-												'encode' => Horde_Mime_Part::ENCODE_BINARY,	// otherwise we cant recode charset
1616
+												'encode' => Horde_Mime_Part::ENCODE_BINARY, // otherwise we cant recode charset
1617 1617
 											)), $charset, 'utf-8');
1618
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Translation::convert_jsonsafe($buffer),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1619
-						} elseif (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'multipart')
1618
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Translation::convert_jsonsafe($buffer), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1619
+						} elseif (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'multipart')
1620 1620
 						{
1621 1621
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part));
1622 1622
 						}
@@ -1627,12 +1627,12 @@  discard block
 block discarded – undo
1627 1627
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1628 1628
 				//error_log(__METHOD__.' ('.__LINE__.') '.' MimeMap:'.array2string($mailStructureObject->contentTypeMap()));
1629 1629
 				//foreach ($_headerObject->getStructure()->getParts() as $p => $part)
1630
-				$headerObject['ATTACHMENTS']=null;
1631
-				$skipParts=array();
1632
-				$messageMimeType='';
1630
+				$headerObject['ATTACHMENTS'] = null;
1631
+				$skipParts = array();
1632
+				$messageMimeType = '';
1633 1633
 				foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
1634 1634
 				{
1635
-					if ($mime_id==0 || $messageMimeType==='') $messageMimeType = $mime_type;
1635
+					if ($mime_id == 0 || $messageMimeType === '') $messageMimeType = $mime_type;
1636 1636
 					$part = $mailStructureObject->getPart($mime_id);
1637 1637
 					$partdisposition = $part->getDisposition();
1638 1638
 					$partPrimaryType = $part->getPrimaryType();
@@ -1640,16 +1640,16 @@  discard block
 block discarded – undo
1640 1640
 					// drawback here it is talking to the mailserver for each mail thus consuming
1641 1641
 					// more time than expected; so we call this section only when there is no
1642 1642
 					// bodypreview could be found (multipart/....)
1643
-					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW'])&&($partPrimaryType == 'text') &&
1643
+					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW']) && ($partPrimaryType == 'text') &&
1644 1644
 						((intval($mime_id) === 1) || !$mime_id) &&
1645 1645
 						($partdisposition !== 'attachment')) {
1646
-							$_structure=$part;
1647
-							$this->fetchPartContents($uid, $_structure, false,true);
1648
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1649
-							$charSet=Translation::detect_encoding($headerObject['BODYPREVIEW']);
1646
+							$_structure = $part;
1647
+							$this->fetchPartContents($uid, $_structure, false, true);
1648
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1649
+							$charSet = Translation::detect_encoding($headerObject['BODYPREVIEW']);
1650 1650
 							// add line breaks to $bodyParts
1651 1651
 							//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
1652
-							$headerObject['BODYPREVIEW']  = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1652
+							$headerObject['BODYPREVIEW'] = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1653 1653
 							//error_log(__METHOD__.__LINE__.$headerObject['BODYPREVIEW']);
1654 1654
 					}
1655 1655
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType);
@@ -1659,28 +1659,28 @@  discard block
 block discarded – undo
1659 1659
 						// the presence of an cid does not necessarily indicate its inline. it may lack the needed
1660 1660
 						// link to show the image. Considering this: we "list" everything that matches the above criteria
1661 1661
 						// as attachment in order to not loose/miss information on our data
1662
-						$partdisposition='attachment';//($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1662
+						$partdisposition = 'attachment'; //($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1663 1663
 					}
1664
-					if ($mime_type=='message/rfc822')
1664
+					if ($mime_type == 'message/rfc822')
1665 1665
 					{
1666 1666
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
1667
-						foreach($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
1667
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
1668 1668
 					}
1669 1669
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType.' Skip:'.array2string($skipParts));
1670
-					if (array_key_exists($mime_id,$skipParts)) continue;
1671
-					if ($partdisposition=='attachment' ||
1672
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&$mime_type=='image/tiff') || // as we are not able to display tiffs
1673
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&empty($cid)) ||
1674
-						($partdisposition=='inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1670
+					if (array_key_exists($mime_id, $skipParts)) continue;
1671
+					if ($partdisposition == 'attachment' ||
1672
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && $mime_type == 'image/tiff') || // as we are not able to display tiffs
1673
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && empty($cid)) ||
1674
+						($partdisposition == 'inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1675 1675
 					{
1676
-						$headerObject['ATTACHMENTS'][$mime_id]=$part->getAllDispositionParameters();
1677
-						$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=$mime_type;
1678
-						$headerObject['ATTACHMENTS'][$mime_id]['uid']=$uid;
1676
+						$headerObject['ATTACHMENTS'][$mime_id] = $part->getAllDispositionParameters();
1677
+						$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] = $mime_type;
1678
+						$headerObject['ATTACHMENTS'][$mime_id]['uid'] = $uid;
1679 1679
 						$headerObject['ATTACHMENTS'][$mime_id]['cid'] = $cid;
1680
-						$headerObject['ATTACHMENTS'][$mime_id]['partID']=$mime_id;
1681
-						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))$headerObject['ATTACHMENTS'][$mime_id]['name']=$part->getName();
1682
-						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'],'winmail.dat') ||
1683
-							$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=='application/ms-tnef')
1680
+						$headerObject['ATTACHMENTS'][$mime_id]['partID'] = $mime_id;
1681
+						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))$headerObject['ATTACHMENTS'][$mime_id]['name'] = $part->getName();
1682
+						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'], 'winmail.dat') ||
1683
+							$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] == 'application/ms-tnef')
1684 1684
 						{
1685 1685
 							$headerObject['ATTACHMENTS'][$mime_id]['is_winmail'] = true;
1686 1686
 						}
@@ -1695,57 +1695,57 @@  discard block
 block discarded – undo
1695 1695
 				if (empty($headerObject['UID'])) continue;
1696 1696
 				//$uid = ($rByUid ? $headerObject['UID'] : $headerObject['MSG_NUM']);
1697 1697
 				// make dates like "Mon, 23 Apr 2007 10:11:06 UT" working with strtotime
1698
-				if(substr($headerObject['DATE'],-2) === 'UT') {
1698
+				if (substr($headerObject['DATE'], -2) === 'UT') {
1699 1699
 					$headerObject['DATE'] .= 'C';
1700 1700
 				}
1701
-				if(substr($headerObject['INTERNALDATE'],-2) === 'UT') {
1701
+				if (substr($headerObject['INTERNALDATE'], -2) === 'UT') {
1702 1702
 					$headerObject['INTERNALDATE'] .= 'C';
1703 1703
 				}
1704 1704
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$headerObject['SUBJECT'].'->'.$headerObject['DATE'].'<->'.$headerObject['INTERNALDATE'] .'#');
1705 1705
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$this->decode_subject($headerObject['SUBJECT']).'->'.$headerObject['DATE']);
1706
-				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][]=$a;}
1707
-				$retValue['header'][$sortOrder[$uid]]['subject']	= $this->decode_subject($headerObject['SUBJECT']);
1708
-				$retValue['header'][$sortOrder[$uid]]['size'] 		= $headerObject['SIZE'];
1709
-				$retValue['header'][$sortOrder[$uid]]['date']		= self::_strtotime(($headerObject['DATE']&&!($headerObject['DATE']=='NIL')?$headerObject['DATE']:$headerObject['INTERNALDATE']),'ts',true);
1710
-				$retValue['header'][$sortOrder[$uid]]['internaldate']= self::_strtotime($headerObject['INTERNALDATE'],'ts',true);
1711
-				$retValue['header'][$sortOrder[$uid]]['mimetype']	= $messageMimeType;
1712
-				$retValue['header'][$sortOrder[$uid]]['id']		= $headerObject['MSG_NUM'];
1713
-				$retValue['header'][$sortOrder[$uid]]['uid']		= $headerObject['UID'];
1714
-				$retValue['header'][$sortOrder[$uid]]['bodypreview']		= $headerObject['BODYPREVIEW'];
1715
-				$retValue['header'][$sortOrder[$uid]]['priority']		= ($headerObject['PRIORITY']?$headerObject['PRIORITY']:3);
1706
+				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][] = $a; }
1707
+				$retValue['header'][$sortOrder[$uid]]['subject'] = $this->decode_subject($headerObject['SUBJECT']);
1708
+				$retValue['header'][$sortOrder[$uid]]['size'] = $headerObject['SIZE'];
1709
+				$retValue['header'][$sortOrder[$uid]]['date'] = self::_strtotime(($headerObject['DATE'] && !($headerObject['DATE'] == 'NIL') ? $headerObject['DATE'] : $headerObject['INTERNALDATE']), 'ts', true);
1710
+				$retValue['header'][$sortOrder[$uid]]['internaldate'] = self::_strtotime($headerObject['INTERNALDATE'], 'ts', true);
1711
+				$retValue['header'][$sortOrder[$uid]]['mimetype'] = $messageMimeType;
1712
+				$retValue['header'][$sortOrder[$uid]]['id'] = $headerObject['MSG_NUM'];
1713
+				$retValue['header'][$sortOrder[$uid]]['uid'] = $headerObject['UID'];
1714
+				$retValue['header'][$sortOrder[$uid]]['bodypreview'] = $headerObject['BODYPREVIEW'];
1715
+				$retValue['header'][$sortOrder[$uid]]['priority'] = ($headerObject['PRIORITY'] ? $headerObject['PRIORITY'] : 3);
1716 1716
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.array2string($retValue['header'][$sortOrder[$uid]]));
1717 1717
 				if (isset($headerObject['DISPOSITION-NOTIFICATION-TO'])) $retValue['header'][$sortOrder[$uid]]['disposition-notification-to'] = $headerObject['DISPOSITION-NOTIFICATION-TO'];
1718 1718
 				if (is_array($headerObject['FLAGS'])) {
1719
-					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]],self::prepareFlagsArray($headerObject));
1719
+					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]], self::prepareFlagsArray($headerObject));
1720 1720
 				}
1721 1721
 				//error_log(__METHOD__.' ('.__LINE__.') '.$headerObject['SUBJECT'].'->'.array2string($_headerObject->getEnvelope()->__get('from')));
1722
-				if(is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1723
-					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0],true);
1722
+				if (is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1723
+					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0], true);
1724 1724
 				}
1725
-				if(is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0]) {
1726
-					$retValue['header'][$sortOrder[$uid]]['reply_to_address'] = self::decode_header($headerObject['REPLY-TO'][0],true);
1725
+				if (is_array($headerObject['REPLY-TO']) && $headerObject['REPLY-TO'][0]) {
1726
+					$retValue['header'][$sortOrder[$uid]]['reply_to_address'] = self::decode_header($headerObject['REPLY-TO'][0], true);
1727 1727
 				}
1728
-				if(is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1729
-					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0],true);
1730
-					if (count($headerObject['TO'])>1)
1728
+				if (is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1729
+					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0], true);
1730
+					if (count($headerObject['TO']) > 1)
1731 1731
 					{
1732
-						$ki=0;
1733
-						foreach($headerObject['TO'] as $k => $add)
1732
+						$ki = 0;
1733
+						foreach ($headerObject['TO'] as $k => $add)
1734 1734
 						{
1735
-							if ($k==0) continue;
1735
+							if ($k == 0) continue;
1736 1736
 							//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1737
-							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add,true);
1737
+							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add, true);
1738 1738
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1739 1739
 							$ki++;
1740 1740
 						}
1741 1741
 					}
1742 1742
 				}
1743
-				if(is_array($headerObject['CC']) && count($headerObject['CC'])>0) {
1744
-					$ki=0;
1745
-					foreach($headerObject['CC'] as $k => $add)
1743
+				if (is_array($headerObject['CC']) && count($headerObject['CC']) > 0) {
1744
+					$ki = 0;
1745
+					foreach ($headerObject['CC'] as $k => $add)
1746 1746
 					{
1747 1747
 						//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1748
-						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add,true);
1748
+						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add, true);
1749 1749
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1750 1750
 						$ki++;
1751 1751
 					}
@@ -1754,27 +1754,27 @@  discard block
 block discarded – undo
1754 1754
 
1755 1755
 				$count++;
1756 1756
 			}
1757
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' fetching Headers and stuff for Folder:'.$_folderName,__METHOD__.' ('.__LINE__.') ');
1757
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' fetching Headers and stuff for Folder:'.$_folderName, __METHOD__.' ('.__LINE__.') ');
1758 1758
 			//self::$debug=false;
1759 1759
 			// sort the messages to the requested displayorder
1760
-			if(is_array($retValue['header'])) {
1760
+			if (is_array($retValue['header'])) {
1761 1761
 				$countMessages = $total;
1762 1762
 				if (isset($_filter['range'])) $countMessages = self::$folderStatusCache[$this->profileID][$_folderName]['messages'];
1763 1763
 				ksort($retValue['header']);
1764 1764
 				$retValue['info']['total']	= $total;
1765 1765
 				//if ($_startMessage>$total) $_startMessage = $total-($count-1);
1766 1766
 				$retValue['info']['first']	= $_startMessage;
1767
-				$retValue['info']['last']	= $_startMessage + $count - 1 ;
1767
+				$retValue['info']['last'] = $_startMessage + $count - 1;
1768 1768
 				return $retValue;
1769 1769
 			} else {
1770 1770
 				$retValue = array();
1771 1771
 				$retValue['info']['total']	= 0;
1772 1772
 				$retValue['info']['first']	= 0;
1773
-				$retValue['info']['last']	= 0;
1773
+				$retValue['info']['last'] = 0;
1774 1774
 				return $retValue;
1775 1775
 			}
1776 1776
 		} else {
1777
-			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew,TRUE));
1777
+			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew, TRUE));
1778 1778
 			$retValue = array();
1779 1779
 			$retValue['info']['total']  = 0;
1780 1780
 			$retValue['info']['first']  = 0;
@@ -1791,17 +1791,17 @@  discard block
 block discarded – undo
1791 1791
 	 */
1792 1792
 	static function prepareFlagsArray($headerObject)
1793 1793
 	{
1794
-		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower',$headerObject['FLAGS']);
1794
+		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower', $headerObject['FLAGS']);
1795 1795
 		$retValue = array();
1796 1796
 		$retValue['recent']		= in_array('\\recent', $headerFlags);
1797 1797
 		$retValue['flagged']	= in_array('\\flagged', $headerFlags);
1798
-		$retValue['answered']	= in_array('\\answered', $headerFlags);
1799
-		$retValue['forwarded']   = in_array('$forwarded', $headerFlags);
1798
+		$retValue['answered'] = in_array('\\answered', $headerFlags);
1799
+		$retValue['forwarded'] = in_array('$forwarded', $headerFlags);
1800 1800
 		$retValue['deleted']	= in_array('\\deleted', $headerFlags);
1801
-		$retValue['seen']		= in_array('\\seen', $headerFlags);
1802
-		$retValue['draft']		= in_array('\\draft', $headerFlags);
1803
-		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags)||in_array('mdnsent', $headerFlags);
1804
-		$retValue['mdnnotsent']	= in_array('$mdnnotsent', $headerFlags)||in_array('mdnnotsent', $headerFlags);
1801
+		$retValue['seen'] = in_array('\\seen', $headerFlags);
1802
+		$retValue['draft'] = in_array('\\draft', $headerFlags);
1803
+		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags) || in_array('mdnsent', $headerFlags);
1804
+		$retValue['mdnnotsent'] = in_array('$mdnnotsent', $headerFlags) || in_array('mdnnotsent', $headerFlags);
1805 1805
 		$retValue['label1']   = in_array('$label1', $headerFlags);
1806 1806
 		$retValue['label2']   = in_array('$label2', $headerFlags);
1807 1807
 		$retValue['label3']   = in_array('$label3', $headerFlags);
@@ -1825,12 +1825,12 @@  discard block
 block discarded – undo
1825 1825
 	 * @param bool $setSession if set to true the session will be populated with the result of the query
1826 1826
 	 * @return mixed bool/array false or array of ids
1827 1827
 	 */
1828
-	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid=true, $setSession=true)
1828
+	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid = true, $setSession = true)
1829 1829
 	{
1830 1830
 		static $cachedFolderStatus = null;
1831 1831
 		// in the past we needed examineMailbox to figure out if the server with the serverID support keywords
1832 1832
 		// this information is filled/provided by examineMailbox; but caching within one request seems o.k.
1833
-		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]) )
1833
+		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]))
1834 1834
 		{
1835 1835
 			$folderStatus = $cachedFolderStatus[$this->profileID][$_folderName] = $this->icServer->examineMailbox($_folderName);
1836 1836
 		}
@@ -1842,29 +1842,29 @@  discard block
 block discarded – undo
1842 1842
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Filter:'.array2string($_filter));
1843 1843
 		$try2useCache = true;
1844 1844
 		static $eMailListContainsDeletedMessages = null;
1845
-		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
1845
+		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
1846 1846
 		// this indicates, that there is no Filter set, and the returned set/subset should not contain DELETED Messages, nor filtered for UNDELETED
1847
-		if ($setSession==true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1847
+		if ($setSession == true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1848 1848
 		{
1849 1849
 			if (self::$debugTimes) $starttime = microtime(true);
1850
-			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);
1851
-			$five=true;
1852
-			$dReverse=1;
1853
-			$deletedMessages = $this->getSortedList($_folderName, 0, $dReverse, array('status'=>array('DELETED')),$five,false);
1850
+			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);
1851
+			$five = true;
1852
+			$dReverse = 1;
1853
+			$deletedMessages = $this->getSortedList($_folderName, 0, $dReverse, array('status'=>array('DELETED')), $five, false);
1854 1854
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') Found DeletedMessages:'.array2string($eMailListContainsDeletedMessages));
1855
-			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] =$deletedMessages['count'];
1856
-			Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),$eMailListContainsDeletedMessages, 60*60*1);
1857
-			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']);
1855
+			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] = $deletedMessages['count'];
1856
+			Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), $eMailListContainsDeletedMessages, 60 * 60 * 1);
1857
+			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']);
1858 1858
 		}
1859 1859
 		$try2useCache = false;
1860 1860
 		//self::$supportsORinQuery[$this->profileID]=true;
1861 1861
 		if (is_null(self::$supportsORinQuery) || !isset(self::$supportsORinQuery[$this->profileID]))
1862 1862
 		{
1863
-			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
1864
-			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID]=true;
1863
+			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
1864
+			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID] = true;
1865 1865
 		}
1866 1866
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_filter).' SupportsOrInQuery:'.self::$supportsORinQuery[$this->profileID]);
1867
-		$filter = $this->createIMAPFilter($_folderName, $_filter,self::$supportsORinQuery[$this->profileID]);
1867
+		$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1868 1868
 		if (self::$debug)
1869 1869
 		{
1870 1870
 			$query_str = $filter->build();
@@ -1872,14 +1872,14 @@  discard block
 block discarded – undo
1872 1872
 		}
1873 1873
 		//_debug_array($filter);
1874 1874
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($filter).'#'.array2string($this->icServer->capability()));
1875
-		if($this->icServer->hasCapability('SORT')) {
1875
+		if ($this->icServer->hasCapability('SORT')) {
1876 1876
 			// when using an orQuery and we sort by date. sort seems to fail on certain servers => ZIMBRA with Horde_Imap_Client
1877 1877
 			// thus we translate the search request from date to Horde_Imap_Client::SORT_SEQUENCE (which should be the same, if
1878 1878
 			// there is no messing with the dates)
1879 1879
 			//if (self::$supportsORinQuery[$this->profileID]&&$_sort=='date'&&$_filter['type']=='quick'&&!empty($_filter['string']))$_sort='INTERNALDATE';
1880 1880
 			if (self::$debug) error_log(__METHOD__." Mailserver has SORT Capability, SortBy: ".array2string($_sort)." Reverse: $_reverse");
1881 1881
 			$sortOrder = $this->_getSortString($_sort, $_reverse);
1882
-			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE,$sortOrder)) $_reverse=false; // as we reversed the result already
1882
+			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE, $sortOrder)) $_reverse = false; // as we reversed the result already
1883 1883
 			if (self::$debug) error_log(__METHOD__." Mailserver runs SORT: SortBy:".array2string($_sort)."->".array2string($sortOrder)." Filter: ".array2string($filter));
1884 1884
 			try
1885 1885
 			{
@@ -1893,24 +1893,24 @@  discard block
 block discarded – undo
1893 1893
 
1894 1894
 			// if there is an Error, we assume that the server is not capable of sorting
1895 1895
 			}
1896
-			catch(\Exception $e)
1896
+			catch (\Exception $e)
1897 1897
 			{
1898 1898
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1899 1899
 				$resultByUid = false;
1900 1900
 				$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
1901
-				if ($_reverse) array_unshift($sortOrder,Horde_Imap_Client::SORT_REVERSE);
1901
+				if ($_reverse) array_unshift($sortOrder, Horde_Imap_Client::SORT_REVERSE);
1902 1902
 				try
1903 1903
 				{
1904 1904
 					$sortResult = $this->icServer->search($_folderName, $filter, array(
1905 1905
 						'sort' => $sortOrder));
1906 1906
 				}
1907
-				catch(\Exception $e)
1907
+				catch (\Exception $e)
1908 1908
 				{
1909 1909
 					error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1910 1910
 					$sortResult = self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'];
1911 1911
 				}
1912 1912
 			}
1913
-			if (self::$debug) error_log(__METHOD__.print_r($sortResult,true));
1913
+			if (self::$debug) error_log(__METHOD__.print_r($sortResult, true));
1914 1914
 		} else {
1915 1915
 			if (self::$debug) error_log(__METHOD__." Mailserver has NO SORT Capability");
1916 1916
 			//$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
@@ -1920,12 +1920,12 @@  discard block
 block discarded – undo
1920 1920
 				$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
1921 1921
 					'sort' => $sortOrder)*/);
1922 1922
 			}
1923
-			catch(\Exception $e)
1923
+			catch (\Exception $e)
1924 1924
 			{
1925 1925
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1926 1926
 				// possible error OR Query. But Horde gives no detailed Info :-(
1927
-				self::$supportsORinQuery[$this->profileID]=false;
1928
-				Cache::setCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),self::$supportsORinQuery,60*60*10);
1927
+				self::$supportsORinQuery[$this->profileID] = false;
1928
+				Cache::setCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), self::$supportsORinQuery, 60 * 60 * 10);
1929 1929
 				if (self::$debug) error_log(__METHOD__.__LINE__." Mailserver seems to have NO OR Capability for Search:".$sortResult->message);
1930 1930
 				$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1931 1931
 				try
@@ -1933,25 +1933,25 @@  discard block
 block discarded – undo
1933 1933
 					$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
1934 1934
 						'sort' => $sortOrder)*/);
1935 1935
 				}
1936
-				catch(\Exception $e)
1936
+				catch (\Exception $e)
1937 1937
 				{
1938 1938
 				}
1939 1939
 			}
1940
-			if(is_array($sortResult['match'])) {
1940
+			if (is_array($sortResult['match'])) {
1941 1941
 					// not sure that this is going so succeed as $sortResult['match'] is a hordeObject
1942 1942
 					sort($sortResult['match'], SORT_NUMERIC);
1943 1943
 			}
1944
-			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
1944
+			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter, true)." ->".print_r($sortResult, true));
1945 1945
 		}
1946 1946
 		if ($setSession)
1947 1947
 		{
1948 1948
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidValidity'] = $folderStatus['UIDVALIDITY'];
1949
-			self::$folderStatusCache[$this->profileID][$_folderName]['messages']	= $folderStatus['MESSAGES'];
1949
+			self::$folderStatusCache[$this->profileID][$_folderName]['messages'] = $folderStatus['MESSAGES'];
1950 1950
 			self::$folderStatusCache[$this->profileID][$_folderName]['deleted']	= $eMailListContainsDeletedMessages[$this->profileID][$_folderName];
1951 1951
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidnext']	= $folderStatus['UIDNEXT'];
1952
-			self::$folderStatusCache[$this->profileID][$_folderName]['filter']	= $_filter;
1952
+			self::$folderStatusCache[$this->profileID][$_folderName]['filter'] = $_filter;
1953 1953
 			self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'] = $sortResult;
1954
-			self::$folderStatusCache[$this->profileID][$_folderName]['sort']	= $_sort;
1954
+			self::$folderStatusCache[$this->profileID][$_folderName]['sort'] = $_sort;
1955 1955
 		}
1956 1956
 		//error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
1957 1957
 		//_debug_array($sortResult['match']->ids);
@@ -1965,12 +1965,12 @@  discard block
 block discarded – undo
1965 1965
 	 * @param bool _reverse wether to add REVERSE to the Sort String or not
1966 1966
 	 * @return the sort sequence for horde search
1967 1967
 	 */
1968
-	function _getSortString($_sort, $_reverse=false)
1968
+	function _getSortString($_sort, $_reverse = false)
1969 1969
 	{
1970
-		$_reverse=false;
1970
+		$_reverse = false;
1971 1971
 		if (is_numeric($_sort))
1972 1972
 		{
1973
-			switch($_sort) {
1973
+			switch ($_sort) {
1974 1974
 				case 2:
1975 1975
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1976 1976
 					break;
@@ -1992,7 +1992,7 @@  discard block
 block discarded – undo
1992 1992
 		}
1993 1993
 		else
1994 1994
 		{
1995
-			switch(strtoupper($_sort)) {
1995
+			switch (strtoupper($_sort)) {
1996 1996
 				case 'FROMADDRESS':
1997 1997
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1998 1998
 					break;
@@ -2018,7 +2018,7 @@  discard block
 block discarded – undo
2018 2018
 					break;
2019 2019
 			}
2020 2020
 		}
2021
-		if ($_reverse) array_unshift($retValue,Horde_Imap_Client::SORT_REVERSE);
2021
+		if ($_reverse) array_unshift($retValue, Horde_Imap_Client::SORT_REVERSE);
2022 2022
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.($_reverse?'REVERSE ':'').$_sort.'->'.$retValue);
2023 2023
 		return $retValue;
2024 2024
 	}
@@ -2031,28 +2031,28 @@  discard block
 block discarded – undo
2031 2031
 	 * @param boolean $_supportsOrInQuery wether to use the OR Query on QuickSearch
2032 2032
 	 * @return Horde_Imap_Client_Search_Query the IMAP filter
2033 2033
 	 */
2034
-	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery=true)
2034
+	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery = true)
2035 2035
 	{
2036 2036
 		$imapFilter = new Horde_Imap_Client_Search_Query();
2037 2037
 		$imapFilter->charset('UTF-8');
2038 2038
 
2039 2039
 		//_debug_array($_criterias);
2040
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2041
-		if((!is_array($_criterias) || $_criterias['status']=='any') &&
2040
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias) ? " none -> returning" : array2string($_criterias)));
2041
+		if ((!is_array($_criterias) || $_criterias['status'] == 'any') &&
2042 2042
 			(!isset($_criterias['string']) || empty($_criterias['string'])) &&
2043
-			(!isset($_criterias['range'])|| empty($_criterias['range']) ||
2044
-			( !empty($_criterias['range'])&& ($_criterias['range']!='BETWEEN' && empty($_criterias['date'])||
2045
-			($_criterias['range']=='BETWEEN' && empty($_criterias['since'])&& empty($_criterias['before']))))))
2043
+			(!isset($_criterias['range']) || empty($_criterias['range']) ||
2044
+			(!empty($_criterias['range']) && ($_criterias['range'] != 'BETWEEN' && empty($_criterias['date']) ||
2045
+			($_criterias['range'] == 'BETWEEN' && empty($_criterias['since']) && empty($_criterias['before']))))))
2046 2046
 		{
2047 2047
 			//error_log(__METHOD__.' ('.__LINE__.') returning early Criterias:'.print_r($_criterias, true));
2048
-			$imapFilter->flag('DELETED', $set=false);
2048
+			$imapFilter->flag('DELETED', $set = false);
2049 2049
 			return $imapFilter;
2050 2050
 		}
2051 2051
 		$queryValid = false;
2052 2052
 		// statusQuery MUST be placed first, as search for subject/mailbody and such is
2053 2053
 		// depending on charset. flagSearch is not BUT messes the charset if called afterwards
2054 2054
 		$statusQueryValid = false;
2055
-		foreach((array)$_criterias['status'] as $k => $criteria) {
2055
+		foreach ((array)$_criterias['status'] as $k => $criteria) {
2056 2056
 			$imapStatusFilter = new Horde_Imap_Client_Search_Query();
2057 2057
 			$imapStatusFilter->charset('UTF-8');
2058 2058
 			$criteria = strtoupper($criteria);
@@ -2062,12 +2062,12 @@  discard block
 block discarded – undo
2062 2062
 				case 'FLAGGED':
2063 2063
 				case 'RECENT':
2064 2064
 				case 'SEEN':
2065
-					$imapStatusFilter->flag($criteria, $set=true);
2066
-					$queryValid = $statusQueryValid =true;
2065
+					$imapStatusFilter->flag($criteria, $set = true);
2066
+					$queryValid = $statusQueryValid = true;
2067 2067
 					break;
2068 2068
 				case 'READ':
2069
-					$imapStatusFilter->flag('SEEN', $set=true);
2070
-					$queryValid = $statusQueryValid =true;
2069
+					$imapStatusFilter->flag('SEEN', $set = true);
2070
+					$queryValid = $statusQueryValid = true;
2071 2071
 					break;
2072 2072
 				case 'LABEL1':
2073 2073
 				case 'KEYWORD1':
@@ -2079,38 +2079,38 @@  discard block
 block discarded – undo
2079 2079
 				case 'KEYWORD4':
2080 2080
 				case 'LABEL5':
2081 2081
 				case 'KEYWORD5':
2082
-					$imapStatusFilter->flag(str_ireplace('KEYWORD','$LABEL',$criteria), $set=true);
2083
-					$queryValid = $statusQueryValid =true;
2082
+					$imapStatusFilter->flag(str_ireplace('KEYWORD', '$LABEL', $criteria), $set = true);
2083
+					$queryValid = $statusQueryValid = true;
2084 2084
 					break;
2085 2085
 				case 'NEW':
2086
-					$imapStatusFilter->flag('RECENT', $set=true);
2087
-					$imapStatusFilter->flag('SEEN', $set=false);
2088
-					$queryValid = $statusQueryValid =true;
2086
+					$imapStatusFilter->flag('RECENT', $set = true);
2087
+					$imapStatusFilter->flag('SEEN', $set = false);
2088
+					$queryValid = $statusQueryValid = true;
2089 2089
 					break;
2090 2090
 				case 'OLD':
2091
-					$imapStatusFilter->flag('RECENT', $set=false);
2092
-					$queryValid = $statusQueryValid =true;
2091
+					$imapStatusFilter->flag('RECENT', $set = false);
2092
+					$queryValid = $statusQueryValid = true;
2093 2093
 					break;
2094 2094
 // operate only on system flags
2095 2095
 //        $systemflags = array(
2096 2096
 //            'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'RECENT', 'SEEN'
2097 2097
 //        );
2098 2098
 				case 'UNANSWERED':
2099
-					$imapStatusFilter->flag('ANSWERED', $set=false);
2100
-					$queryValid = $statusQueryValid =true;
2099
+					$imapStatusFilter->flag('ANSWERED', $set = false);
2100
+					$queryValid = $statusQueryValid = true;
2101 2101
 					break;
2102 2102
 				case 'UNDELETED':
2103
-					$imapFilter->flag('DELETED', $set=false);
2103
+					$imapFilter->flag('DELETED', $set = false);
2104 2104
 					$queryValid = true;
2105 2105
 					break;
2106 2106
 				case 'UNFLAGGED':
2107
-					$imapStatusFilter->flag('FLAGGED', $set=false);
2108
-					$queryValid = $statusQueryValid =true;
2107
+					$imapStatusFilter->flag('FLAGGED', $set = false);
2108
+					$queryValid = $statusQueryValid = true;
2109 2109
 					break;
2110 2110
 				case 'UNREAD':
2111 2111
 				case 'UNSEEN':
2112
-					$imapStatusFilter->flag('SEEN', $set=false);
2113
-					$queryValid = $statusQueryValid =true;
2112
+					$imapStatusFilter->flag('SEEN', $set = false);
2113
+					$queryValid = $statusQueryValid = true;
2114 2114
 					break;
2115 2115
 				case 'UNLABEL1':
2116 2116
 				case 'UNKEYWORD1':
@@ -2122,8 +2122,8 @@  discard block
 block discarded – undo
2122 2122
 				case 'UNKEYWORD4':
2123 2123
 				case 'UNLABEL5':
2124 2124
 				case 'UNKEYWORD5':
2125
-					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD','UNLABEL'),'$LABEL',$criteria), $set=false);
2126
-					$queryValid = $statusQueryValid =true;
2125
+					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD', 'UNLABEL'), '$LABEL', $criteria), $set = false);
2126
+					$queryValid = $statusQueryValid = true;
2127 2127
 					break;
2128 2128
 				default:
2129 2129
 					$statusQueryValid = false;
@@ -2139,20 +2139,20 @@  discard block
 block discarded – undo
2139 2139
 		$imapSearchFilter = new Horde_Imap_Client_Search_Query();
2140 2140
 		$imapSearchFilter->charset('UTF-8');
2141 2141
 
2142
-		if(!empty($_criterias['string'])) {
2142
+		if (!empty($_criterias['string'])) {
2143 2143
 			$criteria = strtoupper($_criterias['type']);
2144 2144
 			switch ($criteria) {
2145 2145
 				case 'BYDATE':
2146 2146
 				case 'QUICK':
2147 2147
 				case 'QUICKWITHCC':
2148
-					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not=false);
2148
+					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not = false);
2149 2149
 					//$imapSearchFilter->charset('UTF-8');
2150 2150
 					$imapFilter2 = new Horde_Imap_Client_Search_Query();
2151 2151
 					$imapFilter2->charset('UTF-8');
2152
-					if($this->isSentFolder($_folder)) {
2153
-						$imapFilter2->headerText('TO', $_criterias['string'], $not=false);
2152
+					if ($this->isSentFolder($_folder)) {
2153
+						$imapFilter2->headerText('TO', $_criterias['string'], $not = false);
2154 2154
 					} else {
2155
-						$imapFilter2->headerText('FROM', $_criterias['string'], $not=false);
2155
+						$imapFilter2->headerText('FROM', $_criterias['string'], $not = false);
2156 2156
 					}
2157 2157
 					if ($_supportsOrInQuery)
2158 2158
 					{
@@ -2162,31 +2162,31 @@  discard block
 block discarded – undo
2162 2162
 					{
2163 2163
 						$imapSearchFilter->andSearch($imapFilter2);
2164 2164
 					}
2165
-					if ($_supportsOrInQuery && $criteria=='QUICKWITHCC')
2165
+					if ($_supportsOrInQuery && $criteria == 'QUICKWITHCC')
2166 2166
 					{
2167 2167
 						$imapFilter3 = new Horde_Imap_Client_Search_Query();
2168 2168
 						$imapFilter3->charset('UTF-8');
2169
-						$imapFilter3->headerText('CC', $_criterias['string'], $not=false);
2169
+						$imapFilter3->headerText('CC', $_criterias['string'], $not = false);
2170 2170
 						$imapSearchFilter->orSearch($imapFilter3);
2171 2171
 					}
2172 2172
 					$queryValid = true;
2173 2173
 					break;
2174 2174
 				case 'LARGER':
2175 2175
 				case 'SMALLER':
2176
-					if (strlen(trim($_criterias['string'])) != strlen((float) trim($_criterias['string'])))
2176
+					if (strlen(trim($_criterias['string'])) != strlen((float)trim($_criterias['string'])))
2177 2177
 					{
2178 2178
 						//examine string to evaluate size
2179
-						$unit = strtoupper(trim(substr(trim($_criterias['string']),strlen((float) trim($_criterias['string'])))));
2180
-						$multipleBy = array('KB'=>1024,'K'=>1024,
2181
-											'MB'=>1024*1000,'M'=>1024*1000,
2182
-											'GB'=>1024*1000*1000,'G'=>1024*1000*1000,
2183
-											'TB'=>1024*1000*1000*1000,'T'=>1024*1000*1000*1000);
2184
-						$numberinBytes=(float)$_criterias['string'];
2185
-						if (isset($multipleBy[$unit])) $numberinBytes=(float)$_criterias['string']*$multipleBy[$unit];
2179
+						$unit = strtoupper(trim(substr(trim($_criterias['string']), strlen((float)trim($_criterias['string'])))));
2180
+						$multipleBy = array('KB'=>1024, 'K'=>1024,
2181
+											'MB'=>1024 * 1000, 'M'=>1024 * 1000,
2182
+											'GB'=>1024 * 1000 * 1000, 'G'=>1024 * 1000 * 1000,
2183
+											'TB'=>1024 * 1000 * 1000 * 1000, 'T'=>1024 * 1000 * 1000 * 1000);
2184
+						$numberinBytes = (float)$_criterias['string'];
2185
+						if (isset($multipleBy[$unit])) $numberinBytes = (float)$_criterias['string'] * $multipleBy[$unit];
2186 2186
 						//error_log(__METHOD__.__LINE__.'#'.$_criterias['string'].'->'.(float)$_criterias['string'].'#'.$unit.' ='.$numberinBytes);
2187
-						$_criterias['string']=$numberinBytes;
2187
+						$_criterias['string'] = $numberinBytes;
2188 2188
 					}
2189
-					$imapSearchFilter->size( $_criterias['string'], ($criteria=='LARGER'?true:false), $not=false);
2189
+					$imapSearchFilter->size($_criterias['string'], ($criteria == 'LARGER' ? true : false), $not = false);
2190 2190
 					//$imapSearchFilter->charset('UTF-8');
2191 2191
 					$queryValid = true;
2192 2192
 					break;
@@ -2195,31 +2195,31 @@  discard block
 block discarded – undo
2195 2195
 				case 'CC':
2196 2196
 				case 'BCC':
2197 2197
 				case 'SUBJECT':
2198
-					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not=false);
2198
+					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not = false);
2199 2199
 					//$imapSearchFilter->charset('UTF-8');
2200 2200
 					$queryValid = true;
2201 2201
 					break;
2202 2202
 				case 'BODY':
2203 2203
 				case 'TEXT':
2204
-					$imapSearchFilter->text($_criterias['string'],($criteria=='BODY'?true:false), $not=false);
2204
+					$imapSearchFilter->text($_criterias['string'], ($criteria == 'BODY' ? true : false), $not = false);
2205 2205
 					//$imapSearchFilter->charset('UTF-8');
2206 2206
 					$queryValid = true;
2207 2207
 					break;
2208 2208
 				case 'SINCE':
2209
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2209
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2210 2210
 					$queryValid = true;
2211 2211
 					break;
2212 2212
 				case 'BEFORE':
2213
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2213
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2214 2214
 					$queryValid = true;
2215 2215
 					break;
2216 2216
 				case 'ON':
2217
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2217
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2218 2218
 					$queryValid = true;
2219 2219
 					break;
2220 2220
 			}
2221 2221
 		}
2222
-		if ($statusQueryValid && !$queryValid) $queryValid=true;
2222
+		if ($statusQueryValid && !$queryValid) $queryValid = true;
2223 2223
 		if ($queryValid) $imapFilter->andSearch($imapSearchFilter);
2224 2224
 
2225 2225
 		if (isset($_criterias['range']) && !empty($_criterias['range']))
@@ -2228,12 +2228,12 @@  discard block
 block discarded – undo
2228 2228
 			$imapRangeFilter = new Horde_Imap_Client_Search_Query();
2229 2229
 			$imapRangeFilter->charset('UTF-8');
2230 2230
 			$criteria = strtoupper($_criterias['range']);
2231
-			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since']==$_criterias['before'])
2231
+			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since'] == $_criterias['before'])
2232 2232
 			{
2233
-				$_criterias['date']=$_criterias['since'];
2233
+				$_criterias['date'] = $_criterias['since'];
2234 2234
 				unset($_criterias['since']);
2235 2235
 				unset($_criterias['before']);
2236
-				$criteria=$_criterias['range']='ON';
2236
+				$criteria = $_criterias['range'] = 'ON';
2237 2237
 			}
2238 2238
 			switch ($criteria) {
2239 2239
 				case 'BETWEEN':
@@ -2241,7 +2241,7 @@  discard block
 block discarded – undo
2241 2241
 					//enddate
2242 2242
 					if ($_criterias['since'])
2243 2243
 					{
2244
-						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2244
+						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2245 2245
 						$rangeValid = true;
2246 2246
 					}
2247 2247
 					//startdate
@@ -2250,28 +2250,28 @@  discard block
 block discarded – undo
2250 2250
 						$imapRangeFilter2 = new Horde_Imap_Client_Search_Query();
2251 2251
 						$imapRangeFilter2->charset('UTF-8');
2252 2252
 						//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2253
-						$_criterias['before'] = date("d-M-Y",DateTime::to($_criterias['before'],'ts')+(3600*24));
2254
-						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2253
+						$_criterias['before'] = date("d-M-Y", DateTime::to($_criterias['before'], 'ts') + (3600 * 24));
2254
+						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2255 2255
 						$imapRangeFilter->andSearch($imapRangeFilter2);
2256 2256
 						$rangeValid = true;
2257 2257
 					}
2258 2258
 					break;
2259 2259
 				case 'SINCE'://enddate
2260
-					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since']?$_criterias['since']:$_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2260
+					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since'] ? $_criterias['since'] : $_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2261 2261
 					$rangeValid = true;
2262 2262
 					break;
2263 2263
 				case 'BEFORE'://startdate
2264 2264
 					//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2265
-					$_criterias['before'] = date("d-M-Y",DateTime::to(($_criterias['before']?$_criterias['before']:$_criterias['date']),'ts')+(3600*24));
2266
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2265
+					$_criterias['before'] = date("d-M-Y", DateTime::to(($_criterias['before'] ? $_criterias['before'] : $_criterias['date']), 'ts') + (3600 * 24));
2266
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2267 2267
 					$rangeValid = true;
2268 2268
 					break;
2269 2269
 				case 'ON':
2270
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2270
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2271 2271
 					$rangeValid = true;
2272 2272
 					break;
2273 2273
 			}
2274
-			if ($rangeValid && !$queryValid) $queryValid=true;
2274
+			if ($rangeValid && !$queryValid) $queryValid = true;
2275 2275
 			if ($rangeValid) $imapFilter->andSearch($imapRangeFilter);
2276 2276
 		}
2277 2277
 		if (self::$debug)
@@ -2280,8 +2280,8 @@  discard block
 block discarded – undo
2280 2280
 			$query_str = $imapFilter->build();
2281 2281
 			//error_log(__METHOD__.' ('.__LINE__.') '.' '.$query_str['query'].' created by Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2282 2282
 		}
2283
-		if($queryValid==false) {
2284
-			$imapFilter->flag('DELETED', $set=false);
2283
+		if ($queryValid == false) {
2284
+			$imapFilter->flag('DELETED', $set = false);
2285 2285
 			return $imapFilter;
2286 2286
 		} else {
2287 2287
 			return $imapFilter;
@@ -2295,11 +2295,11 @@  discard block
 block discarded – undo
2295 2295
 	 * @param  mixed/boolean $_tryIDNConversion (true/false AND FORCE): try IDN Conversion on domainparts of emailADRESSES
2296 2296
 	 * @return mixed - based on the input type
2297 2297
 	 */
2298
-	static function decode_header($_string, $_tryIDNConversion=false)
2298
+	static function decode_header($_string, $_tryIDNConversion = false)
2299 2299
 	{
2300 2300
 		if (is_array($_string))
2301 2301
 		{
2302
-			foreach($_string as $k=>$v)
2302
+			foreach ($_string as $k=>$v)
2303 2303
 			{
2304 2304
 				$_string[$k] = self::decode_header($v, $_tryIDNConversion);
2305 2305
 			}
@@ -2307,18 +2307,18 @@  discard block
 block discarded – undo
2307 2307
 		}
2308 2308
 		else
2309 2309
 		{
2310
-			$_string = Mail\Html::decodeMailHeader($_string,self::$displayCharset);
2310
+			$_string = Mail\Html::decodeMailHeader($_string, self::$displayCharset);
2311 2311
 			$test = @json_encode($_string);
2312 2312
 			//error_log(__METHOD__.__LINE__.' ->'.strlen($singleBodyPart['body']).' Error:'.json_last_error().'<- BodyPart:#'.$test.'#');
2313
-			if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2313
+			if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2314 2314
 			{
2315 2315
 				// try to fix broken utf8
2316 2316
 				$x = utf8_encode($_string);
2317 2317
 				$test = @json_encode($x);
2318
-				if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2318
+				if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2319 2319
 				{
2320 2320
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
2321
-					$_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));
2321
+					$_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));
2322 2322
 				}
2323 2323
 				else
2324 2324
 				{
@@ -2326,7 +2326,7 @@  discard block
 block discarded – undo
2326 2326
 				}
2327 2327
 			}
2328 2328
 
2329
-			if ($_tryIDNConversion===true && stripos($_string,'@')!==false)
2329
+			if ($_tryIDNConversion === true && stripos($_string, '@') !== false)
2330 2330
 			{
2331 2331
 				$rfcAddr = self::parseAddressList($_string);
2332 2332
 				$stringA = array();
@@ -2338,11 +2338,11 @@  discard block
 block discarded – undo
2338 2338
 						$stringA = array();
2339 2339
 						break; // skip idna conversion if we encounter an error here
2340 2340
 					}
2341
-					$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox,Horde_Idna::decode($_rfcAddr->host),$_rfcAddr->personal);
2341
+					$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox, Horde_Idna::decode($_rfcAddr->host), $_rfcAddr->personal);
2342 2342
 				}
2343
-				if (!empty($stringA)) $_string = implode(',',$stringA);
2343
+				if (!empty($stringA)) $_string = implode(',', $stringA);
2344 2344
 			}
2345
-			if ($_tryIDNConversion==='FORCE')
2345
+			if ($_tryIDNConversion === 'FORCE')
2346 2346
 			{
2347 2347
 				//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_string.'='.Horde_Idna::decode($_string));
2348 2348
 				$_string = Horde_Idna::decode($_string);
@@ -2358,17 +2358,17 @@  discard block
 block discarded – undo
2358 2358
 	 * @param  boolean $decode try decoding
2359 2359
 	 * @return mixed - based on the input type
2360 2360
 	 */
2361
-	function decode_subject($_string,$decode=true)
2361
+	function decode_subject($_string, $decode = true)
2362 2362
 	{
2363 2363
 		#$string = $_string;
2364
-		if($_string=='NIL')
2364
+		if ($_string == 'NIL')
2365 2365
 		{
2366 2366
 			return 'No Subject';
2367 2367
 		}
2368 2368
 		if ($decode) $_string = self::decode_header($_string);
2369 2369
 		// make sure its utf-8
2370 2370
 		$test = @json_encode($_string);
2371
-		if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2371
+		if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2372 2372
 		{
2373 2373
 			$_string = utf8_encode($_string);
2374 2374
 		}
@@ -2420,18 +2420,18 @@  discard block
 block discarded – undo
2420 2420
 	function createFolder($_parent, $_folderName, &$_error)
2421 2421
 	{
2422 2422
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."->"."$_parent, $_folderName called from:".function_backtrace());
2423
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2424
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2423
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2424
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2425 2425
 
2426
-		if(empty($parent)) {
2426
+		if (empty($parent)) {
2427 2427
 			$newFolderName = $folderName;
2428 2428
 		} else {
2429 2429
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2430
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2430
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2431 2431
 		}
2432 2432
 		if (empty($newFolderName)) return false;
2433 2433
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.'->'.$newFolderName);
2434
-		if ($this->folderExists($newFolderName,true))
2434
+		if ($this->folderExists($newFolderName, true))
2435 2435
 		{
2436 2436
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." Folder $newFolderName already exists.");
2437 2437
 			return $newFolderName;
@@ -2448,7 +2448,7 @@  discard block
 block discarded – undo
2448 2448
 		}
2449 2449
 		catch (\Exception $e)
2450 2450
 		{
2451
-			$_error = lang('Could not create Folder %1 Reason: %2',$newFolderName,$e->getMessage());
2451
+			$_error = lang('Could not create Folder %1 Reason: %2', $newFolderName, $e->getMessage());
2452 2452
 			error_log(__METHOD__.' ('.__LINE__.') '.' create Folder '.$newFolderName.'->'.$e->getMessage().' ('.$e->details.') Namespace:'.array2string($this->icServer->getNameSpaces()).function_backtrace());
2453 2453
 			return false;
2454 2454
 		}
@@ -2477,15 +2477,15 @@  discard block
 block discarded – undo
2477 2477
 	 */
2478 2478
 	function renameFolder($_oldFolderName, $_parent, $_folderName)
2479 2479
 	{
2480
-		$oldFolderName	= $_oldFolderName;//$this->_encodeFolderName($_oldFolderName);
2481
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2482
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2480
+		$oldFolderName = $_oldFolderName; //$this->_encodeFolderName($_oldFolderName);
2481
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2482
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2483 2483
 
2484
-		if(empty($parent)) {
2484
+		if (empty($parent)) {
2485 2485
 			$newFolderName = $folderName;
2486 2486
 		} else {
2487 2487
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2488
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2488
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2489 2489
 		}
2490 2490
 		if (self::$debug) error_log("create folder: $newFolderName");
2491 2491
 		try
@@ -2494,10 +2494,10 @@  discard block
 block discarded – undo
2494 2494
 		}
2495 2495
 		catch (\Exception $e)
2496 2496
 		{
2497
-			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage());;
2497
+			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage()); ;
2498 2498
 		}
2499 2499
 		// clear FolderExistsInfoCache
2500
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2500
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2501 2501
 
2502 2502
 		return $newFolderName;
2503 2503
 
@@ -2516,15 +2516,15 @@  discard block
 block discarded – undo
2516 2516
 		//$folderName = $this->_encodeFolderName($_folderName);
2517 2517
 		try
2518 2518
 		{
2519
-			$this->icServer->subscribeMailbox($_folderName,false);
2519
+			$this->icServer->subscribeMailbox($_folderName, false);
2520 2520
 			$this->icServer->deleteMailbox($_folderName);
2521 2521
 		}
2522 2522
 		catch (\Exception $e)
2523 2523
 		{
2524
-			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage());;
2524
+			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage()); ;
2525 2525
 		}
2526 2526
 		// clear FolderExistsInfoCache
2527
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2527
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2528 2528
 
2529 2529
 		return true;
2530 2530
 	}
@@ -2559,10 +2559,10 @@  discard block
 block discarded – undo
2559 2559
 	 *
2560 2560
 	 * @return array with folder objects. eg.: INBOX => {inbox object}
2561 2561
 	 */
2562
-	function getFolderObjects($_subscribedOnly=false, $_getCounters=false, $_alwaysGetDefaultFolders=false,$_useCacheIfPossible=true)
2562
+	function getFolderObjects($_subscribedOnly = false, $_getCounters = false, $_alwaysGetDefaultFolders = false, $_useCacheIfPossible = true)
2563 2563
 	{
2564 2564
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' ServerID:'.$this->icServer->ImapServerId.", subscribedOnly:$_subscribedOnly, getCounters:$_getCounters, alwaysGetDefaultFolders:$_alwaysGetDefaultFolders, _useCacheIfPossible:$_useCacheIfPossible");
2565
-		if (self::$debugTimes) $starttime = microtime (true);
2565
+		if (self::$debugTimes) $starttime = microtime(true);
2566 2566
 		static $folders2return;
2567 2567
 		//$_subscribedOnly=false;
2568 2568
 		// always use static on single request if info is available;
@@ -2570,42 +2570,42 @@  discard block
 block discarded – undo
2570 2570
 		// set $_useCacheIfPossible to false !
2571 2571
 		if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2572 2572
 		{
2573
-			if (self::$debugTimes) self::logRunTimes($starttime,null,'using static',__METHOD__.' ('.__LINE__.') ');
2573
+			if (self::$debugTimes) self::logRunTimes($starttime, null, 'using static', __METHOD__.' ('.__LINE__.') ');
2574 2574
 			return $folders2return[$this->icServer->ImapServerId];
2575 2575
 		}
2576 2576
 
2577
-		if ($_subscribedOnly && $_getCounters===false)
2577
+		if ($_subscribedOnly && $_getCounters === false)
2578 2578
 		{
2579
-			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2579
+			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
2580 2580
 			if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2581 2581
 			{
2582 2582
 				//error_log(__METHOD__.' ('.__LINE__.') '.' using Cached folderObjects'.array2string($folders2return[$this->icServer->ImapServerId]));
2583
-				if (self::$debugTimes) self::logRunTimes($starttime,null,'from Cache',__METHOD__.' ('.__LINE__.') ');
2583
+				if (self::$debugTimes) self::logRunTimes($starttime, null, 'from Cache', __METHOD__.' ('.__LINE__.') ');
2584 2584
 				return $folders2return[$this->icServer->ImapServerId];
2585 2585
 			}
2586 2586
 		}
2587 2587
 		// use $folderBasicInfo for holding attributes and other basic folderinfo $folderBasicInfo[$this->icServer->ImapServerId]
2588 2588
 		static $folderBasicInfo;
2589
-		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);
2589
+		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);
2590 2590
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($folderBasicInfo[$this->icServer->ImapServerId])));
2591 2591
 
2592 2592
 		$delimiter = $this->getHierarchyDelimiter();
2593 2593
 
2594 2594
 		$inboxData = new \stdClass;
2595
-		$inboxData->name 		= 'INBOX';
2595
+		$inboxData->name = 'INBOX';
2596 2596
 		$inboxData->folderName		= 'INBOX';
2597
-		$inboxData->displayName		= lang('INBOX');
2597
+		$inboxData->displayName = lang('INBOX');
2598 2598
 		$inboxData->delimiter 		= $delimiter;
2599
-		$inboxData->shortFolderName	= 'INBOX';
2600
-		$inboxData->shortDisplayName	= lang('INBOX');
2599
+		$inboxData->shortFolderName = 'INBOX';
2600
+		$inboxData->shortDisplayName = lang('INBOX');
2601 2601
 		$inboxData->subscribed = true;
2602
-		if($_getCounters == true) {
2602
+		if ($_getCounters == true) {
2603 2603
 			$inboxData->counter = $this->getMailBoxCounters('INBOX');
2604 2604
 		}
2605 2605
 		// force unsubscribed by preference showAllFoldersInFolderPane
2606 2606
 		if ($_subscribedOnly == true &&
2607 2607
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2608
-			$this->mailPreferences['showAllFoldersInFolderPane']==1)
2608
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1)
2609 2609
 		{
2610 2610
 			$_subscribedOnly = false;
2611 2611
 		}
@@ -2618,12 +2618,12 @@  discard block
 block discarded – undo
2618 2618
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2619 2619
 		if (is_array($nameSpace))
2620 2620
 		{
2621
-			foreach($nameSpace as $k => $singleNameSpace) {
2621
+			foreach ($nameSpace as $k => $singleNameSpace) {
2622 2622
 				$type = $singleNameSpace['type'];
2623 2623
 				// the following line (assumption that for the same namespace the delimiter should be equal) may be wrong
2624
-				$foldersNameSpace[$type]['delimiter']  = $singleNameSpace['delimiter'];
2624
+				$foldersNameSpace[$type]['delimiter'] = $singleNameSpace['delimiter'];
2625 2625
 
2626
-				if(is_array($singleNameSpace)&&$fetchedAllInOneGo==false) {
2626
+				if (is_array($singleNameSpace) && $fetchedAllInOneGo == false) {
2627 2627
 					// fetch and sort the subscribed folders
2628 2628
 					// we alway fetch the subscribed, as this provides the only way to tell
2629 2629
 					// if a folder is subscribed or not
@@ -2631,22 +2631,22 @@  discard block
 block discarded – undo
2631 2631
 					{
2632 2632
 						try
2633 2633
 						{
2634
-							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('',0,true);
2634
+							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('', 0, true);
2635 2635
 							if (!empty($subscribedMailboxes))
2636 2636
 							{
2637 2637
 								$fetchedAllInOneGo = true;
2638 2638
 							}
2639 2639
 							else
2640 2640
 							{
2641
-								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'],0,true);
2641
+								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'], 0, true);
2642 2642
 							}
2643 2643
 						}
2644
-						catch(Exception $e)
2644
+						catch (Exception $e)
2645 2645
 						{
2646 2646
 							continue;
2647 2647
 						}
2648 2648
 						//echo "subscribedMailboxes";_debug_array($subscribedMailboxes);
2649
-						$subscribedFoldersPerNS = (!empty($subscribedMailboxes)?array_keys($subscribedMailboxes):array());
2649
+						$subscribedFoldersPerNS = (!empty($subscribedMailboxes) ? array_keys($subscribedMailboxes) : array());
2650 2650
 						//if (is_array($foldersNameSpace[$type]['subscribed'])) sort($foldersNameSpace[$type]['subscribed']);
2651 2651
 						//_debug_array($foldersNameSpace);
2652 2652
 						//error_log(__METHOD__.__LINE__.array2string($singleNameSpace).':#:'.array2string($subscribedFoldersPerNS));
@@ -2656,18 +2656,18 @@  discard block
 block discarded – undo
2656 2656
 							foreach ($subscribedMailboxes as $k => $finfo)
2657 2657
 							{
2658 2658
 								//error_log(__METHOD__.__LINE__.$k.':#:'.array2string($finfo));
2659
-								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k]=
2660
-								$folderBasicInfo[$this->icServer->ImapServerId][$k]=array(
2659
+								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k] =
2660
+								$folderBasicInfo[$this->icServer->ImapServerId][$k] = array(
2661 2661
 									'MAILBOX'=>$finfo['MAILBOX'],
2662 2662
 									'ATTRIBUTES'=>$finfo['ATTRIBUTES'],
2663
-									'delimiter'=>$finfo['delimiter'],//lowercase for some reason???
2664
-									'SUBSCRIBED'=>$finfo['SUBSCRIBED'],//seeded by getMailboxes
2663
+									'delimiter'=>$finfo['delimiter'], //lowercase for some reason???
2664
+									'SUBSCRIBED'=>$finfo['SUBSCRIBED'], //seeded by getMailboxes
2665 2665
 								);
2666
-								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k,$foldersNameSpace[$type]['subscribed']))
2666
+								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k, $foldersNameSpace[$type]['subscribed']))
2667 2667
 								{
2668 2668
 									$foldersNameSpace[$type]['subscribed'][] = $k;
2669 2669
 								}
2670
-								if (empty($foldersNameSpace[$type]['all']) || !in_array($k,$foldersNameSpace[$type]['all']))
2670
+								if (empty($foldersNameSpace[$type]['all']) || !in_array($k, $foldersNameSpace[$type]['all']))
2671 2671
 								{
2672 2672
 									$foldersNameSpace[$type]['all'][] = $k;
2673 2673
 								}
@@ -2690,7 +2690,7 @@  discard block
 block discarded – undo
2690 2690
 						// that may produce problems, when encountering recursions probably
2691 2691
 						// horde is handling that, so we do not; keep that in mind!
2692 2692
 						//$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],2,true);
2693
-						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],0,true);
2693
+						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'], 0, true);
2694 2694
 					}
2695 2695
 					catch (\Exception $e)
2696 2696
 					{
@@ -2708,26 +2708,26 @@  discard block
 block discarded – undo
2708 2708
 					foreach ($allMailboxesExt as $mbx) {
2709 2709
 						if (!isset($folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2710 2710
 						{
2711
-							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]=array(
2711
+							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']] = array(
2712 2712
 								'MAILBOX'=>$mbx['MAILBOX'],
2713 2713
 								'ATTRIBUTES'=>$mbx['ATTRIBUTES'],
2714
-								'delimiter'=>$mbx['delimiter'],//lowercase for some reason???
2715
-								'SUBSCRIBED'=>$mbx['SUBSCRIBED'],//seeded by getMailboxes
2714
+								'delimiter'=>$mbx['delimiter'], //lowercase for some reason???
2715
+								'SUBSCRIBED'=>$mbx['SUBSCRIBED'], //seeded by getMailboxes
2716 2716
 							);
2717 2717
 							if ($mbx['SUBSCRIBED'] && !isset($subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2718 2718
 							{
2719 2719
 								$subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']] = $folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']];
2720 2720
 							}
2721 2721
 						}
2722
-						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'],$foldersNameSpace[$type]['subscribed'])))
2722
+						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'], $foldersNameSpace[$type]['subscribed'])))
2723 2723
 						{
2724 2724
 							$foldersNameSpace[$type]['subscribed'][] = $mbx['MAILBOX'];
2725 2725
 						}
2726 2726
 						//echo __METHOD__;_debug_array($mbx);
2727 2727
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
2728
-						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']])||
2729
-							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']])||
2730
-							(substr($mbx['MAILBOX'],-1)==$foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'],0,-1)]))
2728
+						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']]) ||
2729
+							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']]) ||
2730
+							(substr($mbx['MAILBOX'], -1) == $foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'], 0, -1)]))
2731 2731
 						) continue;
2732 2732
 
2733 2733
 						//echo '#'.$mbx['MAILBOX'].':'.array2string($mbx)."#<br>";
@@ -2737,7 +2737,7 @@  discard block
 block discarded – undo
2737 2737
 					//_debug_array(array_keys($allMailBoxesExtSorted));
2738 2738
 					$allMailboxes = array();
2739 2739
 					foreach ((array)$allMailBoxesExtSorted as $mbx) {
2740
-						if (!in_array($mbx['MAILBOX'],$allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2740
+						if (!in_array($mbx['MAILBOX'], $allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2741 2741
 						//echo "Result:";_debug_array($allMailboxes);
2742 2742
 					}
2743 2743
 					$foldersNameSpace[$type]['all'] = $allMailboxes;
@@ -2746,57 +2746,57 @@  discard block
 block discarded – undo
2746 2746
 			}
2747 2747
 		}
2748 2748
 		//subscribed folders may be used in getFolderStatus
2749
-		Cache::setCache(Cache::INSTANCE,'email','subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$subscribedFoldersForCache,$expiration=60*60*1);
2749
+		Cache::setCache(Cache::INSTANCE, 'email', 'subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $subscribedFoldersForCache, $expiration = 60 * 60 * 1);
2750 2750
 		//echo "<br>FolderNameSpace To Process:";_debug_array($foldersNameSpace);
2751 2751
 		$autoFolderObjects = $folders = array();
2752 2752
 		$autofolder_exists = array();
2753
-		foreach( array('personal', 'others', 'shared') as $type) {
2754
-			if(isset($foldersNameSpace[$type])) {
2755
-				if($_subscribedOnly) {
2756
-					if( !empty($foldersNameSpace[$type]['subscribed']) ) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2753
+		foreach (array('personal', 'others', 'shared') as $type) {
2754
+			if (isset($foldersNameSpace[$type])) {
2755
+				if ($_subscribedOnly) {
2756
+					if (!empty($foldersNameSpace[$type]['subscribed'])) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2757 2757
 				} else {
2758
-					if( !empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2758
+					if (!empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2759 2759
 				}
2760
-				foreach((array)$listOfFolders as $folderName) {
2760
+				foreach ((array)$listOfFolders as $folderName) {
2761 2761
 					//echo "<br>FolderToCheck:$folderName<br>";
2762 2762
 					//error_log(__METHOD__.__LINE__.'#Delimiter:'.$delimiter.':#'.$folderName);
2763
-					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue;//when subscribedonly, we fetch all folders in one go.
2764
-					if($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all'])||in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2763
+					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue; //when subscribedonly, we fetch all folders in one go.
2764
+					if ($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all']) || in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2765 2765
 						#echo "$folderName failed to be here <br>";
2766 2766
 						continue;
2767 2767
 					}
2768 2768
 					if (isset($folders[$folderName])) continue;
2769 2769
 					if (isset($autoFolderObjects[$folderName])) continue;
2770
-					if (empty($delimiter)||$delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2770
+					if (empty($delimiter) || $delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2771 2771
 					$folderParts = explode($delimiter, $folderName);
2772 2772
 					$shortName = array_pop($folderParts);
2773 2773
 
2774 2774
 					$folderObject = new \stdClass;
2775
-					$folderObject->delimiter	= $delimiter;
2776
-					$folderObject->folderName	= $folderName;
2777
-					$folderObject->shortFolderName	= $shortName;
2778
-					if(!$_subscribedOnly) {
2775
+					$folderObject->delimiter = $delimiter;
2776
+					$folderObject->folderName = $folderName;
2777
+					$folderObject->shortFolderName = $shortName;
2778
+					if (!$_subscribedOnly) {
2779 2779
 						#echo $folderName."->".$type."<br>";
2780 2780
 						#_debug_array($foldersNameSpace[$type]['subscribed']);
2781 2781
 						$folderObject->subscribed = in_array($folderName, (array)$foldersNameSpace[$type]['subscribed']);
2782 2782
 					}
2783 2783
 
2784
-					if($_getCounters == true) {
2784
+					if ($_getCounters == true) {
2785 2785
 						//error_log(__METHOD__.' ('.__LINE__.') '.' getCounter forFolder:'.$folderName);
2786 2786
 						$folderObject->counter = $this->getMailBoxCounters($folderName);
2787 2787
 					}
2788
-					if(strtoupper($folderName) == 'INBOX') {
2788
+					if (strtoupper($folderName) == 'INBOX') {
2789 2789
 						$folderName = 'INBOX';
2790
-						$folderObject->folderName	= 'INBOX';
2791
-						$folderObject->shortFolderName	= 'INBOX';
2792
-						$folderObject->displayName	= lang('INBOX');
2790
+						$folderObject->folderName = 'INBOX';
2791
+						$folderObject->shortFolderName = 'INBOX';
2792
+						$folderObject->displayName = lang('INBOX');
2793 2793
 						$folderObject->shortDisplayName = lang('INBOX');
2794
-						$folderObject->subscribed	= true;
2794
+						$folderObject->subscribed = true;
2795 2795
 					// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
2796
-					} elseif (in_array($shortName,self::$autoFolders)) {
2797
-						$tmpfolderparts = explode($delimiter,$folderObject->folderName);
2796
+					} elseif (in_array($shortName, self::$autoFolders)) {
2797
+						$tmpfolderparts = explode($delimiter, $folderObject->folderName);
2798 2798
 						array_pop($tmpfolderparts);
2799
-						$folderObject->displayName = implode($delimiter,$tmpfolderparts).$delimiter.lang($shortName);
2799
+						$folderObject->displayName = implode($delimiter, $tmpfolderparts).$delimiter.lang($shortName);
2800 2800
 						$folderObject->shortDisplayName = lang($shortName);
2801 2801
 						unset($tmpfolderparts);
2802 2802
 					} else {
@@ -2804,13 +2804,13 @@  discard block
 block discarded – undo
2804 2804
 						$folderObject->shortDisplayName = $shortName;
2805 2805
 					}
2806 2806
 					//$folderName = $folderName;
2807
-					if (in_array($shortName,self::$autoFolders)&&self::searchValueInFolderObjects($shortName,$autoFolderObjects)===false) {
2807
+					if (in_array($shortName, self::$autoFolders) && self::searchValueInFolderObjects($shortName, $autoFolderObjects) === false) {
2808 2808
 						$autoFolderObjects[$folderName] = $folderObject;
2809 2809
 					} else {
2810 2810
 						$folders[$folderName] = $folderObject;
2811 2811
 					}
2812 2812
 					//error_log(__METHOD__.' ('.__LINE__.') '.':'.$folderObject->folderName);
2813
-					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders ();
2813
+					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders();
2814 2814
 					if (isset(self::$specialUseFolders[$folderName]))
2815 2815
 					{
2816 2816
 						$autofolder_exists[$folderName] = self::$specialUseFolders[$folderName];
@@ -2819,27 +2819,27 @@  discard block
 block discarded – undo
2819 2819
 			}
2820 2820
 		}
2821 2821
 		if (is_array($autoFolderObjects) && !empty($autoFolderObjects)) {
2822
-			uasort($autoFolderObjects,array($this,"sortByAutoFolderPos"));
2822
+			uasort($autoFolderObjects, array($this, "sortByAutoFolderPos"));
2823 2823
 		}
2824 2824
 		// check if some standard folders are missing and need to be created
2825 2825
 		if (count($autofolder_exists) < count(self::$autoFolders) && $this->check_create_autofolders($autofolder_exists))
2826 2826
 		{
2827 2827
 			// if new folders have been created, re-read folders ignoring the cache
2828
-			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false);	// false = do NOT use cache
2828
+			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false); // false = do NOT use cache
2829 2829
 		}
2830
-		if (is_array($folders)) uasort($folders,array($this,"sortByDisplayName"));
2830
+		if (is_array($folders)) uasort($folders, array($this, "sortByDisplayName"));
2831 2831
 		//$folders2return = array_merge($autoFolderObjects,$folders);
2832 2832
 		//_debug_array($folders2return); #exit;
2833
-		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject,(array)$autoFolderObjects,(array)$folders);
2834
-		if (($_subscribedOnly && $_getCounters===false) ||
2835
-			($_subscribedOnly == false && $_getCounters===false &&
2833
+		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject, (array)$autoFolderObjects, (array)$folders);
2834
+		if (($_subscribedOnly && $_getCounters === false) ||
2835
+			($_subscribedOnly == false && $_getCounters === false &&
2836 2836
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2837
-			$this->mailPreferences['showAllFoldersInFolderPane']==1))
2837
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1))
2838 2838
 		{
2839
-			Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),$folders2return,$expiration=60*60*1);
2839
+			Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), $folders2return, $expiration = 60 * 60 * 1);
2840 2840
 		}
2841
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderBasicInfo,$expiration=60*60*1);
2842
-		if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') ');
2841
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderBasicInfo, $expiration = 60 * 60 * 1);
2842
+		if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') ');
2843 2843
 		return $folders2return[$this->icServer->ImapServerId];
2844 2844
 	}
2845 2845
 
@@ -2860,21 +2860,21 @@  discard block
 block discarded – undo
2860 2860
 	 *
2861 2861
 	 * @return array arrays of folders
2862 2862
 	 */
2863
-	function getFolderArrays ($_nodePath = null, $_onlyTopLevel = false, $_search= 2, $_subscribedOnly = false, $_getCounter = false)
2863
+	function getFolderArrays($_nodePath = null, $_onlyTopLevel = false, $_search = 2, $_subscribedOnly = false, $_getCounter = false)
2864 2864
 	{
2865 2865
 		// delimiter
2866 2866
 		$delimiter = $this->getHierarchyDelimiter();
2867 2867
 
2868
-		$folders = $nameSpace =  array();
2868
+		$folders = $nameSpace = array();
2869 2869
 		$nameSpaceTmp = $this->_getNameSpaces();
2870
-		foreach($nameSpaceTmp as $k => $singleNameSpace) {
2871
-			$nameSpace[$singleNameSpace['type']]=$singleNameSpace;
2870
+		foreach ($nameSpaceTmp as $k => $singleNameSpace) {
2871
+			$nameSpace[$singleNameSpace['type']] = $singleNameSpace;
2872 2872
 		}
2873 2873
 		unset($nameSpaceTmp);
2874 2874
 
2875 2875
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2876 2876
 		// Get special use folders
2877
-		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders (); // Set self::$specialUseFolders
2877
+		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders(); // Set self::$specialUseFolders
2878 2878
 		// topLevelQueries generally ignore the $_search param. Except for Config::examineNamespace
2879 2879
 		if ($_onlyTopLevel) // top level leaves
2880 2880
 		{
@@ -2885,20 +2885,20 @@  discard block
 block discarded – undo
2885 2885
 			if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
2886 2886
 			if (self::$mailConfig['examineNamespace'])
2887 2887
 			{
2888
-				$prefixes=array();
2888
+				$prefixes = array();
2889 2889
 				if (is_array($nameSpace))
2890 2890
 				{
2891
-					foreach($nameSpace as $k => $singleNameSpace) {
2891
+					foreach ($nameSpace as $k => $singleNameSpace) {
2892 2892
 						$type = $singleNameSpace['type'];
2893 2893
 
2894
-						if(is_array($singleNameSpace) && $singleNameSpace['prefix']){
2894
+						if (is_array($singleNameSpace) && $singleNameSpace['prefix']) {
2895 2895
 							$prefixes[$type] = $singleNameSpace['prefix'];
2896 2896
 							//regard extra care for nameSpacequeries when configured AND respect $_search
2897
-							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search==0?0:2, true);
2897
+							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search == 0 ? 0 : 2, true);
2898 2898
 							if (is_array($result))
2899 2899
 							{
2900 2900
 								ksort($result);
2901
-								$topFolders = array_merge($topFolders,$result);
2901
+								$topFolders = array_merge($topFolders, $result);
2902 2902
 							}
2903 2903
 						}
2904 2904
 					}
@@ -2907,7 +2907,7 @@  discard block
 block discarded – undo
2907 2907
 
2908 2908
 			$autofolders = array();
2909 2909
 
2910
-			foreach(self::$specialUseFolders as $path => $folder)
2910
+			foreach (self::$specialUseFolders as $path => $folder)
2911 2911
 			{
2912 2912
 				if ($this->folderExists($path))
2913 2913
 				{
@@ -2915,9 +2915,9 @@  discard block
 block discarded – undo
2915 2915
 				}
2916 2916
 			}
2917 2917
 			// Check if the special use folders are there, otherwise try to create them
2918
-			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders ($autofolders))
2918
+			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders($autofolders))
2919 2919
 			{
2920
-				return $this->getFolderArrays ($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2920
+				return $this->getFolderArrays($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2921 2921
 			}
2922 2922
 
2923 2923
 			// now process topFolders for next level
@@ -2925,13 +2925,13 @@  discard block
 block discarded – undo
2925 2925
 			{
2926 2926
 				$pattern = "/\\".$delimiter."/";
2927 2927
 				$reference = preg_replace($pattern, '', $node['MAILBOX']);
2928
-				if(!empty($prefixes))
2928
+				if (!empty($prefixes))
2929 2929
 				{
2930 2930
 					$reference = '';
2931
-					$tmpArray = explode($delimiter,$node['MAILBOX']);
2932
-					foreach($tmpArray as $p)
2931
+					$tmpArray = explode($delimiter, $node['MAILBOX']);
2932
+					foreach ($tmpArray as $p)
2933 2933
 					{
2934
-						$reference = empty($reference)?$p:$reference.$delimiter.$p;
2934
+						$reference = empty($reference) ? $p : $reference.$delimiter.$p;
2935 2935
 					}
2936 2936
 				}
2937 2937
 				$mainFolder = $subFolders = array();
@@ -2967,19 +2967,19 @@  discard block
 block discarded – undo
2967 2967
 							$nFolders [$path] = $folder;
2968 2968
 						}
2969 2969
 					}
2970
-					if (is_array($aFolders)) uasort ($aFolders, array($this,'sortByAutofolder'));
2970
+					if (is_array($aFolders)) uasort($aFolders, array($this, 'sortByAutofolder'));
2971 2971
 					//ksort($aFolders);
2972 2972
 
2973 2973
 					// Sort none auto folders base on mailbox name
2974
-					uasort($nFolders,array($this,'sortByMailbox'));
2974
+					uasort($nFolders, array($this, 'sortByMailbox'));
2975 2975
 
2976
-					$subFolders = array_merge($aFolders,$nFolders);
2976
+					$subFolders = array_merge($aFolders, $nFolders);
2977 2977
 				}
2978 2978
 				else
2979 2979
 				{
2980 2980
 					if (is_array($subFolders)) ksort($subFolders);
2981 2981
 				}
2982
-				$folders = array_merge($folders,(array)$mainFolder, (array)$subFolders);
2982
+				$folders = array_merge($folders, (array)$mainFolder, (array)$subFolders);
2983 2983
 			}
2984 2984
 		}
2985 2985
 		elseif ($_nodePath) // single node
@@ -3006,9 +3006,9 @@  discard block
 block discarded – undo
3006 3006
 				$folders = $this->icServer->getMailboxes($path, $_search, true);
3007 3007
 			}
3008 3008
 
3009
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
3009
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
3010 3010
 		}
3011
-		elseif(!$_nodePath) // all
3011
+		elseif (!$_nodePath) // all
3012 3012
 		{
3013 3013
 			if ($_subscribedOnly)
3014 3014
 			{
@@ -3024,101 +3024,101 @@  discard block
 block discarded – undo
3024 3024
 		{
3025 3025
 			// SORTING FOLDERS
3026 3026
 			//self::$debugTimes=true;
3027
-			if (self::$debugTimes) $starttime = microtime (true);
3027
+			if (self::$debugTimes) $starttime = microtime(true);
3028 3028
 			// Merge of all auto folders and specialusefolders
3029 3029
 			$autoFoldersTmp = array_unique((array_merge(self::$autoFolders, array_values(self::$specialUseFolders))));
3030
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
3030
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
3031 3031
 			$tmpFolders = $folders;
3032
-			$inboxFolderObject=$inboxSubFolderObjects=$autoFolderObjects=$typeFolderObject=$mySpecialUseFolders=array();
3033
-			$googleMailFolderObject=$googleAutoFolderObjects=$googleSubFolderObjects=array();
3034
-			$isGoogleMail=false;
3035
-			foreach($autoFoldersTmp as $afk=>$aF)
3032
+			$inboxFolderObject = $inboxSubFolderObjects = $autoFolderObjects = $typeFolderObject = $mySpecialUseFolders = array();
3033
+			$googleMailFolderObject = $googleAutoFolderObjects = $googleSubFolderObjects = array();
3034
+			$isGoogleMail = false;
3035
+			foreach ($autoFoldersTmp as $afk=>$aF)
3036 3036
 			{
3037
-				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF]=$this->getFolderByType($aF,false);
3037
+				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF] = $this->getFolderByType($aF, false);
3038 3038
 				//error_log($afk.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3039 3039
 			}
3040 3040
 			//error_log(array2string($mySpecialUseFolders));
3041 3041
 			foreach ($tmpFolders as $k => $f) {
3042
-				$sorted=false;
3043
-				if (strtoupper(substr($k,0,5))=='INBOX') {
3044
-					if (strtoupper($k)=='INBOX') {
3042
+				$sorted = false;
3043
+				if (strtoupper(substr($k, 0, 5)) == 'INBOX') {
3044
+					if (strtoupper($k) == 'INBOX') {
3045 3045
 						//error_log(__METHOD__.__LINE__.':'.strtoupper(substr($k,0,5)).':'.$k);
3046
-						$inboxFolderObject[$k]=$f;
3046
+						$inboxFolderObject[$k] = $f;
3047 3047
 						unset($folders[$k]);
3048
-						$sorted=true;
3048
+						$sorted = true;
3049 3049
 					} else {
3050
-						$isAutoFolder=false;
3051
-						foreach($autoFoldersTmp as $afk=>$aF)
3050
+						$isAutoFolder = false;
3051
+						foreach ($autoFoldersTmp as $afk=>$aF)
3052 3052
 						{
3053 3053
 							//error_log(__METHOD__.__LINE__.$k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3054
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3055
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3056
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3054
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3055
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3056
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3057 3057
 							{
3058 3058
 								//error_log(__METHOD__.__LINE__.$k.'->'.$mySpecialUseFolders[$aF]);
3059
-								$isAutoFolder=true;
3060
-								$autoFolderObjects[$k]=$f;
3059
+								$isAutoFolder = true;
3060
+								$autoFolderObjects[$k] = $f;
3061 3061
 								break;
3062 3062
 							}
3063 3063
 						}
3064
-						if ($isAutoFolder==false) $inboxSubFolderObjects[$k]=$f;
3064
+						if ($isAutoFolder == false) $inboxSubFolderObjects[$k] = $f;
3065 3065
 						unset($folders[$k]);
3066
-						$sorted=true;
3066
+						$sorted = true;
3067 3067
 					}
3068
-				} elseif (strtoupper(substr($k,0,13))=='[GOOGLE MAIL]') {
3069
-					$isGoogleMail=true;
3070
-					if (strtoupper($k)=='[GOOGLE MAIL]') {
3071
-						$googleMailFolderObject[$k]=$f;
3068
+				} elseif (strtoupper(substr($k, 0, 13)) == '[GOOGLE MAIL]') {
3069
+					$isGoogleMail = true;
3070
+					if (strtoupper($k) == '[GOOGLE MAIL]') {
3071
+						$googleMailFolderObject[$k] = $f;
3072 3072
 						unset($folders[$k]);
3073
-						$sorted=true;
3073
+						$sorted = true;
3074 3074
 					} else {
3075
-						$isAutoFolder=false;
3076
-						foreach($autoFoldersTmp as $afk=>$aF)
3075
+						$isAutoFolder = false;
3076
+						foreach ($autoFoldersTmp as $afk=>$aF)
3077 3077
 						{
3078 3078
 							//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3079
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3080
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3081
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3079
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3080
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3081
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3082 3082
 							{
3083 3083
 								//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3084
-								$isAutoFolder=true;
3085
-								$googleAutoFolderObjects[$k]=$f;
3084
+								$isAutoFolder = true;
3085
+								$googleAutoFolderObjects[$k] = $f;
3086 3086
 								break;
3087 3087
 							}
3088 3088
 						}
3089
-						if ($isAutoFolder==false) $googleSubFolderObjects[$k]=$f;
3089
+						if ($isAutoFolder == false) $googleSubFolderObjects[$k] = $f;
3090 3090
 						unset($folders[$k]);
3091
-						$sorted=true;
3091
+						$sorted = true;
3092 3092
 					}
3093 3093
 				} else {
3094
-					$isAutoFolder=false;
3095
-					foreach($autoFoldersTmp as $afk=>$aF)
3094
+					$isAutoFolder = false;
3095
+					foreach ($autoFoldersTmp as $afk=>$aF)
3096 3096
 					{
3097 3097
 						//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3098
-						if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3099
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3100
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3098
+						if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3099
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3100
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3101 3101
 						{
3102 3102
 							//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3103
-							$isAutoFolder=true;
3104
-							$autoFolderObjects[$k]=$f;
3103
+							$isAutoFolder = true;
3104
+							$autoFolderObjects[$k] = $f;
3105 3105
 							unset($folders[$k]);
3106
-							$sorted=true;
3106
+							$sorted = true;
3107 3107
 							break;
3108 3108
 						}
3109 3109
 					}
3110 3110
 				}
3111 3111
 
3112
-				if ($sorted==false)
3112
+				if ($sorted == false)
3113 3113
 				{
3114
-					foreach(array('others','shared') as $type)
3114
+					foreach (array('others', 'shared') as $type)
3115 3115
 					{
3116
-						if ($nameSpace[$type]['prefix_present']&&$nameSpace[$type]['prefix'])
3116
+						if ($nameSpace[$type]['prefix_present'] && $nameSpace[$type]['prefix'])
3117 3117
 						{
3118
-							if (substr($k,0,strlen($nameSpace[$type]['prefix']))==$nameSpace[$type]['prefix']||
3119
-								substr($k,0,strlen($nameSpace[$type]['prefix'])-strlen($nameSpace[$type]['delimiter']))==substr($nameSpace[$type]['prefix'],0,strlen($nameSpace[$type]['delimiter'])*-1)) {
3118
+							if (substr($k, 0, strlen($nameSpace[$type]['prefix'])) == $nameSpace[$type]['prefix'] ||
3119
+								substr($k, 0, strlen($nameSpace[$type]['prefix']) - strlen($nameSpace[$type]['delimiter'])) == substr($nameSpace[$type]['prefix'], 0, strlen($nameSpace[$type]['delimiter']) * -1)) {
3120 3120
 								//error_log(__METHOD__.__LINE__.':'.substr($k,0,strlen($nameSpace[$type]['prefix'])).':'.$k);
3121
-								$typeFolderObject[$type][$k]=$f;
3121
+								$typeFolderObject[$type][$k] = $f;
3122 3122
 								unset($folders[$k]);
3123 3123
 							}
3124 3124
 						}
@@ -3129,40 +3129,40 @@  discard block
 block discarded – undo
3129 3129
 			// avoid calling sortByAutoFolder as it is not regarding subfolders
3130 3130
 			$autoFolderObjectsTmp = $autoFolderObjects;
3131 3131
 			unset($autoFolderObjects);
3132
-			uasort($autoFolderObjectsTmp, array($this,'sortByMailbox'));
3133
-			foreach($autoFoldersTmp as $afk=>$aF)
3132
+			uasort($autoFolderObjectsTmp, array($this, 'sortByMailbox'));
3133
+			foreach ($autoFoldersTmp as $afk=>$aF)
3134 3134
 			{
3135
-				foreach($autoFolderObjectsTmp as $k => $f)
3135
+				foreach ($autoFolderObjectsTmp as $k => $f)
3136 3136
 				{
3137
-					if($aF && ($mySpecialUseFolders[$aF]==$k ||
3138
-						substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter ||
3139
-						stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false))
3137
+					if ($aF && ($mySpecialUseFolders[$aF] == $k ||
3138
+						substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter ||
3139
+						stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false))
3140 3140
 					{
3141
-						$autoFolderObjects[$k]=$f;
3141
+						$autoFolderObjects[$k] = $f;
3142 3142
 					}
3143 3143
 				}
3144 3144
 			}
3145 3145
 			//error_log(__METHOD__.__LINE__.array2string($autoFolderObjects));
3146 3146
 			if (!$isGoogleMail) {
3147
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$inboxSubFolderObjects,(array)$folders,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3147
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$inboxSubFolderObjects, (array)$folders, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3148 3148
 			} else {
3149 3149
 				// avoid calling sortByAutoFolder as it is not regarding subfolders
3150 3150
 				$gAutoFolderObjectsTmp = $googleAutoFolderObjects;
3151 3151
 				unset($googleAutoFolderObjects);
3152
-				uasort($gAutoFolderObjectsTmp, array($this,'sortByMailbox'));
3153
-				foreach($autoFoldersTmp as $afk=>$aF)
3152
+				uasort($gAutoFolderObjectsTmp, array($this, 'sortByMailbox'));
3153
+				foreach ($autoFoldersTmp as $afk=>$aF)
3154 3154
 				{
3155
-					foreach($gAutoFolderObjectsTmp as $k => $f)
3155
+					foreach ($gAutoFolderObjectsTmp as $k => $f)
3156 3156
 					{
3157
-						if($aF && ($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter))
3157
+						if ($aF && ($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter))
3158 3158
 						{
3159
-							$googleAutoFolderObjects[$k]=$f;
3159
+							$googleAutoFolderObjects[$k] = $f;
3160 3160
 						}
3161 3161
 					}
3162 3162
 				}
3163
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$folders,(array)$googleMailFolderObject,$googleAutoFolderObjects,$googleSubFolderObjects,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3163
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$folders, (array)$googleMailFolderObject, $googleAutoFolderObjects, $googleSubFolderObjects, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3164 3164
 			}
3165
-			if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') Sorting:');
3165
+			if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') Sorting:');
3166 3166
 			//self::$debugTimes=false;
3167 3167
 		}
3168 3168
 		// Get counter information and add them to each fetched folders array
@@ -3184,10 +3184,10 @@  discard block
 block discarded – undo
3184 3184
 	 * @param array $autofolders_exists existing folders, no need to check their existance again
3185 3185
 	 * @return int number of new folders created
3186 3186
 	 */
3187
-	function check_create_autofolders(array $autofolders_exists=array())
3187
+	function check_create_autofolders(array $autofolders_exists = array())
3188 3188
 	{
3189 3189
 		$num_created = 0;
3190
-		foreach(self::$autoFolders as $folder)
3190
+		foreach (self::$autoFolders as $folder)
3191 3191
 		{
3192 3192
 			$created = false;
3193 3193
 			if (!in_array($folder, $autofolders_exists) && $this->_getSpecialUseFolder($folder, true, $created) &&
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
 		$rv = false;
3213 3213
 		foreach ($haystack as $k => $v)
3214 3214
 		{
3215
-			foreach($v as &$sv) {if (trim($sv)==trim($needle)) return $k;}
3215
+			foreach ($v as &$sv) {if (trim($sv) == trim($needle)) return $k; }
3216 3216
 		}
3217 3217
 		return $rv;
3218 3218
 	}
@@ -3225,9 +3225,9 @@  discard block
 block discarded – undo
3225 3225
 	 * @param array $b array of folders
3226 3226
 	 * @return int expect values (0, 1 or -1)
3227 3227
 	 */
3228
-	function sortByMailbox($a,$b)
3228
+	function sortByMailbox($a, $b)
3229 3229
 	{
3230
-		return strcasecmp($a['MAILBOX'],$b['MAILBOX']);
3230
+		return strcasecmp($a['MAILBOX'], $b['MAILBOX']);
3231 3231
 	}
3232 3232
 
3233 3233
 	/**
@@ -3237,13 +3237,13 @@  discard block
 block discarded – undo
3237 3237
 	 * @param string $_hDelimiter hierarchy delimiter
3238 3238
 	 * @return array returns an array of data extracted from given node path
3239 3239
 	 */
3240
-	static function pathToFolderData ($_path, $_hDelimiter)
3240
+	static function pathToFolderData($_path, $_hDelimiter)
3241 3241
 	{
3242 3242
 		if (!strpos($_path, self::DELIMITER)) $_path = self::DELIMITER.$_path;
3243 3243
 		list(,$path) = explode(self::DELIMITER, $_path);
3244 3244
 		$path_chain = $parts = explode($_hDelimiter, $path);
3245 3245
 		$name = array_pop($parts);
3246
-		return array (
3246
+		return array(
3247 3247
 			'name' => $name,
3248 3248
 			'mailbox' => $path,
3249 3249
 			'parent' => implode($_hDelimiter, $parts),
@@ -3266,8 +3266,8 @@  discard block
 block discarded – undo
3266 3266
 		// 0, 1 und -1
3267 3267
 		$a = self::pathToFolderData($_a['MAILBOX'], $_a['delimiter']);
3268 3268
 		$b = self::pathToFolderData($_b['MAILBOX'], $_b['delimiter']);
3269
-		$pos1 = array_search(trim($a['name']),self::$autoFolders);
3270
-		$pos2 = array_search(trim($b['name']),self::$autoFolders);
3269
+		$pos1 = array_search(trim($a['name']), self::$autoFolders);
3270
+		$pos2 = array_search(trim($b['name']), self::$autoFolders);
3271 3271
 		if ($pos1 == $pos2) return 0;
3272 3272
 		return ($pos1 < $pos2) ? -1 : 1;
3273 3273
 	}
@@ -3280,10 +3280,10 @@  discard block
 block discarded – undo
3280 3280
 	 * @param object $b array of folderobjects
3281 3281
 	 * @return int expect values (0, 1 or -1)
3282 3282
 	 */
3283
-	function sortByDisplayName($a,$b)
3283
+	function sortByDisplayName($a, $b)
3284 3284
 	{
3285 3285
 		// 0, 1 und -1
3286
-		return strcasecmp($a->displayName,$b->displayName);
3286
+		return strcasecmp($a->displayName, $b->displayName);
3287 3287
 	}
3288 3288
 
3289 3289
 	/**
@@ -3294,11 +3294,11 @@  discard block
 block discarded – undo
3294 3294
 	 * @param object $b array of folderobjects
3295 3295
 	 * @return int expect values (0, 1 or -1)
3296 3296
 	 */
3297
-	function sortByAutoFolderPos($a,$b)
3297
+	function sortByAutoFolderPos($a, $b)
3298 3298
 	{
3299 3299
 		// 0, 1 und -1
3300
-		$pos1 = array_search(trim($a->shortFolderName),self::$autoFolders);
3301
-		$pos2 = array_search(trim($b->shortFolderName),self::$autoFolders);
3300
+		$pos1 = array_search(trim($a->shortFolderName), self::$autoFolders);
3301
+		$pos2 = array_search(trim($b->shortFolderName), self::$autoFolders);
3302 3302
 		if ($pos1 == $pos2) return 0;
3303 3303
 		return ($pos1 < $pos2) ? -1 : 1;
3304 3304
 	}
@@ -3311,7 +3311,7 @@  discard block
 block discarded – undo
3311 3311
 	 * @param boolean $_returnObject return the counters as object rather than an array
3312 3312
 	 * @return mixed false or array of counters array(MESSAGES,UNSEEN,RECENT,UIDNEXT,UIDVALIDITY) or object
3313 3313
 	 */
3314
-	function getMailBoxCounters($folderName,$_returnObject=true)
3314
+	function getMailBoxCounters($folderName, $_returnObject = true)
3315 3315
 	{
3316 3316
 		try
3317 3317
 		{
@@ -3323,9 +3323,9 @@  discard block
 block discarded – undo
3323 3323
 			if (self::$debug) error_log(__METHOD__." returned FolderStatus for Folder $folderName:".$e->getMessage());
3324 3324
 			return false;
3325 3325
 		}
3326
-		if(is_array($folderStatus)) {
3327
-			if ($_returnObject===false) return $folderStatus;
3328
-			$status =  new \stdClass;
3326
+		if (is_array($folderStatus)) {
3327
+			if ($_returnObject === false) return $folderStatus;
3328
+			$status = new \stdClass;
3329 3329
 			$status->messages   = $folderStatus['MESSAGES'];
3330 3330
 			$status->unseen     = $folderStatus['UNSEEN'];
3331 3331
 			$status->recent     = $folderStatus['RECENT'];
@@ -3347,42 +3347,42 @@  discard block
 block discarded – undo
3347 3347
 	 * @param string $reclevel 0, counter to keep track of the current recursionlevel
3348 3348
 	 * @return array of mailboxes
3349 3349
 	 */
3350
-	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel=0)
3350
+	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel = 0)
3351 3351
 	{
3352 3352
 		#echo __METHOD__." retrieve SubFolders for $_mailbox$delimiter <br>";
3353
-		$maxreclevel=25;
3353
+		$maxreclevel = 25;
3354 3354
 		if ($reclevel > $maxreclevel) {
3355
-			error_log( __METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3355
+			error_log(__METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3356 3356
 			return array();
3357 3357
 		}
3358 3358
 		$reclevel++;
3359 3359
 		// clean up double delimiters
3360
-		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$_mailbox);
3360
+		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $_mailbox);
3361 3361
 		//get that mailbox in question
3362
-		$mbx = $this->icServer->getMailboxes($_mailbox,1,true);
3362
+		$mbx = $this->icServer->getMailboxes($_mailbox, 1, true);
3363 3363
 		$mbxkeys = array_keys($mbx);
3364 3364
 		#_debug_array($mbx);
3365 3365
 //error_log(__METHOD__.' ('.__LINE__.') '.' Delimiter:'.array2string($delimiter));
3366 3366
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
3367 3367
 		// Example: Array([INBOX/GaGa] => Array([MAILBOX] => INBOX/GaGa[ATTRIBUTES] => Array([0] => \\unmarked)[delimiter] => /))
3368
-		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"]))) {
3368
+		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"]))) {
3369 3369
 			// if there are children fetch them
3370 3370
 			//echo $mbx[$mbxkeys[0]]['MAILBOX']."<br>";
3371 3371
 
3372
-			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '':$delimiter),2,false);
3372
+			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '' : $delimiter), 2, false);
3373 3373
 			//$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'],2,false);
3374 3374
 			//_debug_array($buff);
3375 3375
 			$allMailboxes = array();
3376 3376
 			foreach ($buff as $mbxname) {
3377 3377
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbxname));
3378
-				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$mbxname['MAILBOX']);
3378
+				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $mbxname['MAILBOX']);
3379 3379
 				#echo "About to recur in level $reclevel:".$mbxname."<br>";
3380
-				if ( $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix  && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3380
+				if ($mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3381 3381
 				{
3382 3382
 					$allMailboxes = array_merge($allMailboxes, self::getMailBoxesRecursive($mbxname, $delimiter, $prefix, $reclevel));
3383 3383
 				}
3384 3384
 			}
3385
-			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'];
3385
+			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'];
3386 3386
 			return $allMailboxes;
3387 3387
 		} else {
3388 3388
 			return array($_mailbox);
@@ -3397,18 +3397,18 @@  discard block
 block discarded – undo
3397 3397
 	 * @param boolean& $created =null on return true: if folder was just created, false if not
3398 3398
 	 * @return mixed string or false
3399 3399
 	 */
3400
-	function _getSpecialUseFolder($_type, $_checkexistance=TRUE, &$created=null)
3400
+	function _getSpecialUseFolder($_type, $_checkexistance = TRUE, &$created = null)
3401 3401
 	{
3402 3402
 		static $types = array(
3403
-			'Drafts'   => array('profileKey'=>'acc_folder_draft','autoFolderName'=>'Drafts'),
3404
-			'Template' => array('profileKey'=>'acc_folder_template','autoFolderName'=>'Templates'),
3405
-			'Trash'    => array('profileKey'=>'acc_folder_trash','autoFolderName'=>'Trash'),
3406
-			'Sent'     => array('profileKey'=>'acc_folder_sent','autoFolderName'=>'Sent'),
3407
-			'Junk'     => array('profileKey'=>'acc_folder_junk','autoFolderName'=>'Junk'),
3408
-			'Outbox'   => array('profileKey'=>'acc_folder_outbox','autoFolderName'=>'Outbox'),
3409
-			'Archive'   => array('profileKey'=>'acc_folder_archive','autoFolderName'=>'Archive'),
3403
+			'Drafts'   => array('profileKey'=>'acc_folder_draft', 'autoFolderName'=>'Drafts'),
3404
+			'Template' => array('profileKey'=>'acc_folder_template', 'autoFolderName'=>'Templates'),
3405
+			'Trash'    => array('profileKey'=>'acc_folder_trash', 'autoFolderName'=>'Trash'),
3406
+			'Sent'     => array('profileKey'=>'acc_folder_sent', 'autoFolderName'=>'Sent'),
3407
+			'Junk'     => array('profileKey'=>'acc_folder_junk', 'autoFolderName'=>'Junk'),
3408
+			'Outbox'   => array('profileKey'=>'acc_folder_outbox', 'autoFolderName'=>'Outbox'),
3409
+			'Archive'   => array('profileKey'=>'acc_folder_archive', 'autoFolderName'=>'Archive'),
3410 3410
 		);
3411
-		if ($_type == 'Templates') $_type = 'Template';	// for some reason self::$autofolders uses 'Templates'!
3411
+		if ($_type == 'Templates') $_type = 'Template'; // for some reason self::$autofolders uses 'Templates'!
3412 3412
 		$created = false;
3413 3413
 		if (!isset($types[$_type]))
3414 3414
 		{
@@ -3430,7 +3430,7 @@  discard block
 block discarded – undo
3430 3430
 		}
3431 3431
 		// do not try to autocreate configured Archive-Folder. Return false if configured folder does not exist
3432 3432
 		if ($_type == 'Archive') {
3433
-			if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3433
+			if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3434 3434
 				return false;
3435 3435
 			} else {
3436 3436
 				return $_folderName;
@@ -3438,38 +3438,38 @@  discard block
 block discarded – undo
3438 3438
 
3439 3439
 		}
3440 3440
 		// does the folder exist??? (is configured/preset, but non-existent)
3441
-		if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3441
+		if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3442 3442
 			try
3443 3443
 			{
3444 3444
 				$error = null;
3445 3445
 				if (($_folderName = $this->createFolder('', $_folderName, $error))) $created = true;
3446 3446
 				if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3447 3447
 			}
3448
-			catch(Exception $e)
3448
+			catch (Exception $e)
3449 3449
 			{
3450 3450
 				error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage().':'.function_backtrace());
3451 3451
 				$_folderName = false;
3452 3452
 			}
3453 3453
 		}
3454 3454
 		// not sure yet if false is the correct behavior on none
3455
-		if ($_folderName =='none') return 'none' ; //false;
3455
+		if ($_folderName == 'none') return 'none'; //false;
3456 3456
 		//no (valid) folder found yet; try specialUseFolders
3457
-		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type,self::$specialUseFolders))) $_folderName = $f;
3457
+		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type, self::$specialUseFolders))) $_folderName = $f;
3458 3458
 		//no specialUseFolder; try some Defaults
3459 3459
 		if (empty($_folderName) && isset($types[$_type]))
3460 3460
 		{
3461 3461
 			$nameSpace = $this->_getNameSpaces();
3462
-			$prefix='';
3462
+			$prefix = '';
3463 3463
 			foreach ($nameSpace as $nSp)
3464 3464
 			{
3465
-				if ($nSp['type']=='personal')
3465
+				if ($nSp['type'] == 'personal')
3466 3466
 				{
3467 3467
 					//error_log(__METHOD__.__LINE__.array2string($nSp));
3468 3468
 					$prefix = $nSp['prefix'];
3469 3469
 					break;
3470 3470
 				}
3471 3471
 			}
3472
-			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'],true))
3472
+			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'], true))
3473 3473
 			{
3474 3474
 				$_folderName = $prefix.$types[$_type]['autoFolderName'];
3475 3475
 			}
@@ -3478,11 +3478,11 @@  discard block
 block discarded – undo
3478 3478
 				try
3479 3479
 				{
3480 3480
 					$error = null;
3481
-					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'],$error);
3481
+					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'], $error);
3482 3482
 					$_folderName = $prefix.$types[$_type]['autoFolderName'];
3483 3483
 					if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3484 3484
 				}
3485
-				catch(Exception $e)
3485
+				catch (Exception $e)
3486 3486
 				{
3487 3487
 					error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage());
3488 3488
 					$_folderName = false;
@@ -3498,7 +3498,7 @@  discard block
 block discarded – undo
3498 3498
 	 * @param boolean $_checkexistance trigger check for existance
3499 3499
 	 * @return mixed string or false
3500 3500
 	 */
3501
-	function getFolderByType($type, $_checkexistance=false)
3501
+	function getFolderByType($type, $_checkexistance = false)
3502 3502
 	{
3503 3503
 		return $this->_getSpecialUseFolder($type, $_checkexistance);
3504 3504
 	}
@@ -3508,7 +3508,7 @@  discard block
 block discarded – undo
3508 3508
 	 * @param boolean $_checkexistance trigger check for existance
3509 3509
 	 * @return mixed string or false
3510 3510
 	 */
3511
-	function getJunkFolder($_checkexistance=TRUE)
3511
+	function getJunkFolder($_checkexistance = TRUE)
3512 3512
 	{
3513 3513
 		return $this->_getSpecialUseFolder('Junk', $_checkexistance);
3514 3514
 	}
@@ -3518,7 +3518,7 @@  discard block
 block discarded – undo
3518 3518
 	 * @param boolean $_checkexistance trigger check for existance
3519 3519
 	 * @return mixed string or false
3520 3520
 	 */
3521
-	function getDraftFolder($_checkexistance=TRUE)
3521
+	function getDraftFolder($_checkexistance = TRUE)
3522 3522
 	{
3523 3523
 		return $this->_getSpecialUseFolder('Drafts', $_checkexistance);
3524 3524
 	}
@@ -3528,7 +3528,7 @@  discard block
 block discarded – undo
3528 3528
 	 * @param boolean $_checkexistance trigger check for existance
3529 3529
 	 * @return mixed string or false
3530 3530
 	 */
3531
-	function getTemplateFolder($_checkexistance=TRUE)
3531
+	function getTemplateFolder($_checkexistance = TRUE)
3532 3532
 	{
3533 3533
 		return $this->_getSpecialUseFolder('Template', $_checkexistance);
3534 3534
 	}
@@ -3538,7 +3538,7 @@  discard block
 block discarded – undo
3538 3538
 	 * @param boolean $_checkexistance trigger check for existance
3539 3539
 	 * @return mixed string or false
3540 3540
 	 */
3541
-	function getTrashFolder($_checkexistance=TRUE)
3541
+	function getTrashFolder($_checkexistance = TRUE)
3542 3542
 	{
3543 3543
 		return $this->_getSpecialUseFolder('Trash', $_checkexistance);
3544 3544
 	}
@@ -3548,7 +3548,7 @@  discard block
 block discarded – undo
3548 3548
 	 * @param boolean $_checkexistance trigger check for existance
3549 3549
 	 * @return mixed string or false
3550 3550
 	 */
3551
-	function getSentFolder($_checkexistance=TRUE)
3551
+	function getSentFolder($_checkexistance = TRUE)
3552 3552
 	{
3553 3553
 		return $this->_getSpecialUseFolder('Sent', $_checkexistance);
3554 3554
 	}
@@ -3558,7 +3558,7 @@  discard block
 block discarded – undo
3558 3558
 	 * @param boolean $_checkexistance trigger check for existance
3559 3559
 	 * @return mixed string or false
3560 3560
 	 */
3561
-	function getOutboxFolder($_checkexistance=TRUE)
3561
+	function getOutboxFolder($_checkexistance = TRUE)
3562 3562
 	{
3563 3563
 		return $this->_getSpecialUseFolder('Outbox', $_checkexistance);
3564 3564
 	}
@@ -3568,7 +3568,7 @@  discard block
 block discarded – undo
3568 3568
 	 * @param boolean $_checkexistance trigger check for existance . We do no autocreation for configured Archive folder
3569 3569
 	 * @return mixed string or false
3570 3570
 	 */
3571
-	function getArchiveFolder($_checkexistance=TRUE)
3571
+	function getArchiveFolder($_checkexistance = TRUE)
3572 3572
 	{
3573 3573
 		return $this->_getSpecialUseFolder('Archive', $_checkexistance);
3574 3574
 	}
@@ -3580,10 +3580,10 @@  discard block
 block discarded – undo
3580 3580
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3581 3581
 	 * @return boolean
3582 3582
 	 */
3583
-	function isSentFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3583
+	function isSentFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3584 3584
 	{
3585 3585
 		$sentFolder = $this->getSentFolder($_checkexistance);
3586
-		if(empty($sentFolder)) {
3586
+		if (empty($sentFolder)) {
3587 3587
 			return false;
3588 3588
 		}
3589 3589
 		// does the folder exist???
@@ -3593,13 +3593,13 @@  discard block
 block discarded – undo
3593 3593
 
3594 3594
 		if ($_exactMatch)
3595 3595
 		{
3596
-			if(false !== stripos($_folderName, $sentFolder)&& strlen($_folderName)==strlen($sentFolder)) {
3596
+			if (false !== stripos($_folderName, $sentFolder) && strlen($_folderName) == strlen($sentFolder)) {
3597 3597
 				return true;
3598 3598
 			} else {
3599 3599
 				return false;
3600 3600
 			}
3601 3601
 		} else {
3602
-			if(false !== stripos($_folderName, $sentFolder)) {
3602
+			if (false !== stripos($_folderName, $sentFolder)) {
3603 3603
 				return true;
3604 3604
 			} else {
3605 3605
 				return false;
@@ -3614,9 +3614,9 @@  discard block
 block discarded – undo
3614 3614
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3615 3615
 	 * @return boolean
3616 3616
 	 */
3617
-	function isOutbox($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3617
+	function isOutbox($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3618 3618
 	{
3619
-		if (stripos($_folderName, 'Outbox')===false) {
3619
+		if (stripos($_folderName, 'Outbox') === false) {
3620 3620
 			return false;
3621 3621
 		}
3622 3622
 		// does the folder exist???
@@ -3624,13 +3624,13 @@  discard block
 block discarded – undo
3624 3624
 			$outboxFolder = $this->getOutboxFolder($_checkexistance);
3625 3625
 			if ($_exactMatch)
3626 3626
 			{
3627
-				if(false !== stripos($_folderName, $outboxFolder)&& strlen($_folderName)==strlen($outboxFolder)) {
3627
+				if (false !== stripos($_folderName, $outboxFolder) && strlen($_folderName) == strlen($outboxFolder)) {
3628 3628
 					return true;
3629 3629
 				} else {
3630 3630
 					return false;
3631 3631
 				}
3632 3632
 			} else {
3633
-				if(false !== stripos($_folderName, $outboxFolder)) {
3633
+				if (false !== stripos($_folderName, $outboxFolder)) {
3634 3634
 					return true;
3635 3635
 				} else {
3636 3636
 					return false;
@@ -3647,26 +3647,26 @@  discard block
 block discarded – undo
3647 3647
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3648 3648
 	 * @return boolean
3649 3649
 	 */
3650
-	function isDraftFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3650
+	function isDraftFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3651 3651
 	{
3652 3652
 		$draftFolder = $this->getDraftFolder($_checkexistance);
3653
-		if(empty($draftFolder)) {
3653
+		if (empty($draftFolder)) {
3654 3654
 			return false;
3655 3655
 		}
3656 3656
 		// does the folder exist???
3657 3657
 		if ($_checkexistance && !$this->folderExists($_folderName)) {
3658 3658
 			return false;
3659 3659
 		}
3660
-		if (is_a($_folderName,"Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3660
+		if (is_a($_folderName, "Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3661 3661
 		if ($_exactMatch)
3662 3662
 		{
3663
-			if(false !== stripos($_folderName, $draftFolder)&& strlen($_folderName)==strlen($draftFolder)) {
3663
+			if (false !== stripos($_folderName, $draftFolder) && strlen($_folderName) == strlen($draftFolder)) {
3664 3664
 				return true;
3665 3665
 			} else {
3666 3666
 				return false;
3667 3667
 			}
3668 3668
 		} else {
3669
-			if(false !== stripos($_folderName, $draftFolder)) {
3669
+			if (false !== stripos($_folderName, $draftFolder)) {
3670 3670
 				return true;
3671 3671
 			} else {
3672 3672
 				return false;
@@ -3681,10 +3681,10 @@  discard block
 block discarded – undo
3681 3681
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3682 3682
 	 * @return boolean
3683 3683
 	 */
3684
-	function isTrashFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3684
+	function isTrashFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3685 3685
 	{
3686 3686
 		$trashFolder = $this->getTrashFolder($_checkexistance);
3687
-		if(empty($trashFolder)) {
3687
+		if (empty($trashFolder)) {
3688 3688
 			return false;
3689 3689
 		}
3690 3690
 		// does the folder exist???
@@ -3694,13 +3694,13 @@  discard block
 block discarded – undo
3694 3694
 
3695 3695
 		if ($_exactMatch)
3696 3696
 		{
3697
-			if(false !== stripos($_folderName, $trashFolder)&& strlen($_folderName)==strlen($trashFolder)) {
3697
+			if (false !== stripos($_folderName, $trashFolder) && strlen($_folderName) == strlen($trashFolder)) {
3698 3698
 				return true;
3699 3699
 			} else {
3700 3700
 				return false;
3701 3701
 			}
3702 3702
 		} else {
3703
-			if(false !== stripos($_folderName, $trashFolder)) {
3703
+			if (false !== stripos($_folderName, $trashFolder)) {
3704 3704
 				return true;
3705 3705
 			} else {
3706 3706
 				return false;
@@ -3715,10 +3715,10 @@  discard block
 block discarded – undo
3715 3715
 	 * @param boolean $_exactMatch make the check more strict. return false if folder is subfolder only
3716 3716
 	 * @return boolean
3717 3717
 	 */
3718
-	function isTemplateFolder($_folderName, $_checkexistance=TRUE, $_exactMatch=false)
3718
+	function isTemplateFolder($_folderName, $_checkexistance = TRUE, $_exactMatch = false)
3719 3719
 	{
3720 3720
 		$templateFolder = $this->getTemplateFolder($_checkexistance);
3721
-		if(empty($templateFolder)) {
3721
+		if (empty($templateFolder)) {
3722 3722
 			return false;
3723 3723
 		}
3724 3724
 		// does the folder exist???
@@ -3727,13 +3727,13 @@  discard block
 block discarded – undo
3727 3727
 		}
3728 3728
 		if ($_exactMatch)
3729 3729
 		{
3730
-			if(false !== stripos($_folderName, $templateFolder)&& strlen($_folderName)==strlen($templateFolder)) {
3730
+			if (false !== stripos($_folderName, $templateFolder) && strlen($_folderName) == strlen($templateFolder)) {
3731 3731
 				return true;
3732 3732
 			} else {
3733 3733
 				return false;
3734 3734
 			}
3735 3735
 		} else {
3736
-			if(false !== stripos($_folderName, $templateFolder)) {
3736
+			if (false !== stripos($_folderName, $templateFolder)) {
3737 3737
 				return true;
3738 3738
 			} else {
3739 3739
 				return false;
@@ -3747,24 +3747,24 @@  discard block
 block discarded – undo
3747 3747
 	 * @param boolean $_forceCheck trigger check for existance on icServer
3748 3748
 	 * @return mixed string or false
3749 3749
 	 */
3750
-	function folderExists($_folder, $_forceCheck=false)
3750
+	function folderExists($_folder, $_forceCheck = false)
3751 3751
 	{
3752 3752
 		static $folderInfo;
3753 3753
 		$forceCheck = $_forceCheck;
3754 3754
 		if (empty($_folder))
3755 3755
 		{
3756 3756
 			// this error is more or less without significance, unless we force the check
3757
-			if ($_forceCheck===true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3757
+			if ($_forceCheck === true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3758 3758
 			return false;
3759 3759
 		}
3760 3760
 		// when check is not enforced , we assume a folder represented as Horde_Imap_Client_Mailbox as existing folder
3761
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")&&$_forceCheck===false) return true;
3762
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")) $_folder =  $_folder->utf8;
3761
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox") && $_forceCheck === false) return true;
3762
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox")) $_folder = $_folder->utf8;
3763 3763
 		// reduce traffic within the Instance per User; Expire every 5 hours
3764 3764
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Called with Folder:'.$_folder.function_backtrace());
3765
-		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),$expiration=60*60*5);
3765
+		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), $expiration = 60 * 60 * 5);
3766 3766
 		//error_log(__METHOD__.' ('.__LINE__.') '.'Cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID.($forceCheck?'(forcedCheck)':'').':'.array2string($folderInfo));
3767
-		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck===false)
3767
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck === false)
3768 3768
 		{
3769 3769
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Using cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID);
3770 3770
 			return $folderInfo[$this->profileID][$_folder];
@@ -3780,7 +3780,7 @@  discard block
 block discarded – undo
3780 3780
 
3781 3781
 		// does the folder exist???
3782 3782
 		//error_log(__METHOD__."->Connected?".$this->icServer->_connected.", ".$_folder.", ".($forceCheck?' forceCheck activated':'dont check on server'));
3783
-		if ( $forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3783
+		if ($forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3784 3784
 			//error_log(__METHOD__."->NotConnected and forceCheck with profile:".$this->profileID);
3785 3785
 			//return false;
3786 3786
 			//try to connect
@@ -3791,18 +3791,18 @@  discard block
 block discarded – undo
3791 3791
 		}
3792 3792
 		catch (\Exception $e)
3793 3793
 		{
3794
-			error_log(__METHOD__.__LINE__.$e->getMessage().($e->details?', '.$e->details:''));
3795
-			self::$profileDefunct[$this->profileID]=$e->getMessage().($e->details?', '.$e->details:'');
3794
+			error_log(__METHOD__.__LINE__.$e->getMessage().($e->details ? ', '.$e->details : ''));
3795
+			self::$profileDefunct[$this->profileID] = $e->getMessage().($e->details ? ', '.$e->details : '');
3796 3796
 			$folderInfo[$this->profileID][$_folder] = false;
3797 3797
 		}
3798 3798
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Folder Exists:'.$folderInfo[$this->profileID][$_folder].function_backtrace());
3799 3799
 
3800
-		if(!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3800
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3801 3801
 			$folderInfo[$this->profileID][$_folder] !== true)
3802 3802
 		{
3803 3803
 			$folderInfo[$this->profileID][$_folder] = false; // set to false, whatever it was (to have a valid returnvalue for the static return)
3804 3804
 		}
3805
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,$expiration=60*60*5);
3805
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, $expiration = 60 * 60 * 5);
3806 3806
 		return (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) ? $folderInfo[$this->profileID][$_folder] : false);
3807 3807
 	}
3808 3808
 
@@ -3815,14 +3815,14 @@  discard block
 block discarded – undo
3815 3815
 	 */
3816 3816
 	function compressFolder($_folderName = false)
3817 3817
 	{
3818
-		$folderName	= ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3819
-		$deleteOptions	= $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3820
-		$trashFolder	= $this->getTrashFolder();
3818
+		$folderName = ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3819
+		$deleteOptions = $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3820
+		$trashFolder = $this->getTrashFolder();
3821 3821
 
3822 3822
 		$this->icServer->openMailbox($folderName);
3823 3823
 
3824
-		if(strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3825
-			$this->deleteMessages('all',$folderName,'remove_immediately');
3824
+		if (strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3825
+			$this->deleteMessages('all', $folderName, 'remove_immediately');
3826 3826
 		} else {
3827 3827
 			$this->icServer->expunge($folderName);
3828 3828
 		}
@@ -3838,19 +3838,19 @@  discard block
 block discarded – undo
3838 3838
 	 * @return bool true, as we do not handle return values yet
3839 3839
 	 * @throws Exception
3840 3840
 	 */
3841
-	function deleteMessages($_messageUID, $_folder=NULL, $_forceDeleteMethod='no')
3841
+	function deleteMessages($_messageUID, $_folder = NULL, $_forceDeleteMethod = 'no')
3842 3842
 	{
3843 3843
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.array2string($_folder).', '.$_forceDeleteMethod);
3844 3844
 		$oldMailbox = '';
3845 3845
 		if (is_null($_folder) || empty($_folder)) $_folder = $this->sessionData['mailbox'];
3846 3846
 		if (empty($_messageUID))
3847 3847
 		{
3848
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
3848
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
3849 3849
 			return false;
3850 3850
 		}
3851
-		elseif ($_messageUID==='all')
3851
+		elseif ($_messageUID === 'all')
3852 3852
 		{
3853
-			$_messageUID= null;
3853
+			$_messageUID = null;
3854 3854
 		}
3855 3855
 		else
3856 3856
 		{
@@ -3859,32 +3859,32 @@  discard block
 block discarded – undo
3859 3859
 			$uidsToDelete->add($_messageUID);
3860 3860
 		}
3861 3861
 		$deleteOptions = $_forceDeleteMethod; // use forceDeleteMethod if not "no", or unknown method
3862
-		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");
3862
+		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");
3863 3863
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3864 3864
 		$trashFolder    = $this->getTrashFolder();
3865
-		$draftFolder	= $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3865
+		$draftFolder = $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3866 3866
 		$templateFolder = $this->getTemplateFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['templateFolder'];
3867
-		if((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") ||
3867
+		if ((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") ||
3868 3868
 		   (strtolower($_folder) == strtolower($draftFolder))) {
3869 3869
 			$deleteOptions = "remove_immediately";
3870 3870
 		}
3871
-		if($this->icServer->getCurrentMailbox() != $_folder) {
3871
+		if ($this->icServer->getCurrentMailbox() != $_folder) {
3872 3872
 			$oldMailbox = $this->icServer->getCurrentMailbox();
3873 3873
 			$this->icServer->openMailbox($_folder);
3874 3874
 		}
3875 3875
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3876 3876
 		$updateCache = false;
3877
-		switch($deleteOptions) {
3877
+		switch ($deleteOptions) {
3878 3878
 			case "move_to_trash":
3879 3879
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3880 3880
 				$updateCache = true;
3881
-				if(!empty($trashFolder)) {
3881
+				if (!empty($trashFolder)) {
3882 3882
 					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.implode(' : ', $_messageUID));
3883
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ". $this->sessionData['mailbox']);
3883
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ".$this->sessionData['mailbox']);
3884 3884
 					// copy messages
3885 3885
 					try
3886 3886
 					{
3887
-						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete,'move'=>true));
3887
+						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete, 'move'=>true));
3888 3888
 					}
3889 3889
 					catch (\Exception $e)
3890 3890
 					{
@@ -3896,18 +3896,18 @@  discard block
 block discarded – undo
3896 3896
 			case "mark_as_deleted":
3897 3897
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3898 3898
 				// mark messages as deleted
3899
-				if (is_null($_messageUID)) $_messageUID='all';
3900
-				foreach((array)$_messageUID as $key =>$uid)
3899
+				if (is_null($_messageUID)) $_messageUID = 'all';
3900
+				foreach ((array)$_messageUID as $key =>$uid)
3901 3901
 				{
3902 3902
 					//flag messages, that are flagged for deletion as seen too
3903 3903
 					$this->flagMessages('read', $uid, $_folder);
3904 3904
 					$flags = $this->getFlags($uid);
3905 3905
 					$this->flagMessages('delete', $uid, $_folder);
3906 3906
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
3907
-					if (strpos( array2string($flags),'Deleted')!==false) $undelete[] = $uid;
3907
+					if (strpos(array2string($flags), 'Deleted') !== false) $undelete[] = $uid;
3908 3908
 					unset($flags);
3909 3909
 				}
3910
-				foreach((array)$undelete as $key =>$uid)
3910
+				foreach ((array)$undelete as $key =>$uid)
3911 3911
 				{
3912 3912
 					$this->flagMessages('undelete', $uid, $_folder);
3913 3913
 				}
@@ -3916,14 +3916,14 @@  discard block
 block discarded – undo
3916 3916
 			case "remove_immediately":
3917 3917
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3918 3918
 				$updateCache = true;
3919
-				if (is_null($_messageUID)) $_messageUID='all';
3919
+				if (is_null($_messageUID)) $_messageUID = 'all';
3920 3920
 				if (is_object($_messageUID))
3921 3921
 				{
3922 3922
 					$this->flagMessages('delete', $_messageUID, $_folder);
3923 3923
 				}
3924 3924
 				else
3925 3925
 				{
3926
-					foreach((array)$_messageUID as $key =>$uid)
3926
+					foreach ((array)$_messageUID as $key =>$uid)
3927 3927
 					{
3928 3928
 						//flag messages, that are flagged for deletion as seen too
3929 3929
 						$this->flagMessages('delete', $uid, $_folder);
@@ -3933,7 +3933,7 @@  discard block
 block discarded – undo
3933 3933
 				$this->icServer->expunge($_folder);
3934 3934
 				break;
3935 3935
 		}
3936
-		if($oldMailbox != '') {
3936
+		if ($oldMailbox != '') {
3937 3937
 			$this->icServer->openMailbox($oldMailbox);
3938 3938
 		}
3939 3939
 
@@ -3947,7 +3947,7 @@  discard block
 block discarded – undo
3947 3947
 	 *
3948 3948
 	 * @return null/array flags
3949 3949
 	 */
3950
-	function getFlags ($_messageUID) {
3950
+	function getFlags($_messageUID) {
3951 3951
 		try
3952 3952
 		{
3953 3953
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -3960,7 +3960,7 @@  discard block
 block discarded – undo
3960 3960
 				'ids' => $uidsToFetch,
3961 3961
 			));
3962 3962
 			if (is_object($headersNew)) {
3963
-				foreach($headersNew->ids() as $id) {
3963
+				foreach ($headersNew->ids() as $id) {
3964 3964
 					$_headerObject = $headersNew->get($id);
3965 3965
 					$flags = $_headerObject->getFlags();
3966 3966
 				}
@@ -3983,22 +3983,22 @@  discard block
 block discarded – undo
3983 3983
 	 *
3984 3984
 	 * @return null/boolean
3985 3985
 	 */
3986
-	function getNotifyFlags ($_messageUID, $flags=null)
3986
+	function getNotifyFlags($_messageUID, $flags = null)
3987 3987
 	{
3988 3988
 		if (self::$debug) error_log(__METHOD__.$_messageUID.' Flags:'.array2string($flags));
3989 3989
 		try
3990 3990
 		{
3991
-			if($flags===null) $flags =  $this->getFlags($_messageUID);
3991
+			if ($flags === null) $flags = $this->getFlags($_messageUID);
3992 3992
 		}
3993 3993
 		catch (\Exception $e)
3994 3994
 		{
3995 3995
 			return null;
3996 3996
 		}
3997 3997
 
3998
-		if ( stripos( array2string($flags),'MDNSent')!==false)
3998
+		if (stripos(array2string($flags), 'MDNSent') !== false)
3999 3999
 			return true;
4000 4000
 
4001
-		if ( stripos( array2string($flags),'MDNnotSent')!==false)
4001
+		if (stripos(array2string($flags), 'MDNnotSent') !== false)
4002 4002
 			return false;
4003 4003
 
4004 4004
 		return null;
@@ -4015,45 +4015,45 @@  discard block
 block discarded – undo
4015 4015
 	 *
4016 4016
 	 * @return bool true, as we do not handle icserver->setFlags returnValue
4017 4017
 	 */
4018
-	function flagMessages($_flag, $_messageUID,$_folder=NULL)
4018
+	function flagMessages($_flag, $_messageUID, $_folder = NULL)
4019 4019
 	{
4020 4020
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",$_folder /".$this->sessionData['mailbox']);
4021 4021
 		if (empty($_messageUID))
4022 4022
 		{
4023
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
4023
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
4024 4024
 			return false;
4025 4025
 		}
4026
-		$this->icServer->openMailbox(($_folder?$_folder:$this->sessionData['mailbox']));
4026
+		$this->icServer->openMailbox(($_folder ? $_folder : $this->sessionData['mailbox']));
4027 4027
 		$folder = $this->icServer->getCurrentMailbox();
4028
-		if (is_array($_messageUID)&& count($_messageUID)>50)
4028
+		if (is_array($_messageUID) && count($_messageUID) > 50)
4029 4029
 		{
4030
-			$count = $this->getMailBoxCounters($folder,true);
4031
-			if ($count->messages == count($_messageUID)) $_messageUID='all';
4030
+			$count = $this->getMailBoxCounters($folder, true);
4031
+			if ($count->messages == count($_messageUID)) $_messageUID = 'all';
4032 4032
 		}
4033 4033
 
4034
-		if ($_messageUID==='all')
4034
+		if ($_messageUID === 'all')
4035 4035
 		{
4036 4036
 			$messageUIDs = array('all');
4037 4037
 		}
4038 4038
 		else
4039 4039
 		{
4040 4040
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4041
-			$messageUIDs = array_chunk($_messageUID,50,true);
4041
+			$messageUIDs = array_chunk($_messageUID, 50, true);
4042 4042
 		}
4043 4043
 		try
4044 4044
 		{
4045
-			foreach($messageUIDs as &$uids)
4045
+			foreach ($messageUIDs as &$uids)
4046 4046
 			{
4047
-				if ($uids==='all')
4047
+				if ($uids === 'all')
4048 4048
 				{
4049
-					$uidsToModify=null;
4049
+					$uidsToModify = null;
4050 4050
 				}
4051 4051
 				else
4052 4052
 				{
4053 4053
 					$uidsToModify = new Horde_Imap_Client_Ids();
4054 4054
 					$uidsToModify->add($uids);
4055 4055
 				}
4056
-				switch($_flag) {
4056
+				switch ($_flag) {
4057 4057
 					case "delete":
4058 4058
 						$ret = $this->icServer->store($folder, array('add'=>array('\\Deleted'), 'ids'=> $uidsToModify));
4059 4059
 						break;
@@ -4077,7 +4077,7 @@  discard block
 block discarded – undo
4077 4077
 						break;
4078 4078
 					case "unread":
4079 4079
 					case "unseen":
4080
-						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen','\\Answered','$Forwarded'), 'ids'=> $uidsToModify));
4080
+						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen', '\\Answered', '$Forwarded'), 'ids'=> $uidsToModify));
4081 4081
 						break;
4082 4082
 					case "mdnsent":
4083 4083
 						$ret = $this->icServer->store($folder, array('add'=>array('MDNSent'), 'ids'=> $uidsToModify));
@@ -4135,13 +4135,13 @@  discard block
 block discarded – undo
4135 4135
 				}
4136 4136
 			}
4137 4137
 		}
4138
-		catch(Exception $e)
4138
+		catch (Exception $e)
4139 4139
 		{
4140 4140
 			error_log(__METHOD__.__LINE__.' Error, could not flag messages in folder '.$folder.' Reason:'.$e->getMessage());
4141 4141
 		}
4142 4142
 		if ($folder instanceof Horde_Imap_Client_Mailbox) $_folder = $folder->utf8;
4143 4143
 		//error_log(__METHOD__.__LINE__.'#'.$this->icServer->ImapServerId.'#'.array2string($_folder).'#');
4144
-		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder)?$_folder: $this->sessionData['mailbox'])]['uidValidity'] = 0;
4144
+		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder) ? $_folder : $this->sessionData['mailbox'])]['uidValidity'] = 0;
4145 4145
 
4146 4146
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",".($_folder?$_folder:$this->sessionData['mailbox']));
4147 4147
 		return true; // as we do not catch/examine setFlags returnValue
@@ -4162,19 +4162,19 @@  discard block
 block discarded – undo
4162 4162
 	 * @return mixed/bool true,false or new uid
4163 4163
 	 * @throws Exception
4164 4164
 	 */
4165
-	function moveMessages($_foldername, $_messageUID, $deleteAfterMove=true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4165
+	function moveMessages($_foldername, $_messageUID, $deleteAfterMove = true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4166 4166
 	{
4167
-		$source = Mail\Account::read(($_sourceProfileID?$_sourceProfileID:$this->icServer->ImapServerId))->imapServer();
4167
+		$source = Mail\Account::read(($_sourceProfileID ? $_sourceProfileID : $this->icServer->ImapServerId))->imapServer();
4168 4168
 		//$deleteOptions  = $GLOBALS['egw_info']["user"]["preferences"]["mail"]["deleteOptions"];
4169 4169
 		if (empty($_messageUID))
4170 4170
 		{
4171
-			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',',$_messageUID));
4171
+			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',', $_messageUID));
4172 4172
 			return false;
4173 4173
 		}
4174
-		elseif ($_messageUID==='all')
4174
+		elseif ($_messageUID === 'all')
4175 4175
 		{
4176 4176
 			//error_log(__METHOD__." all Message(s): ".implode(',',$_messageUID));
4177
-			$uidsToMove= null;
4177
+			$uidsToMove = null;
4178 4178
 		}
4179 4179
 		else
4180 4180
 		{
@@ -4183,7 +4183,7 @@  discard block
 block discarded – undo
4183 4183
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4184 4184
 			$uidsToMove->add($_messageUID);
4185 4185
 		}
4186
-		$sourceFolder = (!empty($currentFolder)?$currentFolder: $this->sessionData['mailbox']);
4186
+		$sourceFolder = (!empty($currentFolder) ? $currentFolder : $this->sessionData['mailbox']);
4187 4187
 		//error_log(__METHOD__.__LINE__."$_targetProfileID !== ".array2string($source->ImapServerId));
4188 4188
 		if (!is_null($_targetProfileID) && $_targetProfileID !== $source->ImapServerId)
4189 4189
 		{
@@ -4203,19 +4203,19 @@  discard block
 block discarded – undo
4203 4203
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' mailheaders:'.array2string($headersNew));
4204 4204
 
4205 4205
 			if (is_object($headersNew)) {
4206
-				$c=0;
4206
+				$c = 0;
4207 4207
 				$retUid = new Horde_Imap_Client_Ids();
4208 4208
 				// we copy chunks of 5 to avoid too much memory and/or server stress
4209 4209
 				// some servers seem not to allow/support the appendig of multiple messages. so we are down to one
4210
-				foreach($headersNew as &$_headerObject) {
4210
+				foreach ($headersNew as &$_headerObject) {
4211 4211
 					$c++;
4212 4212
 					$flags = $_headerObject->getFlags(); //unseen status seems to be lost when retrieving the full message
4213 4213
 					$date = $_headerObject->getImapDate();
4214
-					$currentDate =  new Horde_Imap_Client_DateTime();
4214
+					$currentDate = new Horde_Imap_Client_DateTime();
4215 4215
 					// if the internal Date of the message equals the current date; try using the header date
4216
-					if ($date==$currentDate)
4216
+					if ($date == $currentDate)
4217 4217
 					{
4218
-						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4218
+						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4219 4219
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#'.$headerForPrio['DATE']);
4220 4220
 						$date = new Horde_Imap_Client_DateTime($headerForPrio['DATE']);
4221 4221
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#');
@@ -4224,20 +4224,20 @@  discard block
 block discarded – undo
4224 4224
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
4225 4225
 					$body = $_headerObject->getFullMsg();
4226 4226
 					$dataNflags[] = array('data'=>$body, 'flags'=>$flags, 'internaldate'=>$date);
4227
-					if ($c==1)
4227
+					if ($c == 1)
4228 4228
 					{
4229 4229
 						$target = Mail\Account::read($_targetProfileID)->imapServer();
4230 4230
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' TargetServer:'.$_targetProfileID.' TargetFolderObject:'.array2string($_foldername));
4231 4231
 						$foldername = $target->getMailbox($_foldername);
4232 4232
 						// make sure the target folder is open and ready
4233 4233
 						$target->openMailbox($foldername);
4234
-						$ret = $target->append($foldername,$dataNflags);
4234
+						$ret = $target->append($foldername, $dataNflags);
4235 4235
 						$retUid->add($ret);
4236 4236
 						unset($dataNflags);
4237 4237
 						// sleep 500 miliseconds; AS some sERVERs seem not to be capable of the load this is
4238 4238
 						// inflicting in them. they "reply" with an unspecific IMAP Error
4239
-						time_nanosleep(0,500000);
4240
-						$c=0;
4239
+						time_nanosleep(0, 500000);
4240
+						$c = 0;
4241 4241
 					}
4242 4242
 				}
4243 4243
 				if (isset($dataNflags))
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
 					$foldername = $target->getMailbox($_foldername);
4248 4248
 					// make sure the target folder is open and ready
4249 4249
 					$target->openMailbox($foldername);
4250
-					$ret = $target->append($foldername,$dataNflags);
4250
+					$ret = $target->append($foldername, $dataNflags);
4251 4251
 					$retUid->add($ret);
4252 4252
 					unset($dataNflags);
4253 4253
 				}
@@ -4258,7 +4258,7 @@  discard block
 block discarded – undo
4258 4258
 				{
4259 4259
 					$remember = $this->icServer;
4260 4260
 					$this->icServer = $source;
4261
-					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod='remove_immediately');
4261
+					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod = 'remove_immediately');
4262 4262
 					$this->icServer = $remember;
4263 4263
 				}
4264 4264
 			}
@@ -4267,7 +4267,7 @@  discard block
 block discarded – undo
4267 4267
 		{
4268 4268
 			try
4269 4269
 			{
4270
-				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove,'move'=>$deleteAfterMove));
4270
+				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove, 'move'=>$deleteAfterMove));
4271 4271
 			}
4272 4272
 			catch (exception $e)
4273 4273
 			{
@@ -4287,22 +4287,22 @@  discard block
 block discarded – undo
4287 4287
 	 * @param string $format ='' if none is passed, use user prefs
4288 4288
 	 * @return string returns the date as it is parseable by strtotime, or current timestamp if everything fails
4289 4289
 	 */
4290
-	static function _strtotime($_date='', $format='', $convert2usertime=false)
4290
+	static function _strtotime($_date = '', $format = '', $convert2usertime = false)
4291 4291
 	{
4292 4292
 		try {
4293
-			$date = new DateTime($_date);	// parse date & time including timezone (throws exception, if not parsable)
4294
-			if ($convert2usertime) $date->setUser();	// convert to user-time
4293
+			$date = new DateTime($_date); // parse date & time including timezone (throws exception, if not parsable)
4294
+			if ($convert2usertime) $date->setUser(); // convert to user-time
4295 4295
 			$date2return = $date->format($format);
4296 4296
 		}
4297
-		catch(\Exception $e)
4297
+		catch (\Exception $e)
4298 4298
 		{
4299
-			unset($e);	// not used
4299
+			unset($e); // not used
4300 4300
 
4301 4301
 			// remove last space-separated part and retry
4302
-			$parts = explode(' ',$_date);
4302
+			$parts = explode(' ', $_date);
4303 4303
 			// try only 10 times to prevent of causing error by reaching
4304 4304
 			// maximum function nesting level.
4305
-			if (count($parts) > 1 && count($parts)<10)
4305
+			if (count($parts) > 1 && count($parts) < 10)
4306 4306
 			{
4307 4307
 				array_pop($parts);
4308 4308
 				$date2return = self::_strtotime(implode(' ', $parts), $format, $convert2usertime);
@@ -4322,12 +4322,12 @@  discard block
 block discarded – undo
4322 4322
 	 * @param mixed $_charset false or string -> Target charset, if false Mail displayCharset will be used
4323 4323
 	 * @return string
4324 4324
 	 */
4325
-	static function htmlentities($_string, $_charset=false)
4325
+	static function htmlentities($_string, $_charset = false)
4326 4326
 	{
4327 4327
 		//setting the charset (if not given)
4328
-		if ($_charset===false) $_charset = self::$displayCharset;
4328
+		if ($_charset === false) $_charset = self::$displayCharset;
4329 4329
 		$string = @htmlentities($_string, ENT_QUOTES, $_charset, false);
4330
-		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string,Translation::detect_encoding($_string),$_charset),ENT_QUOTES | ENT_IGNORE,$_charset, false);
4330
+		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string, Translation::detect_encoding($_string), $_charset), ENT_QUOTES|ENT_IGNORE, $_charset, false);
4331 4331
 		return $string;
4332 4332
 	}
4333 4333
 
@@ -4344,21 +4344,21 @@  discard block
 block discarded – undo
4344 4344
 		//$_html = str_replace("\t",' ',$_html);
4345 4345
 		//error_log(__METHOD__.__LINE__.':'.$_html);
4346 4346
 		//repair doubleencoded ampersands, and some stuff htmLawed stumbles upon with balancing switched on
4347
-		$_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>'),
4348
-							 array('&amp;',    '<BR>',           '<BR>',             '<BR>',             '</font></td>','<td>',    '',         '',           '',  ''),$_html);
4347
+		$_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>'),
4348
+							 array('&amp;', '<BR>', '<BR>', '<BR>', '</font></td>', '<td>', '', '', '', ''), $_html);
4349 4349
 		//$_html = str_replace(array('&amp;amp;'),array('&amp;'),$_html);
4350
-		if (stripos($_html,'style')!==false) Mail\Html::replaceTagsCompletley($_html,'style'); // clean out empty or pagewide style definitions / left over tags
4351
-		if (stripos($_html,'head')!==false) Mail\Html::replaceTagsCompletley($_html,'head'); // Strip out stuff in head
4350
+		if (stripos($_html, 'style') !== false) Mail\Html::replaceTagsCompletley($_html, 'style'); // clean out empty or pagewide style definitions / left over tags
4351
+		if (stripos($_html, 'head') !== false) Mail\Html::replaceTagsCompletley($_html, 'head'); // Strip out stuff in head
4352 4352
 		//if (stripos($_html,'![if')!==false && stripos($_html,'<![endif]>')!==false) Mail\Html::replaceTagsCompletley($_html,'!\[if','<!\[endif\]>',false); // Strip out stuff in ifs
4353 4353
 		//if (stripos($_html,'!--[if')!==false && stripos($_html,'<![endif]-->')!==false) Mail\Html::replaceTagsCompletley($_html,'!--\[if','<!\[endif\]-->',false); // Strip out stuff in ifs
4354 4354
 		//error_log(__METHOD__.' ('.__LINE__.') '.$_html);
4355 4355
 
4356 4356
 		if (get_magic_quotes_gpc() === 1) $_html = stripslashes($_html);
4357 4357
 		// Strip out doctype in head, as htmlLawed cannot handle it TODO: Consider extracting it and adding it afterwards
4358
-		if (stripos($_html,'!doctype')!==false) Mail\Html::replaceTagsCompletley($_html,'!doctype');
4359
-		if (stripos($_html,'?xml:namespace')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml:namespace','/>',false);
4360
-		if (stripos($_html,'?xml version')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml version','\?>',false);
4361
-		if (strpos($_html,'!CURSOR')!==false) Mail\Html::replaceTagsCompletley($_html,'!CURSOR');
4358
+		if (stripos($_html, '!doctype') !== false) Mail\Html::replaceTagsCompletley($_html, '!doctype');
4359
+		if (stripos($_html, '?xml:namespace') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml:namespace', '/>', false);
4360
+		if (stripos($_html, '?xml version') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml version', '\?>', false);
4361
+		if (strpos($_html, '!CURSOR') !== false) Mail\Html::replaceTagsCompletley($_html, '!CURSOR');
4362 4362
 		// htmLawed filter only the 'body'
4363 4363
 		//preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $_html, $matches);
4364 4364
 		//if ($matches[2])
@@ -4369,16 +4369,16 @@  discard block
 block discarded – undo
4369 4369
 		// purify got switched to htmLawed
4370 4370
 		// some testcode to test purifying / htmlawed
4371 4371
 		//$_html = "<BLOCKQUOTE>hi <div> there </div> kram <br> </blockquote>".$_html;
4372
-		$_html = Html\HtmLawed::purify($_html,self::$htmLawed_config,array(),true);
4372
+		$_html = Html\HtmLawed::purify($_html, self::$htmLawed_config, array(), true);
4373 4373
 		//if ($hasOther) $_html = $matches[1]. $_html. $matches[3];
4374 4374
 		// clean out comments , should not be needed as purify should do the job.
4375 4375
 		$search = array(
4376
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
4377
-			'@<!--[\s\S]*?[ \t\n\r]*-->@',         // Strip multi-line comments including CDATA
4376
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
4377
+			'@<!--[\s\S]*?[ \t\n\r]*-->@', // Strip multi-line comments including CDATA
4378 4378
 		);
4379
-		$_html = preg_replace($search,"",$_html);
4379
+		$_html = preg_replace($search, "", $_html);
4380 4380
 		// remove non printable chars
4381
-		$_html = preg_replace('/([\000-\011])/','',$_html);
4381
+		$_html = preg_replace('/([\000-\011])/', '', $_html);
4382 4382
 		//error_log(__METHOD__.':'.__LINE__.':'.$_html);
4383 4383
 	}
4384 4384
 
@@ -4395,12 +4395,12 @@  discard block
 block discarded – undo
4395 4395
 	function getMimePartCharset($_mimePartObject)
4396 4396
 	{
4397 4397
 		//$charSet = 'iso-8859-1';//self::$displayCharset; //'iso-8859-1'; // self::displayCharset seems to be asmarter fallback than iso-8859-1
4398
-		$CharsetFound=false;
4398
+		$CharsetFound = false;
4399 4399
 		//echo "#".$_mimePartObject->encoding.'#<br>';
4400
-		if(is_array($_mimePartObject->parameters)) {
4401
-			if(isset($_mimePartObject->parameters['CHARSET'])) {
4400
+		if (is_array($_mimePartObject->parameters)) {
4401
+			if (isset($_mimePartObject->parameters['CHARSET'])) {
4402 4402
 				$charSet = $_mimePartObject->parameters['CHARSET'];
4403
-				$CharsetFound=true;
4403
+				$CharsetFound = true;
4404 4404
 			}
4405 4405
 		}
4406 4406
 		// this one is dirty, but until I find something that does the trick of detecting the encoding, ....
@@ -4419,7 +4419,7 @@  discard block
 block discarded – undo
4419 4419
 	function decodeMimePart($_mimeMessage, $_encoding, $_charset = '')
4420 4420
 	{
4421 4421
 		// decode the part
4422
-		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage,true));
4422
+		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage, true));
4423 4423
 		switch (strtoupper($_encoding))
4424 4424
 		{
4425 4425
 			case 'BASE64':
@@ -4454,16 +4454,16 @@  discard block
 block discarded – undo
4454 4454
 	 * @param Horde_Mime_Part& $partCalendar =null on return text/calendar part, if one was contained or false
4455 4455
 	 * @return array containing the desired part
4456 4456
 	 */
4457
-	function getMultipartAlternative($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$partCalendar=null)
4457
+	function getMultipartAlternative($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$partCalendar = null)
4458 4458
 	{
4459 4459
 		// a multipart/alternative has exactly 2 parts (text and html  OR  text and something else)
4460 4460
 		// sometimes there are 3 parts, when there is an ics/ical attached/included-> we want to show that
4461 4461
 		// as attachment AND as abstracted ical information (we use our notification style here).
4462 4462
 		$partText = $partCalendar = $partHTML = null;
4463
-		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__,"LINE"=>__LINE__,"STRUCTURE"=>$_structure));
4463
+		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__, "LINE"=>__LINE__, "STRUCTURE"=>$_structure));
4464 4464
 		//error_log(__METHOD__.' ('.__LINE__.') ');
4465 4465
 		$ignore_first_part = true;
4466
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4466
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4467 4467
 		{
4468 4468
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type"." ignoreFirstPart:".$ignore_first_part);
4469 4469
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4471,15 +4471,15 @@  discard block
 block discarded – undo
4471 4471
 			if ($ignore_first_part)
4472 4472
 			{
4473 4473
 				$ignore_first_part = false;
4474
-				continue;	// ignore multipart/alternative itself
4474
+				continue; // ignore multipart/alternative itself
4475 4475
 			}
4476 4476
 
4477 4477
 			$mimePart = $_structure->getPart($mime_id);
4478 4478
 
4479
-			switch($mimePart->getPrimaryType())
4479
+			switch ($mimePart->getPrimaryType())
4480 4480
 			{
4481 4481
 				case 'text':
4482
-					switch($mimePart->getSubType())
4482
+					switch ($mimePart->getSubType())
4483 4483
 					{
4484 4484
 						case 'plain':
4485 4485
 							if ($mimePart->getBytes() > 0) $partText = $mimePart;
@@ -4496,7 +4496,7 @@  discard block
 block discarded – undo
4496 4496
 					break;
4497 4497
 
4498 4498
 				case 'multipart':
4499
-					switch($mimePart->getSubType())
4499
+					switch ($mimePart->getSubType())
4500 4500
 					{
4501 4501
 						case 'related':
4502 4502
 						case 'mixed':
@@ -4518,13 +4518,13 @@  discard block
 block discarded – undo
4518 4518
 			}
4519 4519
 		}
4520 4520
 
4521
-		switch($_htmlMode)
4521
+		switch ($_htmlMode)
4522 4522
 		{
4523 4523
 			case 'html_only':
4524 4524
 			case 'always_display':
4525 4525
 				if ($partHTML)
4526 4526
 				{
4527
-					switch($partHTML->getSubType())
4527
+					switch ($partHTML->getSubType())
4528 4528
 					{
4529 4529
 						case 'related':
4530 4530
 							return $this->getMultipartRelated($_uid, $partHTML, $_htmlMode, $_preserveSeen);
@@ -4536,7 +4536,7 @@  discard block
 block discarded – undo
4536 4536
 							return $this->getTextPart($_uid, $partHTML, $_htmlMode, $_preserveSeen);
4537 4537
 					}
4538 4538
 				}
4539
-				elseif ($partText && $_htmlMode=='always_display')
4539
+				elseif ($partText && $_htmlMode == 'always_display')
4540 4540
 				{
4541 4541
 					return $this->getTextPart($_uid, $partText, $_htmlMode, $_preserveSeen);
4542 4542
 				}
@@ -4583,7 +4583,7 @@  discard block
 block discarded – undo
4583 4583
 	 * @param Horde_Mime_Part& $partCalendar =null on return text/calendar part, if one was contained or false
4584 4584
 	 * @return array containing the desired part
4585 4585
 	 */
4586
-	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts=array(), &$partCalendar=null)
4586
+	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts = array(), &$partCalendar = null)
4587 4587
 	{
4588 4588
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlMode<br>";
4589 4589
 		$bodyPart = array();
@@ -4592,7 +4592,7 @@  discard block
 block discarded – undo
4592 4592
 		$ignore_first_part = true;
4593 4593
 		//$skipParts = array();
4594 4594
 		//error_log(__METHOD__.__LINE__.array2string($_structure->contentTypeMap()));
4595
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4595
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4596 4596
 		{
4597 4597
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type");
4598 4598
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4600,9 +4600,9 @@  discard block
 block discarded – undo
4600 4600
 			{
4601 4601
 				$ignore_first_part = false;
4602 4602
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED FirstPart $mime_id: $mime_type");
4603
-				continue;	// ignore multipart/mixed itself
4603
+				continue; // ignore multipart/mixed itself
4604 4604
 			}
4605
-			if (array_key_exists($mime_id,$skipParts))
4605
+			if (array_key_exists($mime_id, $skipParts))
4606 4606
 			{
4607 4607
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED $mime_id: $mime_type");
4608 4608
 				continue;
@@ -4610,11 +4610,11 @@  discard block
 block discarded – undo
4610 4610
 
4611 4611
 			$part = $_structure->getPart($mime_id);
4612 4612
 
4613
-			switch($part->getPrimaryType())
4613
+			switch ($part->getPrimaryType())
4614 4614
 			{
4615 4615
 				case 'multipart':
4616 4616
 					if ($part->getDisposition() == 'attachment') continue;
4617
-					switch($part->getSubType())
4617
+					switch ($part->getSubType())
4618 4618
 					{
4619 4619
 						case 'alternative':
4620 4620
 							return array($this->getMultipartAlternative($_uid, $part, $_htmlMode, $_preserveSeen, $partCalendar));
@@ -4630,15 +4630,15 @@  discard block
 block discarded – undo
4630 4630
 					}
4631 4631
 					break;
4632 4632
 				case 'application':
4633
-					switch($part->getSubType())
4633
+					switch ($part->getSubType())
4634 4634
 					{
4635 4635
 						case 'pgp-encrypted':
4636
-							if (($part = $_structure->getPart($mime_id+1)) &&
4636
+							if (($part = $_structure->getPart($mime_id + 1)) &&
4637 4637
 								$part->getType() == 'application/octet-stream')
4638 4638
 							{
4639 4639
 								$this->fetchPartContents($_uid, $part);
4640
-								$skipParts[$mime_id]=$mime_type;
4641
-								$skipParts[$mime_id+1]=$part->getType();
4640
+								$skipParts[$mime_id] = $mime_type;
4641
+								$skipParts[$mime_id + 1] = $part->getType();
4642 4642
 								$bodyPart[] = array(
4643 4643
 									'body'		=> $part->getContents(array(
4644 4644
 										'stream' => false,
@@ -4652,15 +4652,15 @@  discard block
 block discarded – undo
4652 4652
 					break;
4653 4653
 
4654 4654
 				case 'text':
4655
-					switch($part->getSubType())
4655
+					switch ($part->getSubType())
4656 4656
 					{
4657 4657
 						case 'plain':
4658 4658
 						case 'html':
4659 4659
 						case 'calendar': // inline ics/ical files
4660
-							if($part->getDisposition() != 'attachment')
4660
+							if ($part->getDisposition() != 'attachment')
4661 4661
 							{
4662 4662
 								$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4663
-								$skipParts[$mime_id]=$mime_type;
4663
+								$skipParts[$mime_id] = $mime_type;
4664 4664
 							}
4665 4665
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$part->type."/".$part->subType.' -> BodyPart:'.array2string($bodyPart[count($bodyPart)-1]));
4666 4666
 							break;
@@ -4669,16 +4669,16 @@  discard block
 block discarded – undo
4669 4669
 
4670 4670
 				case 'message':
4671 4671
 					//skip attachments
4672
-					if($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4672
+					if ($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4673 4673
 					{
4674 4674
 						$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4675
-						$skipParts[$mime_id]=$mime_type;
4675
+						$skipParts[$mime_id] = $mime_type;
4676 4676
 					}
4677 4677
 					// do not descend into attached Messages
4678
-					if($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4678
+					if ($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4679 4679
 					{
4680 4680
 						$skipParts[$mime_id.'.0'] = $mime_type;
4681
-						foreach($part->contentTypeMap() as $sub_id => $sub_type){ $skipParts[$sub_id] = $sub_type;}
4681
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { $skipParts[$sub_id] = $sub_type; }
4682 4682
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$_uid.' Part:'.$mime_id.':'.array2string($skipParts));
4683 4683
 						//break 2;
4684 4684
 					}
@@ -4719,13 +4719,13 @@  discard block
 block discarded – undo
4719 4719
 	 * @param boolean $_tryDecodingServerside = true; wether to try to fetch Data with BINARY instead of BODY
4720 4720
 	 * @return string|resource
4721 4721
 	 */
4722
-	function getBodyPart($_uid, $_partID=null, $_folder=null, $_preserveSeen=false, $_stream=false, &$_encoding=null, $_tryDecodingServerside=true)
4722
+	function getBodyPart($_uid, $_partID = null, $_folder = null, $_preserveSeen = false, $_stream = false, &$_encoding = null, $_tryDecodingServerside = true)
4723 4723
 	{
4724
-		if (self::$debug) error_log( __METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4724
+		if (self::$debug) error_log(__METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4725 4725
 
4726 4726
 		if (empty($_folder))
4727 4727
 		{
4728
-			$_folder = (isset($this->sessionData['mailbox'])&&$this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4728
+			$_folder = (isset($this->sessionData['mailbox']) && $this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4729 4729
 		}
4730 4730
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_folder).'/'.$this->icServer->getCurrentMailbox().'/'. $this->sessionData['mailbox']);
4731 4731
 		// querying contents of body part
@@ -4736,11 +4736,11 @@  discard block
 block discarded – undo
4736 4736
 		$fquery = new Horde_Imap_Client_Fetch_Query();
4737 4737
 		$fetchParams = array(
4738 4738
 			'peek' => $_preserveSeen,
4739
-			'decode' => true,	// try decode on server, does NOT neccessary work
4739
+			'decode' => true, // try decode on server, does NOT neccessary work
4740 4740
 		);
4741
-		if ($_tryDecodingServerside===false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4741
+		if ($_tryDecodingServerside === false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4742 4742
 		{
4743
-			$_tryDecodingServerside=false;
4743
+			$_tryDecodingServerside = false;
4744 4744
 			$fetchParams = array(
4745 4745
 				'peek' => $_preserveSeen,
4746 4746
 			);
@@ -4760,12 +4760,12 @@  discard block
 block discarded – undo
4760 4760
 		}
4761 4761
 		// if we get an empty result, server may have trouble fetching data with UID FETCH $_uid (BINARY.PEEK[$_partID])
4762 4762
 		// thus we trigger a second go with UID FETCH $_uid (BODY.PEEK[$_partID])
4763
-		if (empty($partToReturn)&&$_tryDecodingServerside===true)
4763
+		if (empty($partToReturn) && $_tryDecodingServerside === true)
4764 4764
 		{
4765 4765
 			error_log(__METHOD__.__LINE__.' failed to fetch bodyPart in  BINARY. Try BODY');
4766 4766
 			$partToReturn = $this->getBodyPart($_uid, $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, false);
4767 4767
 		}
4768
-		return ($partToReturn?$partToReturn:null);
4768
+		return ($partToReturn ? $partToReturn : null);
4769 4769
 	}
4770 4770
 
4771 4771
 	/**
@@ -4778,13 +4778,13 @@  discard block
 block discarded – undo
4778 4778
 	 * @param boolean $_stream = false true return a stream, false return string
4779 4779
 	 * @return array containing the desired text part, mimeType and charset
4780 4780
 	 */
4781
-	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode='', $_preserveSeen=false, $_stream=false)
4781
+	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode = '', $_preserveSeen = false, $_stream = false)
4782 4782
 	{
4783 4783
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_uid.':'.array2string($_structure).' '.function_backtrace());
4784 4784
 		$bodyPart = array();
4785
-		if (self::$debug) _debug_array(array($_structure,function_backtrace()));
4785
+		if (self::$debug) _debug_array(array($_structure, function_backtrace()));
4786 4786
 
4787
-		if($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4787
+		if ($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4788 4788
 		{
4789 4789
 			$bodyPart = array(
4790 4790
 				'error'		=> 1,
@@ -4831,10 +4831,10 @@  discard block
 block discarded – undo
4831 4831
 	 * @param Horde_Mime_part& $calendar_part =null on return calendar-part or null, if there is none
4832 4832
 	 * @return array containing the message body, mimeType and charset
4833 4833
 	 */
4834
-	function getMessageBody($_uid, $_htmlOptions='', $_partID=null, Horde_Mime_Part $_structure=null, $_preserveSeen = false, $_folder = '', &$calendar_part=null)
4834
+	function getMessageBody($_uid, $_htmlOptions = '', $_partID = null, Horde_Mime_Part $_structure = null, $_preserveSeen = false, $_folder = '', &$calendar_part = null)
4835 4835
 	{
4836 4836
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlOptions, $_partID<br>";
4837
-		if($_htmlOptions != '') {
4837
+		if ($_htmlOptions != '') {
4838 4838
 			$this->htmlOptions = $_htmlOptions;
4839 4839
 		}
4840 4840
 		if (empty($_folder))
@@ -4855,7 +4855,7 @@  discard block
 block discarded – undo
4855 4855
 			return array(
4856 4856
 				array(
4857 4857
 					'error'		=> 1,
4858
-					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions". 'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4858
+					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions".'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4859 4859
 					'mimeType'	=> 'text/plain',
4860 4860
 					'charSet'	=> self::$displayCharset,
4861 4861
 				)
@@ -4868,7 +4868,7 @@  discard block
 block discarded – undo
4868 4868
 			//_debug_array($_structure->getMimeId()); exit;
4869 4869
 		}
4870 4870
 
4871
-		switch($_structure->getPrimaryType())
4871
+		switch ($_structure->getPrimaryType())
4872 4872
 		{
4873 4873
 			case 'application':
4874 4874
 				return array(
@@ -4880,7 +4880,7 @@  discard block
 block discarded – undo
4880 4880
 				);
4881 4881
 
4882 4882
 			case 'multipart':
4883
-				switch($_structure->getSubType())
4883
+				switch ($_structure->getSubType())
4884 4884
 				{
4885 4885
 					case 'alternative':
4886 4886
 						$bodyParts = array($this->getMultipartAlternative($_uid, $_structure, $this->htmlOptions, $_preserveSeen, $calendar_part));
@@ -4915,7 +4915,7 @@  discard block
 block discarded – undo
4915 4915
 				$bodyPart = array();
4916 4916
 				if ($_structure->getDisposition() != 'attachment')
4917 4917
 				{
4918
-					switch($_structure->getSubType())
4918
+					switch ($_structure->getSubType())
4919 4919
 					{
4920 4920
 						case 'calendar':
4921 4921
 							// this is handeled in getTextPart
@@ -4931,11 +4931,11 @@  discard block
 block discarded – undo
4931 4931
 
4932 4932
 			case 'attachment':
4933 4933
 			case 'message':
4934
-				switch($_structure->getSubType())
4934
+				switch ($_structure->getSubType())
4935 4935
 				{
4936 4936
 					case 'rfc822':
4937 4937
 						$newStructure = $_structure->getParts();
4938
-						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]);}
4938
+						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]); }
4939 4939
 						return self::normalizeBodyParts($this->getMessageBody($_uid, $_htmlOptions, $newStructure[0]->getMimeId(), $newStructure[0], $_preserveSeen, $_folder));
4940 4940
 				}
4941 4941
 				break;
@@ -4963,11 +4963,11 @@  discard block
 block discarded – undo
4963 4963
 	{
4964 4964
 		if (is_array($_bodyParts))
4965 4965
 		{
4966
-			foreach($_bodyParts as $singleBodyPart)
4966
+			foreach ($_bodyParts as $singleBodyPart)
4967 4967
 			{
4968 4968
 				if (!isset($singleBodyPart['body'])) {
4969 4969
 					$buff = self::normalizeBodyParts($singleBodyPart);
4970
-					foreach ((array)$buff as $val) { $body2return[] = $val;}
4970
+					foreach ((array)$buff as $val) { $body2return[] = $val; }
4971 4971
 					continue;
4972 4972
 				}
4973 4973
 				$body2return[] = $singleBodyPart;
@@ -4988,14 +4988,14 @@  discard block
 block discarded – undo
4988 4988
 	 * @param boolean $useTidy  switch to use tidy
4989 4989
 	 * @return string a preformatted string with the mails converted to text
4990 4990
 	 */
4991
-	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false,  $useTidy = true)
4991
+	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false, $useTidy = true)
4992 4992
 	{
4993
-		$message='';
4994
-		for($i=0; $i<count($bodyParts); $i++)
4993
+		$message = '';
4994
+		for ($i = 0; $i < count($bodyParts); $i++)
4995 4995
 		{
4996 4996
 			if (!isset($bodyParts[$i]['body'])) {
4997 4997
 				$bodyParts[$i]['body'] = self::getdisplayableBody($mailClass, $bodyParts[$i], $preserveHTML, $useTidy);
4998
-				$message .= empty($bodyParts[$i]['body'])?'':$bodyParts[$i]['body'];
4998
+				$message .= empty($bodyParts[$i]['body']) ? '' : $bodyParts[$i]['body'];
4999 4999
 				continue;
5000 5000
 			}
5001 5001
 			if (isset($bodyParts[$i]['error'])) continue;
@@ -5020,32 +5020,32 @@  discard block
 block discarded – undo
5020 5020
 				'(R)',
5021 5021
 			);
5022 5022
 
5023
-			if(($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
5023
+			if (($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
5024 5024
 				strtoupper($bodyParts[$i]['charSet']) != 'UTF-8')
5025 5025
 			{
5026
-				$bodyParts[$i]['body'] = preg_replace($sar,$rar,$bodyParts[$i]['body']);
5026
+				$bodyParts[$i]['body'] = preg_replace($sar, $rar, $bodyParts[$i]['body']);
5027 5027
 			}
5028 5028
 
5029
-			if ($bodyParts[$i]['charSet']===false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5029
+			if ($bodyParts[$i]['charSet'] === false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
5030 5030
 			// add line breaks to $bodyParts
5031 5031
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
5032
-			$newBody  = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
5032
+			$newBody = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
5033 5033
 			//error_log(__METHOD__.' ('.__LINE__.') '.' MimeType:'.$bodyParts[$i]['mimeType'].'->'.$newBody);
5034 5034
 			$mailClass->activeMimeType = 'text/plain';
5035 5035
 			if ($bodyParts[$i]['mimeType'] == 'text/html') {
5036 5036
 				$mailClass->activeMimeType = $bodyParts[$i]['mimeType'];
5037 5037
 				if (!$preserveHTML)
5038 5038
 				{
5039
-					$alreadyHtmlLawed=false;
5039
+					$alreadyHtmlLawed = false;
5040 5040
 					// as Translation::convert reduces \r\n to \n and purifier eats \n -> peplace it with a single space
5041
-					$newBody = str_replace("\n"," ",$newBody);
5041
+					$newBody = str_replace("\n", " ", $newBody);
5042 5042
 					// convert HTML to text, as we dont want HTML in infologs
5043 5043
 					if ($useTidy && extension_loaded('tidy'))
5044 5044
 					{
5045 5045
 						$tidy = new tidy();
5046
-						$cleaned = $tidy->repairString($newBody, self::$tidy_config,'utf8');
5046
+						$cleaned = $tidy->repairString($newBody, self::$tidy_config, 'utf8');
5047 5047
 						// Found errors. Strip it all so there's some output
5048
-						if($tidy->getStatus() == 2)
5048
+						if ($tidy->getStatus() == 2)
5049 5049
 						{
5050 5050
 							error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$tidy->errorBuffer);
5051 5051
 						}
@@ -5056,7 +5056,7 @@  discard block
 block discarded – undo
5056 5056
 						if (!$preserveHTML)
5057 5057
 						{
5058 5058
 							// filter only the 'body', as we only want that part, if we throw away the html
5059
-							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
5059
+							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
5060 5060
 							if ($matches[2])
5061 5061
 							{
5062 5062
 								$hasOther = true;
@@ -5067,7 +5067,7 @@  discard block
 block discarded – undo
5067 5067
 					else
5068 5068
 					{
5069 5069
 						// htmLawed filter only the 'body'
5070
-						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
5070
+						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
5071 5071
 						if ($matches[2])
5072 5072
 						{
5073 5073
 							$hasOther = true;
@@ -5076,17 +5076,17 @@  discard block
 block discarded – undo
5076 5076
 						$htmLawed = new Html\HtmLawed();
5077 5077
 						// the next line should not be needed, but produces better results on HTML 2 Text conversion,
5078 5078
 						// as we switched off HTMLaweds tidy functionality
5079
-						$newBody = str_replace(array('&amp;amp;','<DIV><BR></DIV>',"<DIV>&nbsp;</DIV>",'<div>&nbsp;</div>'),array('&amp;','<BR>','<BR>','<BR>'),$newBody);
5080
-						$newBody = $htmLawed->run($newBody,self::$htmLawed_config);
5081
-						if ($hasOther && $preserveHTML) $newBody = $matches[1]. $newBody. $matches[3];
5082
-						$alreadyHtmlLawed=true;
5079
+						$newBody = str_replace(array('&amp;amp;', '<DIV><BR></DIV>', "<DIV>&nbsp;</DIV>", '<div>&nbsp;</div>'), array('&amp;', '<BR>', '<BR>', '<BR>'), $newBody);
5080
+						$newBody = $htmLawed->run($newBody, self::$htmLawed_config);
5081
+						if ($hasOther && $preserveHTML) $newBody = $matches[1].$newBody.$matches[3];
5082
+						$alreadyHtmlLawed = true;
5083 5083
 					}
5084 5084
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after purify:'.$newBody);
5085
-					if ($preserveHTML==false) $newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,true,true);
5085
+					if ($preserveHTML == false) $newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, true, true);
5086 5086
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after convertHTMLToText:'.$newBody);
5087
-					if ($preserveHTML==false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
5087
+					if ($preserveHTML == false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
5088 5088
 					/*if (!$alreadyHtmlLawed) */ $mailClass->getCleanHTML($newBody); // remove stuff we regard as unwanted
5089
-					if ($preserveHTML==false) $newBody = str_replace("<br />","\r\n",$newBody);
5089
+					if ($preserveHTML == false) $newBody = str_replace("<br />", "\r\n", $newBody);
5090 5090
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after getClean:'.$newBody);
5091 5091
 				}
5092 5092
 				$message .= $newBody;
@@ -5095,9 +5095,9 @@  discard block
 block discarded – undo
5095 5095
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after specialchars):'.$newBody);
5096 5096
 			//use Mail\Html::convertHTMLToText instead of strip_tags, (even message is plain text) as strip_tags eats away too much
5097 5097
 			//$newBody = strip_tags($newBody); //we need to fix broken tags (or just stuff like "<800 USD/p" )
5098
-			$newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,false,false);
5098
+			$newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, false, false);
5099 5099
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after strip tags):'.$newBody);
5100
-			$newBody = htmlspecialchars_decode($newBody,ENT_QUOTES);
5100
+			$newBody = htmlspecialchars_decode($newBody, ENT_QUOTES);
5101 5101
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body (after hmlspc_decode):'.$newBody);
5102 5102
 			$message .= $newBody;
5103 5103
 			//continue;
@@ -5105,27 +5105,27 @@  discard block
 block discarded – undo
5105 5105
 		return $message;
5106 5106
 	}
5107 5107
 
5108
-	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith=false)
5108
+	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith = false)
5109 5109
 	{
5110 5110
 		$lines = explode("\n", $str);
5111 5111
 		$newStr = '';
5112
-		foreach($lines as $line)
5112
+		foreach ($lines as $line)
5113 5113
 		{
5114 5114
 			// replace tabs by 8 space chars, or any tab only counts one char
5115 5115
 			//$line = str_replace("\t","        ",$line);
5116 5116
 			//$newStr .= wordwrap($line, $cols, $cut);
5117
-			$allowedLength = $cols-strlen($cut);
5117
+			$allowedLength = $cols - strlen($cut);
5118 5118
 			//dont try to break lines with links, chance is we mess up the text is way too big
5119
-			if (strlen($line) > $allowedLength && stripos($line,'href=')===false &&
5120
-				($dontbreaklinesstartingwith==false ||
5119
+			if (strlen($line) > $allowedLength && stripos($line, 'href=') === false &&
5120
+				($dontbreaklinesstartingwith == false ||
5121 5121
 				 ($dontbreaklinesstartingwith &&
5122
-				  strlen($dontbreaklinesstartingwith)>=1 &&
5123
-				  substr($line,0,strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
5122
+				  strlen($dontbreaklinesstartingwith) >= 1 &&
5123
+				  substr($line, 0, strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
5124 5124
 				 )
5125 5125
 				)
5126 5126
 			   )
5127 5127
 			{
5128
-				$s=explode(" ", $line);
5128
+				$s = explode(" ", $line);
5129 5129
 				$line = "";
5130 5130
 				$linecnt = 0;
5131 5131
 				foreach ($s as &$v) {
@@ -5133,22 +5133,22 @@  discard block
 block discarded – undo
5133 5133
 					// only break long words within the wordboundaries,
5134 5134
 					// but it may destroy links, so we check for href and dont do it if we find one
5135 5135
 					// we check for any html within the word, because we do not want to break html by accident
5136
-					if($cnt > $allowedLength && stripos($v,'href=')===false && stripos($v,'onclick=')===false && $cnt == strlen(html_entity_decode($v)))
5136
+					if ($cnt > $allowedLength && stripos($v, 'href=') === false && stripos($v, 'onclick=') === false && $cnt == strlen(html_entity_decode($v)))
5137 5137
 					{
5138
-						$v=wordwrap($v, $allowedLength, $cut, true);
5138
+						$v = wordwrap($v, $allowedLength, $cut, true);
5139 5139
 					}
5140 5140
 					// the rest should be broken at the start of the new word that exceeds the limit
5141
-					if ($linecnt+$cnt > $allowedLength) {
5142
-						$v=$cut.$v;
5141
+					if ($linecnt + $cnt > $allowedLength) {
5142
+						$v = $cut.$v;
5143 5143
 						#$linecnt = 0;
5144
-						$linecnt =strlen($v)-strlen($cut);
5144
+						$linecnt = strlen($v) - strlen($cut);
5145 5145
 					} else {
5146 5146
 						$linecnt += $cnt;
5147 5147
 					}
5148 5148
 					if (strlen($v)) $line .= (strlen($line) ? " " : "").$v;
5149 5149
 				}
5150 5150
 			}
5151
-			$newStr .= $line . "\n";
5151
+			$newStr .= $line."\n";
5152 5152
 		}
5153 5153
 		return $newStr;
5154 5154
 	}
@@ -5163,12 +5163,12 @@  discard block
 block discarded – undo
5163 5163
 	 * @param boolean $_useHeaderInsteadOfEnvelope - force getMessageHeader method to be used for fetching Envelope Information
5164 5164
 	 * @return array the message header
5165 5165
 	 */
5166
-	function getMessageEnvelope($_uid, $_partID = '',$decode=false, $_folder='', $_useHeaderInsteadOfEnvelope=false)
5166
+	function getMessageEnvelope($_uid, $_partID = '', $decode = false, $_folder = '', $_useHeaderInsteadOfEnvelope = false)
5167 5167
 	{
5168 5168
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder".function_backtrace());
5169
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5169
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5170 5170
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder");
5171
-		if((empty($_partID)||$_partID=='null')&&$_useHeaderInsteadOfEnvelope===false) {
5171
+		if ((empty($_partID) || $_partID == 'null') && $_useHeaderInsteadOfEnvelope === false) {
5172 5172
 			$uidsToFetch = new Horde_Imap_Client_Ids();
5173 5173
 			if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5174 5174
 			$uidsToFetch->add($_uid);
@@ -5181,7 +5181,7 @@  discard block
 block discarded – undo
5181 5181
 				'ids' => $uidsToFetch,
5182 5182
 			));
5183 5183
 			if (is_object($headersNew)) {
5184
-				foreach($headersNew as &$_headerObject) {
5184
+				foreach ($headersNew as &$_headerObject) {
5185 5185
 					$env = $_headerObject->getEnvelope();
5186 5186
 					//_debug_array($envFields->singleFields());
5187 5187
 					$singleFields = $envFields->singleFields();
@@ -5196,34 +5196,34 @@  discard block
 block discarded – undo
5196 5196
 							case 'bcc':
5197 5197
 							case 'sender':
5198 5198
 								//error_log(__METHOD__.' ('.__LINE__.') '.$v.'->'.array2string($env->$v->addresses));
5199
-								$envelope[$v]=$env->$v->addresses;
5199
+								$envelope[$v] = $env->$v->addresses;
5200 5200
 								$address = array();
5201 5201
 								if (!is_array($envelope[$v])) break;
5202 5202
 								foreach ($envelope[$v] as $k => $ad)
5203 5203
 								{
5204
-									if (stripos($ad,'@')===false)
5204
+									if (stripos($ad, '@') === false)
5205 5205
 									{
5206
-										$remember=$k;
5206
+										$remember = $k;
5207 5207
 									}
5208 5208
 									else
5209 5209
 									{
5210
-										$address[] = (!is_null($remember)?$envelope[$v][$remember].' ':'').$ad;
5211
-										$remember=null;
5210
+										$address[] = (!is_null($remember) ? $envelope[$v][$remember].' ' : '').$ad;
5211
+										$remember = null;
5212 5212
 									}
5213 5213
 								}
5214 5214
 								$envelope[$v] = $address;
5215 5215
 								break;
5216 5216
 							case 'date':
5217
-								$envelope[$v]=DateTime::to($env->$v);
5217
+								$envelope[$v] = DateTime::to($env->$v);
5218 5218
 								break;
5219 5219
 							default:
5220
-								$envelope[$v]=$env->$v;
5220
+								$envelope[$v] = $env->$v;
5221 5221
 						}
5222 5222
 					}
5223
-					$envelope['size']=$_headerObject->getSize();
5223
+					$envelope['size'] = $_headerObject->getSize();
5224 5224
 				}
5225 5225
 			}
5226
-			$envelope = array_change_key_case($envelope,CASE_UPPER);
5226
+			$envelope = array_change_key_case($envelope, CASE_UPPER);
5227 5227
 			//if ($decode) _debug_array($envelope);
5228 5228
 			//error_log(__METHOD__.' ('.__LINE__.') '.array2string($envelope));
5229 5229
 			if ($decode)
@@ -5231,19 +5231,19 @@  discard block
 block discarded – undo
5231 5231
 				foreach ($envelope as $key => $rvV)
5232 5232
 				{
5233 5233
 					//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5234
-					$envelope[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5234
+					$envelope[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5235 5235
 				}
5236 5236
 			}
5237 5237
 			return $envelope;
5238 5238
 		} else {
5239 5239
 
5240
-			$headers = $this->getMessageHeader($_uid, $_partID, true,true,$_folder);
5240
+			$headers = $this->getMessageHeader($_uid, $_partID, true, true, $_folder);
5241 5241
 
5242 5242
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($headers));
5243 5243
 			//_debug_array($headers);
5244 5244
 			$newData = array(
5245 5245
 				'DATE'		=> $headers['DATE'],
5246
-				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']):$headers['SUBJECT']),
5246
+				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']) : $headers['SUBJECT']),
5247 5247
 				'MESSAGE_ID'	=> $headers['MESSAGE-ID']
5248 5248
 			);
5249 5249
 			if (isset($headers['IN-REPLY-TO'])) $newData['IN-REPLY-TO'] = $headers['IN-REPLY-TO'];
@@ -5254,11 +5254,11 @@  discard block
 block discarded – undo
5254 5254
 			if (isset($headers['SIZE'])) $newData['SIZE'] = $headers['SIZE'];
5255 5255
 			//_debug_array($newData);
5256 5256
 			$recepientList = array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO');
5257
-			foreach($recepientList as $recepientType) {
5258
-				if(isset($headers[$recepientType])) {
5259
-					if ($decode) $headers[$recepientType] =  self::decode_header($headers[$recepientType],true);
5257
+			foreach ($recepientList as $recepientType) {
5258
+				if (isset($headers[$recepientType])) {
5259
+					if ($decode) $headers[$recepientType] = self::decode_header($headers[$recepientType], true);
5260 5260
 					//error_log(__METHOD__.__LINE__." ".$recepientType."->".array2string($headers[$recepientType]));
5261
-					foreach(self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5261
+					foreach (self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5262 5262
 						$addressData = array(
5263 5263
 							'PERSONAL_NAME'		=> $singleAddress->personal ? $singleAddress->personal : 'NIL',
5264 5264
 							'AT_DOMAIN_LIST'	=> $singleAddress->adl ? $singleAddress->adl : 'NIL',
@@ -5266,15 +5266,15 @@  discard block
 block discarded – undo
5266 5266
 							'HOST_NAME'		=> $singleAddress->host ? $singleAddress->host : 'NIL',
5267 5267
 							'EMAIL'			=> $singleAddress->host ? $singleAddress->mailbox.'@'.$singleAddress->host : $singleAddress->mailbox,
5268 5268
 						);
5269
-						if($addressData['PERSONAL_NAME'] != 'NIL') {
5269
+						if ($addressData['PERSONAL_NAME'] != 'NIL') {
5270 5270
 							$addressData['RFC822_EMAIL'] = imap_rfc822_write_address($singleAddress->mailbox, $singleAddress->host, $singleAddress->personal);
5271 5271
 						} else {
5272 5272
 							$addressData['RFC822_EMAIL'] = 'NIL';
5273 5273
 						}
5274
-						$newData[$recepientType][] = ($addressData['RFC822_EMAIL']!='NIL'?$addressData['RFC822_EMAIL']:$addressData['EMAIL']);//$addressData;
5274
+						$newData[$recepientType][] = ($addressData['RFC822_EMAIL'] != 'NIL' ? $addressData['RFC822_EMAIL'] : $addressData['EMAIL']); //$addressData;
5275 5275
 					}
5276 5276
 				} else {
5277
-					if($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5277
+					if ($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5278 5278
 						$newData[$recepientType] = $newData['FROM'];
5279 5279
 					} else {
5280 5280
 						$newData[$recepientType] = array();
@@ -5296,10 +5296,10 @@  discard block
 block discarded – undo
5296 5296
 	 * @param string $_folder folder to work on
5297 5297
 	 * @return array|Horde_Mime_Headers message header as array or object
5298 5298
 	 */
5299
-	function getMessageHeader($_uid, $_partID = '',$decode=false, $preserveUnSeen=false, $_folder='')
5299
+	function getMessageHeader($_uid, $_partID = '', $decode = false, $preserveUnSeen = false, $_folder = '')
5300 5300
 	{
5301 5301
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$_uid.', '.$_partID.', '.$decode.', '.$preserveUnSeen.', '.$_folder);
5302
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5302
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5303 5303
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5304 5304
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5305 5305
 		$uidsToFetch->add($_uid);
@@ -5307,7 +5307,7 @@  discard block
 block discarded – undo
5307 5307
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5308 5308
 		if ($_partID != '')
5309 5309
 		{
5310
-			$fquery->headerText(array('id'=>$_partID,'peek'=>$preserveUnSeen));
5310
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>$preserveUnSeen));
5311 5311
 			$fquery->structure();
5312 5312
 		}
5313 5313
 		else
@@ -5320,18 +5320,18 @@  discard block
 block discarded – undo
5320 5320
 			'ids' => $uidsToFetch,
5321 5321
 		));
5322 5322
 		if (is_object($headersNew)) {
5323
-			foreach($headersNew as $_fetchObject)
5323
+			foreach ($headersNew as $_fetchObject)
5324 5324
 			{
5325
-				$headers = $_fetchObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5325
+				$headers = $_fetchObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5326 5326
 				if ($_partID != '')
5327 5327
 				{
5328 5328
 					$mailStructureObject = $_fetchObject->getStructure();
5329 5329
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5330 5330
 					{
5331
-						if ($mime_id==$_partID)
5331
+						if ($mime_id == $_partID)
5332 5332
 						{
5333 5333
 							//error_log(__METHOD__.' ('.__LINE__.') '."$mime_id == $_partID".array2string($_headerObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray()));
5334
-							$headers = $_fetchObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5334
+							$headers = $_fetchObject->getHeaderText($mime_id, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5335 5335
 							break;
5336 5336
 						}
5337 5337
 					}
@@ -5344,15 +5344,15 @@  discard block
 block discarded – undo
5344 5344
 				if (is_object($headers)) $headers->setUserAgent('EGroupware API '.$GLOBALS['egw_info']['server']['versions']['phpgwapi']);
5345 5345
 				return $headers;
5346 5346
 			}
5347
-			$retValue = is_object($headers) ? $headers->toArray():array();
5347
+			$retValue = is_object($headers) ? $headers->toArray() : array();
5348 5348
 			if ($size) $retValue['size'] = $size;
5349 5349
 		}
5350
-		$retValue = array_change_key_case($retValue,CASE_UPPER);
5350
+		$retValue = array_change_key_case($retValue, CASE_UPPER);
5351 5351
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue));
5352 5352
 		// if SUBJECT is an array, use thelast one, as we assume something with the unfolding for the subject did not work
5353 5353
 		if (is_array($retValue['SUBJECT']))
5354 5354
 		{
5355
-			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT'])-1];
5355
+			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT']) - 1];
5356 5356
 		}
5357 5357
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($decode ? self::decode_header($retValue,true):$retValue));
5358 5358
 		if ($decode)
@@ -5360,7 +5360,7 @@  discard block
 block discarded – undo
5360 5360
 			foreach ($retValue as $key => $rvV)
5361 5361
 			{
5362 5362
 				//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5363
-				$retValue[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5363
+				$retValue[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5364 5364
 			}
5365 5365
 		}
5366 5366
 		return $retValue;
@@ -5377,14 +5377,14 @@  discard block
 block discarded – undo
5377 5377
 	function getMessageRawHeader($_uid, $_partID = '', $_folder = '')
5378 5378
 	{
5379 5379
 		static $rawHeaders;
5380
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5380
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5381 5381
 		//error_log(__METHOD__.' ('.__LINE__.') '." Try Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5382 5382
 
5383
-		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);
5384
-		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5383
+		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);
5384
+		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5385 5385
 		{
5386 5386
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5387
-			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5387
+			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5388 5388
 		}
5389 5389
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5390 5390
 		$uid = $_uid;
@@ -5394,7 +5394,7 @@  discard block
 block discarded – undo
5394 5394
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5395 5395
 		if ($_partID != '')
5396 5396
 		{
5397
-			$fquery->headerText(array('id'=>$_partID,'peek'=>true));
5397
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>true));
5398 5398
 			$fquery->structure();
5399 5399
 		}
5400 5400
 		else
@@ -5405,14 +5405,14 @@  discard block
 block discarded – undo
5405 5405
 			'ids' => $uidsToFetch,
5406 5406
 		));
5407 5407
 		if (is_object($headersNew)) {
5408
-			foreach($headersNew as &$_headerObject) {
5408
+			foreach ($headersNew as &$_headerObject) {
5409 5409
 				$retValue = $_headerObject->getHeaderText();
5410 5410
 				if ($_partID != '')
5411 5411
 				{
5412 5412
 					$mailStructureObject = $_headerObject->getStructure();
5413 5413
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5414 5414
 					{
5415
-						if ($mime_id==$_partID)
5415
+						if ($mime_id == $_partID)
5416 5416
 						{
5417 5417
 							$retValue = $_headerObject->getHeaderText($mime_id);
5418 5418
 						}
@@ -5420,8 +5420,8 @@  discard block
 block discarded – undo
5420 5420
 				}
5421 5421
 			}
5422 5422
 		}
5423
-		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]=$retValue;
5424
-		Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']),$rawHeaders,60*60*1);
5423
+		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $retValue;
5424
+		Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']), $rawHeaders, 60 * 60 * 1);
5425 5425
 		return $retValue;
5426 5426
 	}
5427 5427
 
@@ -5434,25 +5434,25 @@  discard block
 block discarded – undo
5434 5434
 	{
5435 5435
 		$style = '';
5436 5436
 		if (empty($_bodyParts)) return "";
5437
-		foreach((array)$_bodyParts as $singleBodyPart) {
5437
+		foreach ((array)$_bodyParts as $singleBodyPart) {
5438 5438
 			if (!isset($singleBodyPart['body'])) {
5439 5439
 				$singleBodyPart['body'] = self::getStyles($singleBodyPart);
5440 5440
 				$style .= $singleBodyPart['body'];
5441 5441
 				continue;
5442 5442
 			}
5443 5443
 
5444
-			if ($singleBodyPart['charSet']===false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5444
+			if ($singleBodyPart['charSet'] === false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5445 5445
 			$singleBodyPart['body'] = Translation::convert(
5446 5446
 				$singleBodyPart['body'],
5447 5447
 				strtolower($singleBodyPart['charSet'])
5448 5448
 			);
5449 5449
 			$ct = 0;
5450
-			$newStyle=array();
5451
-			if (stripos($singleBodyPart['body'],'<style')!==false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5452
-			if ($ct>0)
5450
+			$newStyle = array();
5451
+			if (stripos($singleBodyPart['body'], '<style') !== false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5452
+			if ($ct > 0)
5453 5453
 			{
5454 5454
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$ct.'#'.array2string($newStyle));
5455
-				$style2buffer = implode('',$newStyle[0]);
5455
+				$style2buffer = implode('', $newStyle[0]);
5456 5456
 			}
5457 5457
 			if ($style2buffer && strtoupper(self::$displayCharset) == 'UTF-8')
5458 5458
 			{
@@ -5460,7 +5460,7 @@  discard block
 block discarded – undo
5460 5460
 				$test = json_encode($style2buffer);
5461 5461
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$test.'# ->'.strlen($style2buffer).' Error:'.json_last_error());
5462 5462
 				//if (json_last_error() != JSON_ERROR_NONE && strlen($style2buffer)>0)
5463
-				if ($test=="null" && strlen($style2buffer)>0)
5463
+				if ($test == "null" && strlen($style2buffer) > 0)
5464 5464
 				{
5465 5465
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
5466 5466
 					error_log(__METHOD__.' ('.__LINE__.') '.' Found Invalid sequence for utf-8 in CSS:'.$style2buffer.' Charset Reported:'.$singleBodyPart['charSet'].' Carset Detected:'.Translation::detect_encoding($style2buffer));
@@ -5471,19 +5471,19 @@  discard block
 block discarded – undo
5471 5471
 		}
5472 5472
 		// clean out comments and stuff
5473 5473
 		$search = array(
5474
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
5474
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
5475 5475
 //			'@<!--[\s\S]*?[ \t\n\r]*-->@',   // Strip multi-line comments including CDATA
5476 5476
 //			'@<!--[\s\S]*?[ \t\n\r]*--@',    // Strip broken multi-line comments including CDATA
5477 5477
 		);
5478
-		$style = preg_replace($search,"",$style);
5478
+		$style = preg_replace($search, "", $style);
5479 5479
 
5480 5480
 		// CSS Security
5481 5481
 		// http://code.google.com/p/browsersec/wiki/Part1#Cascading_stylesheets
5482
-		$css = preg_replace('/(javascript|expression|-moz-binding)/i','',$style);
5483
-		if (stripos($css,'script')!==false) Mail\Html::replaceTagsCompletley($css,'script'); // Strip out script that may be included
5482
+		$css = preg_replace('/(javascript|expression|-moz-binding)/i', '', $style);
5483
+		if (stripos($css, 'script') !== false) Mail\Html::replaceTagsCompletley($css, 'script'); // Strip out script that may be included
5484 5484
 		// 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
5485 5485
 		// as the comments as <!-- styledefinition --> in stylesheet are outdated, and ck-editor does not understand it, we remove it
5486
-		$css = str_replace(array(':','<!--','-->'),array(': ','',''),$css);
5486
+		$css = str_replace(array(':', '<!--', '-->'), array(': ', '', ''), $css);
5487 5487
 		//error_log(__METHOD__.' ('.__LINE__.') '.$css);
5488 5488
 		// TODO: we may have to strip urls and maybe comments and ifs
5489 5489
 		return $css;
@@ -5498,16 +5498,16 @@  discard block
 block discarded – undo
5498 5498
 	 * @param boolean $_stream =false true: return a stream, false: return string, stream suppresses any caching
5499 5499
 	 * @return string the message body
5500 5500
 	 */
5501
-	function getMessageRawBody($_uid, $_partID = '', $_folder='', $_stream=false)
5501
+	function getMessageRawBody($_uid, $_partID = '', $_folder = '', $_stream = false)
5502 5502
 	{
5503 5503
 		//TODO: caching einbauen static!
5504 5504
 		static $rawBody;
5505 5505
 		if (is_null($rawBody)) $rawBody = array();
5506
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5507
-		if (!$_stream && isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5506
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5507
+		if (!$_stream && isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5508 5508
 		{
5509 5509
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Body $_uid, $_partID in Folder $_folder");
5510
-			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5510
+			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5511 5511
 		}
5512 5512
 
5513 5513
 		$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -5520,13 +5520,13 @@  discard block
 block discarded – undo
5520 5520
 		if ($_partID != '')
5521 5521
 		{
5522 5522
 			$fquery->structure();
5523
-			$fquery->bodyPart($_partID,array('peek'=>true));
5523
+			$fquery->bodyPart($_partID, array('peek'=>true));
5524 5524
 		}
5525 5525
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5526 5526
 			'ids' => $uidsToFetch,
5527 5527
 		));
5528 5528
 		if (is_object($headersNew)) {
5529
-			foreach($headersNew as &$_headerObject) {
5529
+			foreach ($headersNew as &$_headerObject) {
5530 5530
 				$body = $_headerObject->getFullMsg($_stream);
5531 5531
 				if ($_partID != '')
5532 5532
 				{
@@ -5534,7 +5534,7 @@  discard block
 block discarded – undo
5534 5534
 					//_debug_array($mailStructureObject->contentTypeMap());
5535 5535
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5536 5536
 					{
5537
-						if ($mime_id==$_partID)
5537
+						if ($mime_id == $_partID)
5538 5538
 						{
5539 5539
 							$body = $_headerObject->getBodyPart($mime_id, $_stream);
5540 5540
 						}
@@ -5545,7 +5545,7 @@  discard block
 block discarded – undo
5545 5545
 		//error_log(__METHOD__.' ('.__LINE__.') '."[$this->icServer->ImapServerId][$_folder][$_uid][".(empty($_partID)?'NIL':$_partID)."]");
5546 5546
 		if (!$_stream)
5547 5547
 		{
5548
-			$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)] = $body;
5548
+			$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $body;
5549 5549
 		}
5550 5550
 		return $body;
5551 5551
 	}
@@ -5560,13 +5560,13 @@  discard block
 block discarded – undo
5560 5560
 	 * @param Horde_Imap_Client_Fetch_Query $fquery=null default query just structure
5561 5561
 	 * @return Horde_Mime_Part
5562 5562
 	 */
5563
-	function getStructure($_uid, $_partID=null, $_folder=null, $_preserveSeen=false)
5563
+	function getStructure($_uid, $_partID = null, $_folder = null, $_preserveSeen = false)
5564 5564
 	{
5565
-		if (self::$debug) error_log( __METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5565
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5566 5566
 
5567 5567
 		if (empty($_folder))
5568 5568
 		{
5569
-			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5569
+			$_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5570 5570
 		}
5571 5571
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5572 5572
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
@@ -5584,7 +5584,7 @@  discard block
 block discarded – undo
5584 5584
 				'ids' => $uidsToFetch,
5585 5585
 			))->first();
5586 5586
 
5587
-			return is_object($mail)?$mail->getStructure():null;
5587
+			return is_object($mail) ? $mail->getStructure() : null;
5588 5588
 		}
5589 5589
 		catch (\Exception $e)
5590 5590
 		{
@@ -5607,14 +5607,14 @@  discard block
 block discarded – undo
5607 5607
 	 * @param string $_folder folder to work on
5608 5608
 	 * @return array  an array of information about the attachment: array of array(name, size, mimeType, partID, encoding)
5609 5609
 	 */
5610
-	function getMessageAttachments($_uid, $_partID=null, Horde_Mime_Part $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=false, $resolveTNEF=true, $_folder='')
5610
+	function getMessageAttachments($_uid, $_partID = null, Horde_Mime_Part $_structure = null, $fetchEmbeddedImages = true, $fetchTextCalendar = false, $resolveTNEF = true, $_folder = '')
5611 5611
 	{
5612
-		if (self::$debug) error_log( __METHOD__.":$_uid, $_partID");
5613
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5612
+		if (self::$debug) error_log(__METHOD__.":$_uid, $_partID");
5613
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5614 5614
 		$attachments = array();
5615 5615
 		if (!isset($_structure))
5616 5616
 		{
5617
-			$_structure = $this->getStructure($_uid, $_partID,$_folder,true);
5617
+			$_structure = $this->getStructure($_uid, $_partID, $_folder, true);
5618 5618
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.print_r($_structure->contentTypeMap(),true));
5619 5619
 		}
5620 5620
 		if (!$_structure || !$_structure->contentTypeMap()) return array();
@@ -5622,7 +5622,7 @@  discard block
 block discarded – undo
5622 5622
 		$skipParts = array();
5623 5623
 		$tnefParts = array();
5624 5624
 		$skip = 0;
5625
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
5625
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
5626 5626
 		{
5627 5627
 			// skip multipart/encrypted incl. its two sub-parts, as we show 2. sub-part as body to be decrypted client-side
5628 5628
 			if ($mime_type == 'multipart/encrypted')
@@ -5630,7 +5630,7 @@  discard block
 block discarded – undo
5630 5630
 				$skip = 2;
5631 5631
 				continue;
5632 5632
 			}
5633
-			elseif($skip)
5633
+			elseif ($skip)
5634 5634
 			{
5635 5635
 				$skip--;
5636 5636
 				continue;
@@ -5644,10 +5644,10 @@  discard block
 block discarded – undo
5644 5644
 			$partPrimaryType = $part->getPrimaryType();
5645 5645
 			// we only want to retrieve the attachments of the current mail, not those of possible
5646 5646
 			// attached mails
5647
-			if ($mime_type=='message/rfc822' && $_partID!=$mime_id)
5647
+			if ($mime_type == 'message/rfc822' && $_partID != $mime_id)
5648 5648
 			{
5649 5649
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
5650
-				foreach($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
5650
+				foreach ($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
5651 5651
 			}
5652 5652
 			if (empty($partDisposition) && $partPrimaryType != 'multipart' && $partPrimaryType != 'text')
5653 5653
 			{
@@ -5655,27 +5655,27 @@  discard block
 block discarded – undo
5655 5655
 				// attachment with no link to show the attachment inline.
5656 5656
 				// Considering this: we "list" everything that matches the above criteria
5657 5657
 				// as attachment in order to not loose/miss information on our data
5658
-				$partDisposition='attachment';
5658
+				$partDisposition = 'attachment';
5659 5659
 			}
5660 5660
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($skipParts));
5661
-			if (array_key_exists($mime_id,$skipParts)) continue;
5661
+			if (array_key_exists($mime_id, $skipParts)) continue;
5662 5662
 
5663 5663
 			if ($partDisposition == 'attachment' ||
5664
-				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId()=='') ||
5664
+				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId() == '') ||
5665 5665
 				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType != 'image' && $partPrimaryType != 'text' && $partPrimaryType != 'multipart') ||
5666
-				($mime_type=='image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5666
+				($mime_type == 'image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5667 5667
 				($fetchEmbeddedImages && ($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image') ||
5668 5668
 				($fetchTextCalendar && $partPrimaryType == 'text' && $part->getSubType() == 'calendar'))
5669 5669
 			{
5670 5670
 				// if type is message/rfc822 and _partID is given, and MimeID equals partID
5671 5671
 				// we attempt to fetch "ourselves"
5672
-				if ($_partID==$part->getMimeId() && $part->getPrimaryType()=='message') continue;
5672
+				if ($_partID == $part->getMimeId() && $part->getPrimaryType() == 'message') continue;
5673 5673
 				$attachment = $part->getAllDispositionParameters();
5674 5674
 				$attachment['disposition'] = $part->getDisposition();
5675 5675
 				$attachment['mimeType'] = $mime_type;
5676 5676
 				$attachment['uid'] = $_uid;
5677 5677
 				$attachment['partID'] = $mime_id;
5678
-				if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5678
+				if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5679 5679
 				if ($fetchTextCalendar)
5680 5680
 				{
5681 5681
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part->getAllContentTypeParameters()));
@@ -5685,11 +5685,11 @@  discard block
 block discarded – undo
5685 5685
 				}
5686 5686
 				$attachment['size'] = $part->getBytes();
5687 5687
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5688
-				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);
5688
+				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);
5689 5689
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($attachment));
5690 5690
 				//typical winmail.dat attachment is
5691 5691
 				//Array([size] => 1462762[filename] => winmail.dat[mimeType] => application/ms-tnef[uid] => 100[partID] => 2[name] => winmail.dat)
5692
-				if ($resolveTNEF && ($attachment['mimeType']=='application/ms-tnef' || !strcasecmp($attachment['name'],'winmail.dat')))
5692
+				if ($resolveTNEF && ($attachment['mimeType'] == 'application/ms-tnef' || !strcasecmp($attachment['name'], 'winmail.dat')))
5693 5693
 				{
5694 5694
 					$tnefParts[] = $attachment;
5695 5695
 				}
@@ -5704,31 +5704,31 @@  discard block
 block discarded – undo
5704 5704
 			//error_log(__METHOD__.__LINE__.array2string($tnefParts));
5705 5705
 			foreach ($tnefParts as $k => $tnp)
5706 5706
 			{
5707
-				$tnefResolved=false;
5708
-				$tnef_data = $this->getAttachment($tnp['uid'],$tnp['partID'],$k,false);
5707
+				$tnefResolved = false;
5708
+				$tnef_data = $this->getAttachment($tnp['uid'], $tnp['partID'], $k, false);
5709 5709
 				$myTnef = $this->tnef_decoder($tnef_data['attachment']);
5710 5710
 				//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
5711 5711
 				// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
5712 5712
 				// we need to build Something that meets the needs
5713 5713
 				if ($myTnef)
5714 5714
 				{
5715
-					foreach($myTnef->getParts() as $mime_id => $part)
5715
+					foreach ($myTnef->getParts() as $mime_id => $part)
5716 5716
 					{
5717
-						$tnefResolved=true;
5717
+						$tnefResolved = true;
5718 5718
 						$attachment = $part->getAllDispositionParameters();
5719 5719
 						$attachment['disposition'] = $part->getDisposition();
5720 5720
 						$attachment['mimeType'] = $part->getType();
5721 5721
 						$attachment['uid'] = $tnp['uid'];
5722 5722
 						$attachment['partID'] = $tnp['partID'];
5723 5723
 						$attachment['is_winmail'] = $tnp['uid'].'@'.$tnp['partID'].'@'.$mime_id;
5724
-						if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5724
+						if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5725 5725
 						$attachment['size'] = $part->getBytes();
5726 5726
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5727
-						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']);
5727
+						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']);
5728 5728
 						$attachments[] = $attachment;
5729 5729
 					}
5730 5730
 				}
5731
-				if ($tnefResolved===false) $attachments[]=$tnp;
5731
+				if ($tnefResolved === false) $attachments[] = $tnp;
5732 5732
 			}
5733 5733
 		}
5734 5734
 		//error_log(__METHOD__.__LINE__.array2string($attachments));
@@ -5743,9 +5743,9 @@  discard block
 block discarded – undo
5743 5743
 	 * @return boolean|Horde_Mime_part Multipart/Mixed part decoded attachments |
5744 5744
 	 *	return false if there's no attachments or failure
5745 5745
 	 */
5746
-	public function tnef_decoder( $data )
5746
+	public function tnef_decoder($data)
5747 5747
 	{
5748
-		foreach(array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5748
+		foreach (array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5749 5749
 		{
5750 5750
 			if (!class_exists($class))
5751 5751
 			{
@@ -5777,7 +5777,7 @@  discard block
 block discarded – undo
5777 5777
 				$tmp_part->setContents($data['stream']);
5778 5778
 				$tmp_part->setDescription($data['name']);
5779 5779
 
5780
-				$type = $data['type'] . '/' . $data['subtype'];
5780
+				$type = $data['type'].'/'.$data['subtype'];
5781 5781
 				if (in_array($type, array('application/octet-stream', 'application/base64')))
5782 5782
 				{
5783 5783
 					$type = Horde_Mime_Magic::filenameToMIME($data['name']);
@@ -5820,24 +5820,24 @@  discard block
 block discarded – undo
5820 5820
 	 *
5821 5821
 	 * @return array returns an array of all resolved embeded attachments from winmail.dat
5822 5822
 	 */
5823
-	function getTnefAttachments ($_uid, $_partID, $_stream=false)
5823
+	function getTnefAttachments($_uid, $_partID, $_stream = false)
5824 5824
 	{
5825
-		$tnef_data = $this->getAttachment($_uid, $_partID,0,false);
5825
+		$tnef_data = $this->getAttachment($_uid, $_partID, 0, false);
5826 5826
 		$tnef_parts = $this->tnef_decoder($tnef_data['attachment']);
5827 5827
 		$attachments = array();
5828 5828
 		if ($tnef_parts)
5829 5829
 		{
5830
-			foreach($tnef_parts->getParts() as $mime_id => $part)
5830
+			foreach ($tnef_parts->getParts() as $mime_id => $part)
5831 5831
 			{
5832 5832
 
5833 5833
 				$attachment = $part->getAllDispositionParameters();
5834 5834
 				$attachment['mimeType'] = $part->getType();
5835
-				if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5835
+				if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5836 5836
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5837 5837
 				if (empty($attachment['filename']))
5838 5838
 				{
5839
-					$attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?
5840
-						$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5839
+					$attachment['filename'] = (isset($attachment['cid']) && !empty($attachment['cid']) ?
5840
+						$attachment['cid'] : lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5841 5841
 				}
5842 5842
 
5843 5843
 				$attachment['attachment'] = $part->getContents(array('stream'=>$_stream));
@@ -5861,10 +5861,10 @@  discard block
 block discarded – undo
5861 5861
 	 *
5862 5862
 	 * @return array
5863 5863
 	 */
5864
-	function getAttachment($_uid, $_partID, $_winmail_nr=0, $_returnPart=true, $_stream=false, $_folder=null)
5864
+	function getAttachment($_uid, $_partID, $_winmail_nr = 0, $_returnPart = true, $_stream = false, $_folder = null)
5865 5865
 	{
5866 5866
 		//error_log(__METHOD__.__LINE__."Uid:$_uid, PartId:$_partID, WinMailNr:$_winmail_nr, ReturnPart:$_returnPart, Stream:$_stream, Folder:$_folder".function_backtrace());
5867
-		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5867
+		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5868 5868
 
5869 5869
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5870 5870
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
@@ -5877,36 +5877,36 @@  discard block
 block discarded – undo
5877 5877
 			'ids' => $uidsToFetch,
5878 5878
 		));
5879 5879
 		if (is_object($headersNew)) {
5880
-			foreach($headersNew as $id=>$_headerObject) {
5880
+			foreach ($headersNew as $id=>$_headerObject) {
5881 5881
 				$body = $_headerObject->getFullMsg();
5882 5882
 				if ($_partID != '')
5883 5883
 				{
5884 5884
 					$mailStructureObject = $_headerObject->getStructure();
5885 5885
 					$mailStructureObject->contentTypeMap();
5886 5886
 					$part = $mailStructureObject->getPart($_partID);
5887
-					$partDisposition = ($part?$part->getDisposition():'failed');
5888
-					if ($partDisposition=='failed')
5887
+					$partDisposition = ($part ? $part->getDisposition() : 'failed');
5888
+					if ($partDisposition == 'failed')
5889 5889
 					{
5890 5890
 						error_log(__METHOD__.'('.__LINE__.'):'.array2string($_uid).','.$_partID.' ID:'.$id.' HObject:'.array2string($_headerObject).' StructureObject:'.array2string($mailStructureObject->contentTypeMap()).'->'.function_backtrace());
5891 5891
 					}
5892 5892
 					// if $partDisposition is empty, we assume attachment, and hope that the function
5893 5893
 					// itself is only triggered to fetch attachments
5894
-					if (empty($partDisposition)) $partDisposition='attachment';
5895
-					if ($part && ($partDisposition=='attachment' || $partDisposition=='inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
5894
+					if (empty($partDisposition)) $partDisposition = 'attachment';
5895
+					if ($part && ($partDisposition == 'attachment' || $partDisposition == 'inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
5896 5896
 					{
5897 5897
 						//$headerObject=$part->getAllDispositionParameters();//not used anywhere around here
5898 5898
 						$structure_mime = $part->getType();
5899 5899
 						$filename = $part->getName();
5900 5900
 						$charset = $part->getContentTypeParameter('charset');
5901 5901
 						//$structure_bytes = $part->getBytes(); $structure_partID=$part->getMimeId(); error_log(__METHOD__.__LINE__." fetchPartContents(".array2string($_uid).", $structure_partID, $_stream, $_preserveSeen,$structure_mime)" );
5902
-						$this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen=true,$structure_mime);
5902
+						$this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen = true, $structure_mime);
5903 5903
 						if ($_returnPart) return $part;
5904 5904
 					}
5905 5905
 				}
5906 5906
 			}
5907 5907
 		}
5908 5908
 		$ext = MimeMagic::mime2ext($structure_mime);
5909
-		if ($ext && stripos($filename,'.')===false && stripos($filename,$ext)===false) $filename = trim($filename).'.'.$ext;
5909
+		if ($ext && stripos($filename, '.') === false && stripos($filename, $ext) === false) $filename = trim($filename).'.'.$ext;
5910 5910
 		if (!$part)
5911 5911
 		{
5912 5912
 			throw new Exception\WrongParameter("Error: Could not fetch attachment for Uid=".array2string($_uid).", PartId=$_partID, WinMailNr=$_winmail_nr, folder=$_folder");
@@ -5924,20 +5924,20 @@  discard block
 block discarded – undo
5924 5924
 		// try guessing the mimetype, if we get the application/octet-stream
5925 5925
 		if (strtolower($attachmentData['type']) == 'application/octet-stream') $attachmentData['type'] = MimeMagic::filename2mime($attachmentData['filename']);
5926 5926
 		# if the attachment holds a winmail number and is a winmail.dat then we have to handle that.
5927
-		if ( $filename == 'winmail.dat' && $_winmail_nr)
5927
+		if ($filename == 'winmail.dat' && $_winmail_nr)
5928 5928
 		{
5929 5929
 			//by now _uid is of type array
5930
-			$tnefResolved=false;
5931
-			$wantedPart=$_uid[0].'@'.$_partID;
5930
+			$tnefResolved = false;
5931
+			$wantedPart = $_uid[0].'@'.$_partID;
5932 5932
 			$myTnef = $this->tnef_decoder($attachmentData['attachment']);
5933 5933
 			//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
5934 5934
 			// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
5935 5935
 			// we need to build Something that meets the needs
5936 5936
 			if ($myTnef)
5937 5937
 			{
5938
-				foreach($myTnef->getParts() as $mime_id => $part)
5938
+				foreach ($myTnef->getParts() as $mime_id => $part)
5939 5939
 				{
5940
-					$tnefResolved=true;
5940
+					$tnefResolved = true;
5941 5941
 					$attachment = $part->getAllDispositionParameters();
5942 5942
 					$attachment['mimeType'] = $part->getType();
5943 5943
 					//error_log(__METHOD__.__LINE__.'#'.$mime_id.'#'.$filename.'#'.array2string($attachment));
@@ -5945,9 +5945,9 @@  discard block
 block discarded – undo
5945 5945
 					if ($_winmail_nr == $wantedPart.'@'.$mime_id)
5946 5946
 					{
5947 5947
 						//error_log(__METHOD__.__LINE__.'#'.$structure_mime.'#'.$filename.'#'.array2string($attachment));
5948
-						if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5948
+						if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5949 5949
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5950
-						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']);
5950
+						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']);
5951 5951
 						$wmattach = $attachment;
5952 5952
 						$wmattach['attachment'] = $part->getContents(array('stream'=>$_stream));
5953 5953
 
@@ -5957,7 +5957,7 @@  discard block
 block discarded – undo
5957 5957
 			if ($tnefResolved)
5958 5958
 			{
5959 5959
 				$ext = MimeMagic::mime2ext($wmattach['mimeType']);
5960
-				if ($ext && stripos($wmattach['filename'],'.')===false && stripos($wmattach['filename'],$ext)===false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
5960
+				if ($ext && stripos($wmattach['filename'], '.') === false && stripos($wmattach['filename'], $ext) === false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
5961 5961
 				$attachmentData = array(
5962 5962
 					'type'       => $wmattach['mimeType'],
5963 5963
 					'filename'   => $wmattach['filename'],
@@ -5981,21 +5981,21 @@  discard block
 block discarded – undo
5981 5981
 	 *	true:
5982 5982
 	 * @return Horde_Mime_Part
5983 5983
 	 */
5984
-	function getAttachmentByCID($_uid, $_cid, $_part, $_stream=null)
5984
+	function getAttachmentByCID($_uid, $_cid, $_part, $_stream = null)
5985 5985
 	{
5986 5986
 		// some static variables to avoid fetching the same mail multiple times
5987
-		static $uid=null, $part=null, $structure=null;
5987
+		static $uid = null, $part = null, $structure = null;
5988 5988
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_cid, $_part");
5989 5989
 
5990
-		if(empty($_cid)) return false;
5990
+		if (empty($_cid)) return false;
5991 5991
 
5992 5992
 		if ($_uid != $uid || $_part != $part)
5993 5993
 		{
5994
-			$structure = $this->getStructure($uid=$_uid, $part=$_part);
5994
+			$structure = $this->getStructure($uid = $_uid, $part = $_part);
5995 5995
 		}
5996 5996
 		/** @var Horde_Mime_Part */
5997 5997
 		$attachment = null;
5998
-		foreach($structure->contentTypeMap() as $mime_id => $mime_type)
5998
+		foreach ($structure->contentTypeMap() as $mime_id => $mime_type)
5999 5999
 		{
6000 6000
 			$part = $structure->getPart($mime_id);
6001 6001
 
@@ -6047,16 +6047,16 @@  discard block
 block discarded – undo
6047 6047
 	 * @param string  $_mimetype to decide wether to try to fetch part as binary or not
6048 6048
 	 * @return Horde_Mime_Part
6049 6049
 	 */
6050
-	public function fetchPartContents($_uid, Horde_Mime_Part $part=null, $_stream=false, $_preserveSeen=false, $_mimetype=null)
6050
+	public function fetchPartContents($_uid, Horde_Mime_Part $part = null, $_stream = false, $_preserveSeen = false, $_mimetype = null)
6051 6051
 	{
6052
-		if (is_null($part)) return null;//new Horde_Mime_Part;
6052
+		if (is_null($part)) return null; //new Horde_Mime_Part;
6053 6053
 		$encoding = null;
6054 6054
 		$fetchAsBinary = true;
6055
-		if ($_mimetype && strtolower($_mimetype)=='message/rfc822') $fetchAsBinary = false;
6055
+		if ($_mimetype && strtolower($_mimetype) == 'message/rfc822') $fetchAsBinary = false;
6056 6056
 		// we need to set content on structure to decode transfer encoding
6057 6057
 		$part->setContents(
6058 6058
 			$this->getBodyPart($_uid, $part->getMimeId(), null, $_preserveSeen, $_stream, $encoding, $fetchAsBinary),
6059
-			array('encoding' => (!$fetchAsBinary&&!$encoding?'8bit':$encoding)));
6059
+			array('encoding' => (!$fetchAsBinary && !$encoding ? '8bit' : $encoding)));
6060 6060
 
6061 6061
 		return $part;
6062 6062
 	}
@@ -6074,17 +6074,17 @@  discard block
 block discarded – undo
6074 6074
 	 * @return the id of the message appended or exception
6075 6075
 	 * @throws Exception\WrongUserinput
6076 6076
 	 */
6077
-	function appendMessage($_folderName, $_header, $_body, $_flags='\\Recent')
6077
+	function appendMessage($_folderName, $_header, $_body, $_flags = '\\Recent')
6078 6078
 	{
6079 6079
 		if (!is_resource($_header))
6080 6080
 		{
6081
-			if (stripos($_header,'message-id:')===false)
6081
+			if (stripos($_header, 'message-id:') === false)
6082 6082
 			{
6083 6083
 				$_header = 'Message-ID: <'.self::getRandomString().'@localhost>'."\n".$_header;
6084 6084
 			}
6085 6085
 			//error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_header, $_body, $_flags");
6086
-			$_header = ltrim(str_replace("\n","\r\n",$_header));
6087
-			$_header .= str_replace("\n","\r\n",$_body);
6086
+			$_header = ltrim(str_replace("\n", "\r\n", $_header));
6087
+			$_header .= str_replace("\n", "\r\n", $_body);
6088 6088
 		}
6089 6089
 		// the recent flag is the default enforced here ; as we assume the _flags is always set,
6090 6090
 		// we default it to hordes default (Recent) (, other wise we should not pass the parameter
@@ -6102,7 +6102,7 @@  discard block
 block discarded – undo
6102 6102
 			// searched for the message-id then returning the uid found
6103 6103
 			//$dataNflags[] = array('data'=>array(array('t'=>'text','v'=>"$header"."$body")), 'flags'=>array($_flags));
6104 6104
 			$dataNflags[] = array('data' => $_header, 'flags'=>array($_flags));
6105
-			$messageid = $this->icServer->append($_folderName,$dataNflags);
6105
+			$messageid = $this->icServer->append($_folderName, $dataNflags);
6106 6106
 		}
6107 6107
 		catch (\Exception $e)
6108 6108
 		{
@@ -6114,7 +6114,7 @@  discard block
 block discarded – undo
6114 6114
 		//$messageid = true; // for debug reasons only
6115 6115
 		if ($messageid === true || empty($messageid)) // try to figure out the message uid
6116 6116
 		{
6117
-			$list = $this->getHeaders($_folderName, $_startMessage=1, 1, 'INTERNALDATE', true, array(),null, false);
6117
+			$list = $this->getHeaders($_folderName, $_startMessage = 1, 1, 'INTERNALDATE', true, array(), null, false);
6118 6118
 			if ($list)
6119 6119
 			{
6120 6120
 				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' MessageUid:'.$messageid.' but found:'.array2string($list));
@@ -6154,27 +6154,27 @@  discard block
 block discarded – undo
6154 6154
 	 *				'attachments'=>$attachments,
6155 6155
 	 *				'headers'=>$headers,; boolean false on failure
6156 6156
 	 */
6157
-	static function get_mailcontent(&$mailClass,$uid,$partid='',$mailbox='', $preserveHTML = false, $addHeaderSection=true, $includeAttachments=true)
6157
+	static function get_mailcontent(&$mailClass, $uid, $partid = '', $mailbox = '', $preserveHTML = false, $addHeaderSection = true, $includeAttachments = true)
6158 6158
 	{
6159 6159
 			//echo __METHOD__." called for $uid,$partid <br>";
6160
-			$headers = $mailClass->getMessageHeader($uid,$partid,true,false,$mailbox);
6160
+			$headers = $mailClass->getMessageHeader($uid, $partid, true, false, $mailbox);
6161 6161
 			if (empty($headers)) return false;
6162 6162
 			// dont force retrieval of the textpart, let mailClass preferences decide
6163
-			$bodyParts = $mailClass->getMessageBody($uid,($preserveHTML?'always_display':'only_if_no_text'),$partid,null,false,$mailbox);
6163
+			$bodyParts = $mailClass->getMessageBody($uid, ($preserveHTML ? 'always_display' : 'only_if_no_text'), $partid, null, false, $mailbox);
6164 6164
 			// if we do not want HTML but there is no TextRepresentation with the message itself, try converting
6165
-			if ( !$preserveHTML && $bodyParts[0]['mimeType']=='text/html')
6165
+			if (!$preserveHTML && $bodyParts[0]['mimeType'] == 'text/html')
6166 6166
 			{
6167
-				foreach($bodyParts as $i => $part)
6167
+				foreach ($bodyParts as $i => $part)
6168 6168
 				{
6169
-					if ($bodyParts[$i]['mimeType']=='text/html')
6169
+					if ($bodyParts[$i]['mimeType'] == 'text/html')
6170 6170
 					{
6171
-						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'],$bodyParts[$i]['charSet'],true,$stripalltags=true);
6172
-						$bodyParts[$i]['mimeType']='text/plain';
6171
+						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'], $bodyParts[$i]['charSet'], true, $stripalltags = true);
6172
+						$bodyParts[$i]['mimeType'] = 'text/plain';
6173 6173
 					}
6174 6174
 				}
6175 6175
 			}
6176 6176
 			//error_log(array2string($bodyParts));
6177
-			$attachments = $includeAttachments?$mailClass->getMessageAttachments($uid,$partid,null,true,false,true,$mailbox):array();
6177
+			$attachments = $includeAttachments ? $mailClass->getMessageAttachments($uid, $partid, null, true, false, true, $mailbox) : array();
6178 6178
 
6179 6179
 			if ($mailClass->isSentFolder($mailbox)) $mailaddress = $headers['TO'];
6180 6180
 			elseif (isset($headers['FROM'])) $mailaddress = $headers['FROM'];
@@ -6185,7 +6185,7 @@  discard block
 block discarded – undo
6185 6185
 
6186 6186
 			$message = self::getdisplayableBody($mailClass, $bodyParts, $preserveHTML);
6187 6187
 			if ($preserveHTML && $mailClass->activeMimeType == 'text/plain') $message = '<pre>'.$message.'</pre>';
6188
-			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '',$preserveHTML) : '');
6188
+			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '', $preserveHTML) : '');
6189 6189
 			$message = $headdata.$message;
6190 6190
 			//echo __METHOD__.'<br>';
6191 6191
 			//_debug_array($attachments);
@@ -6201,25 +6201,25 @@  discard block
 block discarded – undo
6201 6201
 						//_debug_array($mailClass->getMessageHeader($uid, $attachment['partID']));
6202 6202
 						//_debug_array($mailClass->getMessageBody($uid,'', $attachment['partID']));
6203 6203
 						//_debug_array($mailClass->getMessageAttachments($uid, $attachment['partID']));
6204
-						$mailcontent = self::get_mailcontent($mailClass,$uid,$attachment['partID'],$mailbox);
6205
-						$headdata ='';
6204
+						$mailcontent = self::get_mailcontent($mailClass, $uid, $attachment['partID'], $mailbox);
6205
+						$headdata = '';
6206 6206
 						if ($mailcontent['headers'])
6207 6207
 						{
6208
-							$headdata = self::createHeaderInfoSection($mailcontent['headers'],'',$preserveHTML);
6208
+							$headdata = self::createHeaderInfoSection($mailcontent['headers'], '', $preserveHTML);
6209 6209
 						}
6210 6210
 						if ($mailcontent['message'])
6211 6211
 						{
6212
-							$tempname =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6212
+							$tempname = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6213 6213
 							$attachedMessages[] = array(
6214 6214
 								'type' => 'TEXT/PLAIN',
6215 6215
 								'name' => $mailcontent['subject'].'.txt',
6216 6216
 								'tmp_name' => $tempname,
6217 6217
 							);
6218
-							$tmpfile = fopen($tempname,'w');
6219
-							fwrite($tmpfile,$headdata.$mailcontent['message']);
6218
+							$tmpfile = fopen($tempname, 'w');
6219
+							fwrite($tmpfile, $headdata.$mailcontent['message']);
6220 6220
 							fclose($tmpfile);
6221 6221
 						}
6222
-						foreach($mailcontent['attachments'] as &$tmpval)
6222
+						foreach ($mailcontent['attachments'] as &$tmpval)
6223 6223
 						{
6224 6224
 							$attachedMessages[] = $tmpval;
6225 6225
 						}
@@ -6227,36 +6227,36 @@  discard block
 block discarded – undo
6227 6227
 					}
6228 6228
 					else
6229 6229
 					{
6230
-						$attachments[$num] = array_merge($attachments[$num],$mailClass->getAttachment($uid, $attachment['partID'],0,false,false));
6230
+						$attachments[$num] = array_merge($attachments[$num], $mailClass->getAttachment($uid, $attachment['partID'], 0, false, false));
6231 6231
 
6232
-						if (empty($attachments[$num]['attachment'])&&$attachments[$num]['cid'])
6232
+						if (empty($attachments[$num]['attachment']) && $attachments[$num]['cid'])
6233 6233
 						{
6234
-							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'],true);
6234
+							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'], true);
6235 6235
 							$attachments[$num]['attachment'] = $c->getContents();
6236 6236
 						}
6237 6237
 						// no attempt to convert, if we dont know about the charset
6238
-						if (isset($attachments[$num]['charset'])&&!empty($attachments[$num]['charset'])) {
6238
+						if (isset($attachments[$num]['charset']) && !empty($attachments[$num]['charset'])) {
6239 6239
 							// we do not try guessing the charset, if it is not set
6240 6240
 							//if ($attachments[$num]['charset']===false) $attachments[$num]['charset'] = Translation::detect_encoding($attachments[$num]['attachment']);
6241
-							Translation::convert($attachments[$num]['attachment'],$attachments[$num]['charset']);
6241
+							Translation::convert($attachments[$num]['attachment'], $attachments[$num]['charset']);
6242 6242
 						}
6243
-						if(in_array($attachments[$num]['name'], $file_list))
6243
+						if (in_array($attachments[$num]['name'], $file_list))
6244 6244
 						{
6245 6245
 							$dupe_count[$attachments[$num]['name']]++;
6246
-							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME) .
6247
-								' ('.($dupe_count[$attachments[$num]['name']] + 1).')' . '.' .
6246
+							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME).
6247
+								' ('.($dupe_count[$attachments[$num]['name']] + 1).')'.'.'.
6248 6248
 								pathinfo($attachments[$num]['name'], PATHINFO_EXTENSION);
6249 6249
 						}
6250 6250
 						$attachments[$num]['type'] = $attachments[$num]['mimeType'];
6251
-						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6252
-						$tmpfile = fopen($attachments[$num]['tmp_name'],'w');
6253
-						fwrite($tmpfile,$attachments[$num]['attachment']);
6251
+						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6252
+						$tmpfile = fopen($attachments[$num]['tmp_name'], 'w');
6253
+						fwrite($tmpfile, $attachments[$num]['attachment']);
6254 6254
 						fclose($tmpfile);
6255 6255
 						$file_list[] = $attachments[$num]['name'];
6256 6256
 						unset($attachments[$num]['attachment']);
6257 6257
 					}
6258 6258
 				}
6259
-				if (is_array($attachedMessages)) $attachments = array_merge($attachments,$attachedMessages);
6259
+				if (is_array($attachedMessages)) $attachments = array_merge($attachments, $attachedMessages);
6260 6260
 			}
6261 6261
 			return array(
6262 6262
 					'mailaddress'=>$mailaddress,
@@ -6278,10 +6278,10 @@  discard block
 block discarded – undo
6278 6278
 	{
6279 6279
 		$c = 0;
6280 6280
 		// use the standardIdentity
6281
-		foreach($_identities as $key => $acc) {
6282
-			if ($c==0) $identity = $acc;
6281
+		foreach ($_identities as $key => $acc) {
6282
+			if ($c == 0) $identity = $acc;
6283 6283
 			//error_log(__METHOD__.__LINE__." $key == $_profile_id ");
6284
-			if ($key==$_profile_id) $identity = $acc;
6284
+			if ($key == $_profile_id) $identity = $acc;
6285 6285
 			$c++;
6286 6286
 		}
6287 6287
 		return $identity;
@@ -6293,29 +6293,29 @@  discard block
 block discarded – undo
6293 6293
 	 * @param bool createHTML do it with HTML breaks
6294 6294
 	 * @return string a preformatted string with the information of the header worked into it
6295 6295
 	 */
6296
-	static function createHeaderInfoSection($header,$headline='', $createHTML = false)
6296
+	static function createHeaderInfoSection($header, $headline = '', $createHTML = false)
6297 6297
 	{
6298 6298
 		$headdata = null;
6299 6299
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($header).function_backtrace());
6300
-		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML?"<br />":"\n");
6301
-		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML?"<br />":"\n");
6302
-		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML?"<br />":"\n");
6303
-		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML?"<br />":"\n");
6304
-		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML?"<br />":"\n");
6305
-		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML?"<br />":"\n");
6306
-		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML?"<br />":"\n");
6307
-		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML?"<br />":"\n");
6308
-		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] !='normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML?"<br />":"\n");
6300
+		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML ? "<br />" : "\n");
6301
+		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML ? "<br />" : "\n");
6302
+		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML ? "<br />" : "\n");
6303
+		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML ? "<br />" : "\n");
6304
+		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML ? "<br />" : "\n");
6305
+		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML ? "<br />" : "\n");
6306
+		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML ? "<br />" : "\n");
6307
+		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML ? "<br />" : "\n");
6308
+		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] != 'normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML ? "<br />" : "\n");
6309 6309
 		//if ($mailcontent['headers']['ORGANIZATION']) $headdata .= lang('organization').': '.$mailcontent['headers']['ORGANIZATION']."\
6310 6310
 		if (!empty($headdata))
6311 6311
 		{
6312
-			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML?"<br />":"\n").$headdata;
6313
-			if (empty($headline)) $headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'').$headdata;
6314
-			$headdata .= ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6312
+			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML ? "<br />" : "\n").$headdata;
6313
+			if (empty($headline)) $headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '').$headdata;
6314
+			$headdata .= ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6315 6315
 		}
6316 6316
 		else
6317 6317
 		{
6318
-			$headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6318
+			$headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6319 6319
 		}
6320 6320
 		return $headdata;
6321 6321
 	}
@@ -6328,8 +6328,8 @@  discard block
 block discarded – undo
6328 6328
 	 */
6329 6329
 	static function adaptSubjectForImport($subject)
6330 6330
 	{
6331
-		$subject = str_replace('$$','__',($subject?$subject:lang('(no subject)')));
6332
-		$subject = str_ireplace(array('[FWD]','[',']','{','}','<','>'),array('Fwd:',' ',' ',' ',' ',' ',' '),trim($subject));
6331
+		$subject = str_replace('$$', '__', ($subject ? $subject : lang('(no subject)')));
6332
+		$subject = str_ireplace(array('[FWD]', '[', ']', '{', '}', '<', '>'), array('Fwd:', ' ', ' ', ' ', ' ', ' ', ' '), trim($subject));
6333 6333
 		return $subject;
6334 6334
 	}
6335 6335
 
@@ -6341,15 +6341,15 @@  discard block
 block discarded – undo
6341 6341
 	static function convertAddressArrayToString($rfcAddressArray)
6342 6342
 	{
6343 6343
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($rfcAddressArray));
6344
-		$returnAddr ='';
6344
+		$returnAddr = '';
6345 6345
 		if (is_array($rfcAddressArray))
6346 6346
 		{
6347
-			foreach((array)$rfcAddressArray as $addressData) {
6347
+			foreach ((array)$rfcAddressArray as $addressData) {
6348 6348
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($addressData));
6349
-				if($addressData['MAILBOX_NAME'] == 'NIL') {
6349
+				if ($addressData['MAILBOX_NAME'] == 'NIL') {
6350 6350
 					continue;
6351 6351
 				}
6352
-				if(strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6352
+				if (strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6353 6353
 					continue;
6354 6354
 				}
6355 6355
 				if ($addressData['RFC822_EMAIL'])
@@ -6358,7 +6358,7 @@  discard block
 block discarded – undo
6358 6358
 				}
6359 6359
 				else
6360 6360
 				{
6361
-					$emailaddress = ($addressData['PERSONAL_NAME']?$addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>':$addressData['EMAIL']);
6361
+					$emailaddress = ($addressData['PERSONAL_NAME'] ? $addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>' : $addressData['EMAIL']);
6362 6362
 					$addressObjectA = self::parseAddressList($emailaddress);
6363 6363
 				}
6364 6364
 				$addressObject = $addressObjectA[0];
@@ -6367,10 +6367,10 @@  discard block
 block discarded – undo
6367 6367
 				//$mb =(string)$addressObject->mailbox;
6368 6368
 				//$h = (string)$addressObject->host;
6369 6369
 				//$p = (string)$addressObject->personal;
6370
-				$returnAddr .= (strlen($returnAddr)>0?',':'');
6370
+				$returnAddr .= (strlen($returnAddr) > 0 ? ',' : '');
6371 6371
 				//error_log(__METHOD__.' ('.__LINE__.') '.$p.' <'.$mb.'@'.$h.'>');
6372 6372
 				$buff = imap_rfc822_write_address($addressObject->mailbox, Horde_Idna::decode($addressObject->host), $addressObject->personal);
6373
-				$buff = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$buff);
6373
+				$buff = str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $buff);
6374 6374
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Address: '.$returnAddr);
6375 6375
 				$returnAddr .= $buff;
6376 6376
 			}
@@ -6378,8 +6378,8 @@  discard block
 block discarded – undo
6378 6378
 		else
6379 6379
 		{
6380 6380
 			// do not mess with strings, return them untouched /* ToDo: validate string as Address */
6381
-			$rfcAddressArray = self::decode_header($rfcAddressArray,true);
6382
-			$rfcAddressArray = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$rfcAddressArray);
6381
+			$rfcAddressArray = self::decode_header($rfcAddressArray, true);
6382
+			$rfcAddressArray = str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $rfcAddressArray);
6383 6383
 			if (is_string($rfcAddressArray)) return $rfcAddressArray;
6384 6384
 		}
6385 6385
 		return $returnAddr;
@@ -6393,12 +6393,12 @@  discard block
 block discarded – undo
6393 6393
 	 * @param string &$err error-message on error
6394 6394
 	 * @return string/boolean merged content or false on error
6395 6395
 	 */
6396
-	static function merge($content,$ids,$mimetype='')
6396
+	static function merge($content, $ids, $mimetype = '')
6397 6397
 	{
6398 6398
 		$mergeobj = new Contacts\Merge();
6399 6399
 
6400
-		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ?'text/plain':'text/html');
6401
-		$rv = $mergeobj->merge_string($content,$ids,$err='',$mimetype, array(), self::$displayCharset);
6400
+		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ? 'text/plain' : 'text/html');
6401
+		$rv = $mergeobj->merge_string($content, $ids, $err = '', $mimetype, array(), self::$displayCharset);
6402 6402
 		if (empty($rv) && !empty($content) && !empty($err)) $rv = $content;
6403 6403
 		if (!empty($err) && !empty($content) && !empty($ids)) error_log(__METHOD__.' ('.__LINE__.') '.' Merge failed for Ids:'.array2string($ids).' ContentType:'.$mimetype.' Content:'.$content.' Reason:'.array2string($err));
6404 6404
 		return $rv;
@@ -6440,12 +6440,12 @@  discard block
 block discarded – undo
6440 6440
 		else
6441 6441
 			settype($bytes, 'integer');
6442 6442
 
6443
-		return $bytes . ' ' . $type ;
6443
+		return $bytes.' '.$type;
6444 6444
 	}
6445 6445
 
6446 6446
 	static function detect_qp(&$sting) {
6447 6447
 		$needle = '/(=[0-9][A-F])|(=[A-F][0-9])|(=[A-F][A-F])|(=[0-9][0-9])/';
6448
-		return preg_match("$needle",$string);
6448
+		return preg_match("$needle", $string);
6449 6449
 	}
6450 6450
 
6451 6451
 	/**
@@ -6458,11 +6458,11 @@  discard block
 block discarded – undo
6458 6458
 	 * @param string $_methodNline - Information where the log was taken
6459 6459
 	 * @return void
6460 6460
 	 */
6461
-	static function logRunTimes($_starttime,$_endtime=null,$_message='',$_methodNline='')
6461
+	static function logRunTimes($_starttime, $_endtime = null, $_message = '', $_methodNline = '')
6462 6462
 	{
6463 6463
 		if (is_null($_endtime)) $_endtime = microtime(true);
6464 6464
 		$usagetime = microtime(true) - $_starttime;
6465
-		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime,5).'(s) '.($_message?'Details:'.$_message:''));
6465
+		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime, 5).'(s) '.($_message ? 'Details:'.$_message : ''));
6466 6466
 	}
6467 6467
 
6468 6468
 	/**
@@ -6475,9 +6475,9 @@  discard block
 block discarded – undo
6475 6475
 	 *
6476 6476
 	 * @throws Exception\WrongUserinput
6477 6477
 	 */
6478
-	static function checkFileBasics(&$_formData, $IDtoAddToFileName='', $reqMimeType='message/rfc822')
6478
+	static function checkFileBasics(&$_formData, $IDtoAddToFileName = '', $reqMimeType = 'message/rfc822')
6479 6479
 	{
6480
-		if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6480
+		if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6481 6481
 
6482 6482
 		//error_log(__METHOD__.__FILE__.array2string($_formData).' Id:'.$IDtoAddToFileName.' ReqMimeType:'.$reqMimeType);
6483 6483
 		$importfailed = $tmpFileName = false;
@@ -6487,7 +6487,7 @@  discard block
 block discarded – undo
6487 6487
 			$importfailed = true;
6488 6488
 			$alert_msg .= lang("Empty file %1 ignored.", $_formData['name']);
6489 6489
 		}
6490
-		elseif (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6490
+		elseif (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6491 6491
 			realpath(dirname($_formData['file'])) == realpath($GLOBALS['egw_info']['server']['temp_dir']))
6492 6492
 		{
6493 6493
 			// ensure existance of eGW temp dir
@@ -6495,7 +6495,7 @@  discard block
 block discarded – undo
6495 6495
 			// and different from any other temp file location set in php.ini
6496 6496
 			if (!file_exists($GLOBALS['egw_info']['server']['temp_dir']))
6497 6497
 			{
6498
-				@mkdir($GLOBALS['egw_info']['server']['temp_dir'],0700);
6498
+				@mkdir($GLOBALS['egw_info']['server']['temp_dir'], 0700);
6499 6499
 			}
6500 6500
 
6501 6501
 			// if we were NOT able to create this temp directory, then make an ERROR report
@@ -6522,14 +6522,14 @@  discard block
 block discarded – undo
6522 6522
 			// maybe its application/octet-stream -> this may mean that we could not determine the type
6523 6523
 			// so we check for the suffix too
6524 6524
 			// trust vfs mime-types, trust the mimetype if it contains a method
6525
-			if ((substr($_formData['file'],0,6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'],'method=')===false)
6525
+			if ((substr($_formData['file'], 0, 6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'], 'method=') === false)
6526 6526
 			{
6527
-				$buff = explode('.',$_formData['name']);
6527
+				$buff = explode('.', $_formData['name']);
6528 6528
 				$suffix = '';
6529 6529
 				if (is_array($buff)) $suffix = array_pop($buff); // take the last extension to check with ext2mime
6530 6530
 				if (!empty($suffix)) $sfxMimeType = MimeMagic::ext2mime($suffix);
6531 6531
 				if (!empty($suffix) && !empty($sfxMimeType) &&
6532
-					(strlen(trim($_formData['type']))==0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6532
+					(strlen(trim($_formData['type'])) == 0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6533 6533
 				{
6534 6534
 					error_log(__METHOD__.' ('.__LINE__.') '.' Data:'.array2string($_formData));
6535 6535
 					error_log(__METHOD__.' ('.__LINE__.') '.' Form reported Mimetype:'.$_formData['type'].' but seems to be:'.$sfxMimeType);
@@ -6544,13 +6544,13 @@  discard block
 block discarded – undo
6544 6544
 			if ($reqMimeType)
6545 6545
 			{
6546 6546
 				// so if PHP did not pass any file_type info, then substitute the rfc default value
6547
-				if (substr(strtolower(trim($_formData['type'])),0,strlen($mime_type_default)) != $mime_type_default)
6547
+				if (substr(strtolower(trim($_formData['type'])), 0, strlen($mime_type_default)) != $mime_type_default)
6548 6548
 				{
6549 6549
 					if (!(strtolower(trim($_formData['type'])) == "application/octet-stream" && $sfxMimeType == $reqMimeType))
6550 6550
 					{
6551 6551
 						//error_log("Message rejected, no message/rfc. Is:".$_formData['type']);
6552 6552
 						$importfailed = true;
6553
-						$alert_msg .= lang("File rejected, no %2. Is:%1",$_formData['type'],$reqMimeType);
6553
+						$alert_msg .= lang("File rejected, no %2. Is:%1", $_formData['type'], $reqMimeType);
6554 6554
 					}
6555 6555
 					if ((strtolower(trim($_formData['type'])) != $reqMimeType && $sfxMimeType == $reqMimeType))
6556 6556
 					{
@@ -6559,17 +6559,17 @@  discard block
 block discarded – undo
6559 6559
 				}
6560 6560
 			}
6561 6561
 			// as FreeBSD seems to have problems with the generated temp names we append some more random stuff
6562
-			$randomString = chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90));
6562
+			$randomString = chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90));
6563 6563
 			$tmpFileName = $GLOBALS['egw_info']['user']['account_id'].
6564 6564
 				trim($IDtoAddToFileName).basename($_formData['file']).'_'.$randomString;
6565 6565
 
6566
-			if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs')
6566
+			if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs')
6567 6567
 			{
6568
-				$tmpFileName = $_formData['file'];	// no need to store it somewhere
6568
+				$tmpFileName = $_formData['file']; // no need to store it somewhere
6569 6569
 			}
6570 6570
 			elseif (is_uploaded_file($_formData['file']))
6571 6571
 			{
6572
-				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName);	// requirement for safe_mode!
6572
+				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName); // requirement for safe_mode!
6573 6573
 			}
6574 6574
 			else
6575 6575
 			{
@@ -6578,7 +6578,7 @@  discard block
 block discarded – undo
6578 6578
 		} else {
6579 6579
 			//error_log("Import of message ".$_formData['file']." failes to meet basic restrictions");
6580 6580
 			$importfailed = true;
6581
-			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.",$_formData['name']);
6581
+			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.", $_formData['name']);
6582 6582
 		}
6583 6583
 		if ($importfailed == true)
6584 6584
 		{
@@ -6586,7 +6586,7 @@  discard block
 block discarded – undo
6586 6586
 		}
6587 6587
 		else
6588 6588
 		{
6589
-			if (parse_url($tmpFileName,PHP_URL_SCHEME) == 'vfs')
6589
+			if (parse_url($tmpFileName, PHP_URL_SCHEME) == 'vfs')
6590 6590
 			{
6591 6591
 				Vfs::load_wrapper('vfs');
6592 6592
 			}
@@ -6611,7 +6611,7 @@  discard block
 block discarded – undo
6611 6611
 		$images = null;
6612 6612
 		if (preg_match_all("/(src|background)=\"(.*)\"/Ui", $_html2parse, $images) && isset($images[2]))
6613 6613
 		{
6614
-			foreach($images[2] as $i => $url)
6614
+			foreach ($images[2] as $i => $url)
6615 6615
 			{
6616 6616
 				//$isData = false;
6617 6617
 				$basedir = $data = '';
@@ -6623,20 +6623,20 @@  discard block
 block discarded – undo
6623 6623
 					$filename = basename($url);
6624 6624
 					if (($directory = dirname($url)) == '.') $directory = '';
6625 6625
 					$ext = pathinfo($filename, PATHINFO_EXTENSION);
6626
-					$mimeType  = MimeMagic::ext2mime($ext);
6627
-					if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
6626
+					$mimeType = MimeMagic::ext2mime($ext);
6627
+					if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
6628 6628
 					$myUrl = $directory.$filename;
6629
-					if ($myUrl[0]=='/') // local path -> we only allow path's that are available via http/https (or vfs)
6629
+					if ($myUrl[0] == '/') // local path -> we only allow path's that are available via http/https (or vfs)
6630 6630
 					{
6631
-						$basedir = ($_SERVER['HTTPS']?'https://':'http://'.$_SERVER['HTTP_HOST']);
6631
+						$basedir = ($_SERVER['HTTPS'] ? 'https://' : 'http://'.$_SERVER['HTTP_HOST']);
6632 6632
 					}
6633 6633
 					// use vfs instead of url containing webdav.php
6634 6634
 					// ToDo: we should test if the webdav url is of our own scope, as we cannot handle foreign
6635 6635
 					// webdav.php urls as vfs
6636
-					if (strpos($myUrl,'/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6636
+					if (strpos($myUrl, '/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6637 6637
 					{
6638 6638
 						Vfs::load_wrapper('vfs');
6639
-						list(,$myUrl) = explode('/webdav.php',$myUrl,2);
6639
+						list(,$myUrl) = explode('/webdav.php', $myUrl, 2);
6640 6640
 						$basedir = 'vfs://default';
6641 6641
 						$needTempFile = false;
6642 6642
 					}
@@ -6649,11 +6649,11 @@  discard block
 block discarded – undo
6649 6649
 						// Strips the url and store it into a temp for further procss
6650 6650
 						$tmp_url = html_entity_decode($myUrl);
6651 6651
 
6652
-						parse_str(parse_url($tmp_url, PHP_URL_QUERY),$URI_params);
6652
+						parse_str(parse_url($tmp_url, PHP_URL_QUERY), $URI_params);
6653 6653
 						if ($URI_params['mailbox'] && $URI_params['uid'] && $URI_params['cid'])
6654 6654
 						{
6655 6655
 							$mail_bo->reopen(base64_decode($URI_params['mailbox']));
6656
-							$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']),base64_decode($URI_params['partID']),true);
6656
+							$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']), base64_decode($URI_params['partID']), true);
6657 6657
 							$mail_bo->closeConnection();
6658 6658
 							if ($attachment)
6659 6659
 							{
@@ -6664,32 +6664,32 @@  discard block
 block discarded – undo
6664 6664
 						}
6665 6665
 					}
6666 6666
 
6667
-					if ( strlen($basedir) > 1 && substr($basedir,-1) != '/' && $myUrl[0]!='/') { $basedir .= '/'; }
6668
-					if ($needTempFile && !$attachment && substr($myUrl,0,4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6667
+					if (strlen($basedir) > 1 && substr($basedir, -1) != '/' && $myUrl[0] != '/') { $basedir .= '/'; }
6668
+					if ($needTempFile && !$attachment && substr($myUrl, 0, 4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6669 6669
 				}
6670
-				if (substr($url,0,strlen('data:'))=='data:')
6670
+				if (substr($url, 0, strlen('data:')) == 'data:')
6671 6671
 				{
6672 6672
 					//error_log(__METHOD__.' ('.__LINE__.') '.' -> '.$i.': '.array2string($images[$i]));
6673 6673
 					// we only support base64 encoded data
6674
-					$tmp = substr($url,strlen('data:'));
6675
-					list($mimeType,$data_base64) = explode(';base64,',$tmp);
6674
+					$tmp = substr($url, strlen('data:'));
6675
+					list($mimeType, $data_base64) = explode(';base64,', $tmp);
6676 6676
 					$data = base64_decode($data_base64);
6677 6677
 					// FF currently does NOT add any mime-type
6678 6678
 					if (strtolower(substr($mimeType, 0, 6)) != 'image/')
6679 6679
 					{
6680 6680
 						$mimeType = MimeMagic::analyze_data($data);
6681 6681
 					}
6682
-					list($what,$exactly) = explode('/',$mimeType);
6682
+					list($what, $exactly) = explode('/', $mimeType);
6683 6683
 					$needTempFile = true;
6684
-					$filename = ($what?$what:'data').$imageC++.'.'.$exactly;
6684
+					$filename = ($what ? $what : 'data').$imageC++.'.'.$exactly;
6685 6685
 				}
6686 6686
 				if ($data || $needTempFile === false)
6687 6687
 				{
6688 6688
 					if ($needTempFile)
6689 6689
 					{
6690
-						$attachment_file =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6691
-						$tmpfile = fopen($attachment_file,'w');
6692
-						fwrite($tmpfile,$data);
6690
+						$attachment_file = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6691
+						$tmpfile = fopen($attachment_file, 'w');
6692
+						fwrite($tmpfile, $data);
6693 6693
 						fclose($tmpfile);
6694 6694
 					}
6695 6695
 					else
@@ -6700,7 +6700,7 @@  discard block
 block discarded – undo
6700 6700
 					// (or similar) in all cases (when cut&paste). This may lead to more attached files, in case
6701 6701
 					// we use the same image multiple times, but, if we do this, we should try to detect that
6702 6702
 					// on upload. filename itself is not sufficient to determine the sameness of images
6703
-					$cid = 'cid:' . md5($attachment_file);
6703
+					$cid = 'cid:'.md5($attachment_file);
6704 6704
 					if ($_mailObject->AddEmbeddedImage($attachment_file, substr($cid, 4), urldecode($filename), $mimeType) !== null)
6705 6705
 					{
6706 6706
 						//$_html2parse = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $_html2parse);
@@ -6729,10 +6729,10 @@  discard block
 block discarded – undo
6729 6729
 	 * @param string& $importID ID for the imported message, used by attachments to identify them unambiguously
6730 6730
 	 * @return mixed array of messages with success and failed messages or exception
6731 6731
 	 */
6732
-	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID='')
6732
+	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID = '')
6733 6733
 	{
6734 6734
 		$importfailed = false;
6735
-		$processStats = array('success'=>array(),'failed'=>array());
6735
+		$processStats = array('success'=>array(), 'failed'=>array());
6736 6736
 		if (empty($SendAndMergeTocontacts))
6737 6737
 		{
6738 6738
 			$importfailed = true;
@@ -6773,7 +6773,7 @@  discard block
 block discarded – undo
6773 6773
 				$_folder = $this->getSentFolder();
6774 6774
 			}
6775 6775
 			$delimiter = $this->getHierarchyDelimiter();
6776
-			if($_folder=='INBOX'.$delimiter) $_folder='INBOX';
6776
+			if ($_folder == 'INBOX'.$delimiter) $_folder = 'INBOX';
6777 6777
 			if ($importfailed === false)
6778 6778
 			{
6779 6779
 				$Subject = $mailObject->getHeader('Subject');
@@ -6791,9 +6791,9 @@  discard block
 block discarded – undo
6791 6791
 				{
6792 6792
 					$mailObject->clearReplyTos();
6793 6793
 					$activeMailProfiles = $this->mail->getAccountIdentities($this->profileID);
6794
-					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
6794
+					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
6795 6795
 
6796
-					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']),Mail::generateIdentityString($activeMailProfile,false));
6796
+					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']), Mail::generateIdentityString($activeMailProfile, false));
6797 6797
 				}
6798 6798
 				foreach ($SendAndMergeTocontacts as $k => $val)
6799 6799
 				{
@@ -6807,12 +6807,12 @@  discard block
 block discarded – undo
6807 6807
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6808 6808
 
6809 6809
 						// Parse destinations for placeholders
6810
-						foreach(Mailer::$type2header as $type => $h)
6810
+						foreach (Mailer::$type2header as $type => $h)
6811 6811
 						{
6812 6812
 							//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));
6813
-							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset);
6814
-							$mailObject->addAddress($merged,'',$type);
6815
-							if($type == 'to')
6813
+							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]), $val, $e, 'text/plain', array(), self::$displayCharset);
6814
+							$mailObject->addAddress($merged, '', $type);
6815
+							if ($type == 'to')
6816 6816
 							{
6817 6817
 								$email = $merged;
6818 6818
 							}
@@ -6825,26 +6825,26 @@  discard block
 block discarded – undo
6825 6825
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ID:'.$val.' Data:'.array2string($contact));
6826 6826
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
6827 6827
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
6828
-							if($email)
6828
+							if ($email)
6829 6829
 							{
6830 6830
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
6831 6831
 							}
6832 6832
 						}
6833 6833
 
6834 6834
 						$activeMailProfiles = $this->getAccountIdentities($this->profileID);
6835
-						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
6835
+						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
6836 6836
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($activeMailProfile));
6837 6837
 						$mailObject->setFrom($activeMailProfile['ident_email'],
6838
-							self::generateIdentityString($activeMailProfile,false));
6838
+							self::generateIdentityString($activeMailProfile, false));
6839 6839
 
6840 6840
 						$mailObject->removeHeader('Message-ID');
6841 6841
 						$mailObject->removeHeader('Date');
6842 6842
 						$mailObject->clearCustomHeaders();
6843 6843
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6844 6844
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6845
-						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));
6845
+						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));
6846 6846
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6847
-						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));
6847
+						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));
6848 6848
 
6849 6849
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6850 6850
 						// set a higher timeout for big messages
@@ -6853,7 +6853,7 @@  discard block
 block discarded – undo
6853 6853
 						try {
6854 6854
 							$mailObject->send();
6855 6855
 						}
6856
-						catch(Exception $e) {
6856
+						catch (Exception $e) {
6857 6857
 							$sendOK = false;
6858 6858
 							$errorInfo = $e->getMessage();
6859 6859
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($errorInfo));
@@ -6867,41 +6867,41 @@  discard block
 block discarded – undo
6867 6867
 						$mailObject->clearCustomHeaders();
6868 6868
 
6869 6869
 						// Parse destinations for placeholders
6870
-						foreach(Mailer::$type2header as $type => $h)
6870
+						foreach (Mailer::$type2header as $type => $h)
6871 6871
 						{
6872
-							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset);
6872
+							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]), $val, $e, 'text/plain', array(), self::$displayCharset);
6873 6873
 							//error_log($type . ': ' . $mailObject->getHeader(Mailer::$type2header[$type]) . ' -> ' .$merged);
6874
-							$mailObject->addAddress(trim($merged,'"'),'',$type);
6874
+							$mailObject->addAddress(trim($merged, '"'), '', $type);
6875 6875
 						}
6876 6876
 
6877 6877
 						// No addresses from placeholders?  Treat it as just a contact ID
6878
-						if (count($mailObject->getAddresses('to',true)) == 0 &&
6878
+						if (count($mailObject->getAddresses('to', true)) == 0 &&
6879 6879
 							is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val)) // do the merge
6880 6880
 						{
6881 6881
 							$contact = $bo_merge->contacts->read($val);
6882 6882
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($contact));
6883 6883
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
6884 6884
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
6885
-							if($email)
6885
+							if ($email)
6886 6886
 							{
6887 6887
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
6888 6888
 							}
6889 6889
 						}
6890 6890
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6891 6891
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6892
-						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));
6892
+						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));
6893 6893
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6894
-						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));
6894
+						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));
6895 6895
 						$_folder = $this->getDraftFolder();
6896 6896
 					}
6897 6897
 					if ($sendOK || $openAsDraft)
6898 6898
 					{
6899
-						if ($this->folderExists($_folder,true))
6899
+						if ($this->folderExists($_folder, true))
6900 6900
 						{
6901
-						    if($this->isSentFolder($_folder))
6901
+						    if ($this->isSentFolder($_folder))
6902 6902
 							{
6903 6903
 						        $flags = '\\Seen';
6904
-						    } elseif($this->isDraftFolder($_folder)) {
6904
+						    } elseif ($this->isDraftFolder($_folder)) {
6905 6905
 						        $flags = '\\Draft';
6906 6906
 						    } else {
6907 6907
 						        $flags = '';
@@ -6909,7 +6909,7 @@  discard block
 block discarded – undo
6909 6909
 							$savefailed = false;
6910 6910
 							try
6911 6911
 							{
6912
-								$messageUid =$this->appendMessage($_folder,
6912
+								$messageUid = $this->appendMessage($_folder,
6913 6913
 									$mailObject->getRaw(),
6914 6914
 									null,
6915 6915
 									$flags);
@@ -6917,10 +6917,10 @@  discard block
 block discarded – undo
6917 6917
 							catch (\Exception\WrongUserinput $e)
6918 6918
 							{
6919 6919
 								$savefailed = true;
6920
-								$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3",$Subject,$_folder,$e->getMessage());
6920
+								$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3", $Subject, $_folder, $e->getMessage());
6921 6921
 							}
6922 6922
 							// no send, save successful, and message_uid present
6923
-							if ($savefailed===false && $messageUid && is_null($sendOK))
6923
+							if ($savefailed === false && $messageUid && is_null($sendOK))
6924 6924
 							{
6925 6925
 								$importID = $messageUid;
6926 6926
 								$openComposeWindow = true;
@@ -6929,20 +6929,20 @@  discard block
 block discarded – undo
6929 6929
 						else
6930 6930
 						{
6931 6931
 							$savefailed = true;
6932
-							$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.",$Subject,$_folder);
6932
+							$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.", $Subject, $_folder);
6933 6933
 						}
6934 6934
 						if ($sendOK)
6935 6935
 						{
6936
-							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed?' but failed to store to Folder:'.$_folder:'');
6936
+							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed ? ' but failed to store to Folder:'.$_folder : '');
6937 6937
 						}
6938 6938
 						else
6939 6939
 						{
6940
-							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6940
+							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6941 6941
 						}
6942 6942
 					}
6943
-					if (!is_null($sendOK) && $sendOK===false && is_null($openComposeWindow))
6943
+					if (!is_null($sendOK) && $sendOK === false && is_null($openComposeWindow))
6944 6944
 					{
6945
-						$processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6945
+						$processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6946 6946
 					}
6947 6947
 				}
6948 6948
 			}
@@ -7021,16 +7021,16 @@  discard block
 block discarded – undo
7021 7021
 
7022 7022
 		if (is_string($message))
7023 7023
 		{
7024
-			$start = substr($message,0, strpos($message, $eol));
7024
+			$start = substr($message, 0, strpos($message, $eol));
7025 7025
 			$body = substr($message, strlen($start));
7026 7026
 			$hlength = strpos($start, $eol) ? strpos($start, $eol) : strlen($start);
7027
-			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0,$hlength));
7028
-			foreach($headers->toArray() as $header => $value)
7027
+			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0, $hlength));
7028
+			foreach ($headers->toArray() as $header => $value)
7029 7029
 			{
7030 7030
 				$needsReplacement = false;
7031
-				foreach((array)$value as &$val)
7031
+				foreach ((array)$value as &$val)
7032 7032
 				{
7033
-					if (strlen($val)+ strlen($header) > 900)
7033
+					if (strlen($val) + strlen($header) > 900)
7034 7034
 					{
7035 7035
 						$needsReplacement = $needsFix = true;
7036 7036
 					}
@@ -7052,7 +7052,7 @@  discard block
 block discarded – undo
7052 7052
 	 * @param boolean $force8bitOnPrimaryPart (default false. force transferEncoding and charset to 8bit/utf8 if we have a textpart as primaryPart)
7053 7053
 	 * @throws Exception\WrongParameter when the required Horde_Mail_Part not found
7054 7054
 	 */
7055
-	function parseRawMessageIntoMailObject(Mailer $mailer, $message, $force8bitOnPrimaryPart=false)
7055
+	function parseRawMessageIntoMailObject(Mailer $mailer, $message, $force8bitOnPrimaryPart = false)
7056 7056
 	{
7057 7057
 		if (is_string($message) || is_resource($message))
7058 7058
 		{
@@ -7061,7 +7061,7 @@  discard block
 block discarded – undo
7061 7061
 
7062 7062
 			$structure = Horde_Mime_Part::parseMessage($message);
7063 7063
 			//error_log(__METHOD__.__LINE__.'#'.$structure->getPrimaryType().'#');
7064
-			if ($force8bitOnPrimaryPart&&$structure->getPrimaryType()=='text')
7064
+			if ($force8bitOnPrimaryPart && $structure->getPrimaryType() == 'text')
7065 7065
 			{
7066 7066
 				$structure->setTransferEncoding('8bit');
7067 7067
 				$structure->setCharset('utf-8');
@@ -7070,19 +7070,18 @@  discard block
 block discarded – undo
7070 7070
 			//error_log(__METHOD__.__LINE__.':'.array2string($structure));
7071 7071
 
7072 7072
 			// unfortunately parseMessage does NOT return parsed headers (we assume header is shorter then 8k)
7073
-			$start = is_string($message) ? substr($message, 0, 8192) :
7074
-				(fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 8192));
7073
+			$start = is_string($message) ? substr($message, 0, 8192) : (fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 8192));
7075 7074
 
7076 7075
 			$length = strpos($start, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
7077
-			if ($length===false) $length = strlen($start);
7078
-			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0,$length));
7076
+			if ($length === false) $length = strlen($start);
7077
+			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0, $length));
7079 7078
 
7080
-			foreach($headers->toArray(array('nowrap' => true)) as $header => $value)
7079
+			foreach ($headers->toArray(array('nowrap' => true)) as $header => $value)
7081 7080
 			{
7082
-				foreach((array)$value as $n => $val)
7081
+				foreach ((array)$value as $n => $val)
7083 7082
 				{
7084 7083
 					$overwrite = !$n;
7085
-					switch($header)
7084
+					switch ($header)
7086 7085
 					{
7087 7086
 						case 'Content-Transfer-Encoding':
7088 7087
 							//as we parse the message and this sets the part with a Content-Transfer-Encoding, we
@@ -7109,7 +7108,7 @@  discard block
 block discarded – undo
7109 7108
 		}
7110 7109
 		else
7111 7110
 		{
7112
-			if (($type = gettype($message)) == 'object') $type = get_class ($message);
7111
+			if (($type = gettype($message)) == 'object') $type = get_class($message);
7113 7112
 			throw new Exception\WrongParameter('Wrong parameter type for message: '.$type);
7114 7113
 		}
7115 7114
 	}
@@ -7123,50 +7122,50 @@  discard block
 block discarded – undo
7123 7122
 	 * @param string $default_domain
7124 7123
 	 * @return Horde_Mail_Rfc822_List iteratable Horde_Mail_Rfc822_Address objects with attributes mailbox, host, personal and valid
7125 7124
 	 */
7126
-	public static function parseAddressList($addresses, $default_domain=null)
7125
+	public static function parseAddressList($addresses, $default_domain = null)
7127 7126
 	{
7128 7127
 		$rfc822 = new Horde_Mail_Rfc822();
7129 7128
 		$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
7130 7129
 		//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count.function_backtrace());
7131
-		if ((empty($ret) || $ret->count()==0)&& is_string($addresses) && strlen($addresses)>0)
7130
+		if ((empty($ret) || $ret->count() == 0) && is_string($addresses) && strlen($addresses) > 0)
7132 7131
 		{
7133 7132
 			$matches = array();
7134
-			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/",$addresses,$matches);
7133
+			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/", $addresses, $matches);
7135 7134
 			//error_log(__METHOD__.__LINE__.array2string($matches));
7136
-			foreach ($matches[0] as &$match) {$match = trim($match,', ');}
7137
-			$addresses = implode(',',$matches[0]);
7135
+			foreach ($matches[0] as &$match) {$match = trim($match, ', '); }
7136
+			$addresses = implode(',', $matches[0]);
7138 7137
 			//error_log(__METHOD__.__LINE__.array2string($addresses));
7139 7138
 			$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
7140 7139
 			//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count);
7141 7140
 		}
7142
-		$previousFailed=false;
7141
+		$previousFailed = false;
7143 7142
 		$ret2 = new Horde_Mail_Rfc822_List();
7144 7143
 		// handle known problems on emailaddresses
7145
-		foreach($ret as $i => $adr)
7144
+		foreach ($ret as $i => $adr)
7146 7145
 		{
7147 7146
 			//mailaddresses enclosed in single quotes like '[email protected]' show up as 'me as mailbox and you.com' as host
7148
-			if ($adr->mailbox && stripos($adr->mailbox,"'")== 0 &&
7149
-					$adr->host && stripos($adr->host,"'")== (strlen($adr->host) -1))
7147
+			if ($adr->mailbox && stripos($adr->mailbox, "'") == 0 &&
7148
+					$adr->host && stripos($adr->host, "'") == (strlen($adr->host) - 1))
7150 7149
 			{
7151
-				$adr->mailbox = str_replace("'","",$adr->mailbox);
7152
-				$adr->host = str_replace("'","",$adr->host);
7150
+				$adr->mailbox = str_replace("'", "", $adr->mailbox);
7151
+				$adr->host = str_replace("'", "", $adr->host);
7153 7152
 			}
7154 7153
 			// no mailbox or host part as 'Xr\xc3\xa4hlyz, User <[email protected]>' is parsed as 2 addresses separated by ','
7155 7154
 			//#'Xr\xc3\xa4hlyz, User <[email protected]>'
7156 7155
 			//#Horde_Mail_Rfc822_List Object([_data:protected] => Array(
7157 7156
 			//[0] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => Xr\xc3\xa4hlyz[_host:protected] => [_personal:protected] => )
7158 7157
 			//[1] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => mailboxpart1.mailboxpart2[_host:protected] => youthost.com[_personal:protected] => User))[_filter:protected] => Array()[_ptr:protected] => )#2#,
7159
-			if (strlen($adr->mailbox)==0||strlen($adr->host)==0)
7158
+			if (strlen($adr->mailbox) == 0 || strlen($adr->host) == 0)
7160 7159
 			{
7161
-				$remember = ($adr->mailbox?$adr->mailbox:($adr->host?$adr->host:''));
7162
-				$previousFailed=true;
7160
+				$remember = ($adr->mailbox ? $adr->mailbox : ($adr->host ? $adr->host : ''));
7161
+				$previousFailed = true;
7163 7162
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
7164 7163
 			}
7165 7164
 			else
7166 7165
 			{
7167
-				if ($previousFailed && $remember) $adr->personal = $remember. ' ' . $adr->personal;
7166
+				if ($previousFailed && $remember) $adr->personal = $remember.' '.$adr->personal;
7168 7167
 				$remember = '';
7169
-				$previousFailed=false;
7168
+				$previousFailed = false;
7170 7169
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
7171 7170
 				$ret2->add($adr);
7172 7171
 			}
@@ -7182,7 +7181,7 @@  discard block
 block discarded – undo
7182 7181
 	 * @param string $_folder
7183 7182
 	 * @return boolean
7184 7183
 	 */
7185
-	function sendMDN($uid,$_folder)
7184
+	function sendMDN($uid, $_folder)
7186 7185
 	{
7187 7186
 		$acc = Mail\Account::read($this->profileID);
7188 7187
 		$identity = Mail\Account::read_identity($acc['ident_id'], true, null, $acc);
@@ -7212,7 +7211,7 @@  discard block
 block discarded – undo
7212 7211
 	 */
7213 7212
 	function addAccount($_hookValues)
7214 7213
 	{
7215
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7214
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7216 7215
 
7217 7216
 	}
7218 7217
 
@@ -7226,7 +7225,7 @@  discard block
 block discarded – undo
7226 7225
 	 */
7227 7226
 	function deleteAccount($_hookValues)
7228 7227
 	{
7229
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7228
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7230 7229
 
7231 7230
 	}
7232 7231
 
@@ -7240,7 +7239,7 @@  discard block
 block discarded – undo
7240 7239
 	 */
7241 7240
 	function updateAccount($_hookValues)
7242 7241
 	{
7243
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7242
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7244 7243
 
7245 7244
 	}
7246 7245
 }
Please login to merge, or discard this patch.