Completed
Push — master ( 28e3c7...8a6126 )
by Klaus
47:43 queued 26:30
created
api/src/Mail.php 1 patch
Spacing   +1117 added lines, -1118 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
@@ -131,9 +131,9 @@  discard block
 block discarded – undo
131 131
 	static $htmLawed_config = array('comment'=>1, //remove comments
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
-		'balance'=>1,//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)
134
+		'balance'=>1, //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 135
 		'direct_list_nest' => 1,
136
-		'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
136
+		'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 137
 		// tidy eats away even some wanted whitespace, so we switch it off;
138 138
 		// we used it for its compacting and beautifying capabilities, which resulted in better html for further processing
139 139
 		'tidy'=>0,
@@ -148,13 +148,13 @@  discard block
 block discarded – undo
148 148
 	 *
149 149
 	 * @array
150 150
 	 */
151
-	static $aclShortCuts = array('' => array('label'=>'none','title'=>'The user has no rights whatsoever.'),
152
-		'lrs'		=> array('label'=>'readable','title'=>'Allows a user to read the contents of the mailbox.'),
153
-		'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.'),
154
-		'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.'),
155
-		'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.'),
156
-		'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.'),
157
-		'custom'	=> array('label'=>'custom','title'=>'User defined combination of rights for the ACL'),
151
+	static $aclShortCuts = array('' => array('label'=>'none', 'title'=>'The user has no rights whatsoever.'),
152
+		'lrs'		=> array('label'=>'readable', 'title'=>'Allows a user to read the contents of the mailbox.'),
153
+		'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.'),
154
+		'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.'),
155
+		'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.'),
156
+		'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.'),
157
+		'custom'	=> array('label'=>'custom', 'title'=>'User defined combination of rights for the ACL'),
158 158
 	);
159 159
 
160 160
 	/**
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
196 196
 	 * @return Mail
197 197
 	 */
198
-	public static function getInstance($_restoreSession=true, &$_profileID=0, $_validate=true, $_oldImapServerObject=false, $_reuseCache=null)
198
+	public static function getInstance($_restoreSession = true, &$_profileID = 0, $_validate = true, $_oldImapServerObject = false, $_reuseCache = null)
199 199
 	{
200 200
 		//$_restoreSession=false;
201 201
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
@@ -205,13 +205,13 @@  discard block
 block discarded – undo
205 205
 		{
206 206
 			if (!is_object(self::$instances[$_profileID]))
207 207
 			{
208
-				self::$instances[$_profileID] = new Mail('utf-8',false,$_profileID,false,$_reuseCache);
208
+				self::$instances[$_profileID] = new Mail('utf-8', false, $_profileID, false, $_reuseCache);
209 209
 			}
210 210
 			self::$instances[$_profileID]->icServer = $_oldImapServerObject;
211
-			self::$instances[$_profileID]->accountid= $_oldImapServerObject->ImapServerId;
212
-			self::$instances[$_profileID]->profileID= $_oldImapServerObject->ImapServerId;
211
+			self::$instances[$_profileID]->accountid = $_oldImapServerObject->ImapServerId;
212
+			self::$instances[$_profileID]->profileID = $_oldImapServerObject->ImapServerId;
213 213
 			self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
214
-			self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
214
+			self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
215 215
 			return self::$instances[$_profileID];
216 216
 		}
217 217
 		if ($_profileID == 0)
@@ -224,14 +224,14 @@  discard block
 block discarded – undo
224 224
 			{
225 225
 				$profileID = Mail\Account::get_default_acc_id();
226 226
 			}
227
-			if ($profileID!=$_profileID) $_restoreSession==false;
228
-			$_profileID=$profileID;
227
+			if ($profileID != $_profileID) $_restoreSession == false;
228
+			$_profileID = $profileID;
229 229
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' called with profileID==0 using '.$profileID.' instead->'.function_backtrace());
230 230
 		}
231 231
 		// no validation or restoreSession for old ImapServer Object, just fetch it and return it
232
-		if ($_oldImapServerObject===true)
232
+		if ($_oldImapServerObject === true)
233 233
 		{
234
-			return new Mail('utf-8',false,$_profileID,true,$_reuseCache);
234
+			return new Mail('utf-8', false, $_profileID, true, $_reuseCache);
235 235
 		}
236 236
 		if ($_profileID != 0 && $_validate)
237 237
 		{
@@ -251,9 +251,9 @@  discard block
 block discarded – undo
251 251
 			//Cache::setSession('mail','activeProfileID',$_profileID);
252 252
 		}
253 253
 		//error_log(__METHOD__.' ('.__LINE__.') '.' RestoreSession:'.$_restoreSession.' ProfileId:'.$_profileID.' called from:'.function_backtrace());
254
-		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession===false))
254
+		if ($_profileID && (!isset(self::$instances[$_profileID]) || $_restoreSession === false))
255 255
 		{
256
-			self::$instances[$_profileID] = new Mail('utf-8',$_restoreSession,$_profileID,false,$_reuseCache);
256
+			self::$instances[$_profileID] = new Mail('utf-8', $_restoreSession, $_profileID, false, $_reuseCache);
257 257
 		}
258 258
 		else
259 259
 		{
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 				self::$instances[$_profileID]->ogServer = Mail\Account::read($_profileID)->smtpServer();
265 265
 				// TODO: merge mailprefs into userprefs, for easy treatment
266 266
 				self::$instances[$_profileID]->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
267
-				self::$instances[$_profileID]->htmlOptions  = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
267
+				self::$instances[$_profileID]->htmlOptions = self::$instances[$_profileID]->mailPreferences['htmlOptions'];
268 268
 			} catch (\Exception $e)
269 269
 			{
270 270
 				$newprofileID = Mail\Account::get_default_acc_id();
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 				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());
273 273
 				if ($newprofileID)
274 274
 				{
275
-					self::$instances[$newprofileID] = new Mail('utf-8',false,$newprofileID,false,$_reuseCache);
275
+					self::$instances[$newprofileID] = new Mail('utf-8', false, $newprofileID, false, $_reuseCache);
276 276
 					$_profileID = $newprofileID;
277 277
 				}
278 278
 				else
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 					throw $e;
281 281
 				}
282 282
 			}
283
-			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate );
283
+			self::storeActiveProfileIDToPref(self::$instances[$_profileID]->icServer, $_profileID, $_validate);
284 284
 		}
285 285
 		self::$instances[$_profileID]->profileID = $_profileID;
286 286
 		if (!isset(self::$instances[$_profileID]->idna2)) self::$instances[$_profileID]->idna2 = new Horde_Idna;
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 	 * @param boolean $_testConnection = 0
297 297
 	 * @return mixed $_profileID or false on failed ConnectionTest
298 298
 	 */
299
-	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID=0, $_testConnection=true)
299
+	public static function storeActiveProfileIDToPref($_icServerObject, $_profileID = 0, $_testConnection = true)
300 300
 	{
301 301
 		if (isset($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']) && !empty($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']))
302 302
 		{
@@ -317,12 +317,12 @@  discard block
 block discarded – undo
317 317
 		}
318 318
 		if ($oldProfileID != $_profileID)
319 319
 		{
320
-			if ($oldProfileID && $_profileID==0) $_profileID = $oldProfileID;
321
-			$GLOBALS['egw']->preferences->add('mail','ActiveProfileID',$_profileID,'user');
320
+			if ($oldProfileID && $_profileID == 0) $_profileID = $oldProfileID;
321
+			$GLOBALS['egw']->preferences->add('mail', 'ActiveProfileID', $_profileID, 'user');
322 322
 			// save prefs
323 323
 			$GLOBALS['egw']->preferences->save_repository(true);
324 324
 			$GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $_profileID;
325
-			Cache::setSession('mail','activeProfileID',$_profileID);
325
+			Cache::setSession('mail', 'activeProfileID', $_profileID);
326 326
 		}
327 327
 		return $_profileID;
328 328
 	}
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 	 * @param int $_acc_id = 0
338 338
 	 * @return int validated acc_id -> either acc_id given, or first valid one
339 339
 	 */
340
-	public static function validateProfileID($_acc_id=0)
340
+	public static function validateProfileID($_acc_id = 0)
341 341
 	{
342 342
 		if ($_acc_id)
343 343
 		{
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
 		}
357 357
 		// no account specified or specified account not found or not valid
358 358
 		// --> search existing account for first valid one and return that
359
-		foreach(Mail\Account::search($only_current_user=true, 'acc_imap_host') as $acc_id => $imap_host)
359
+		foreach (Mail\Account::search($only_current_user = true, 'acc_imap_host') as $acc_id => $imap_host)
360 360
 		{
361 361
 			if (!empty($imap_host) && ($account = Mail\Account::read($acc_id)) && $account->is_imap())
362 362
 			{
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
 	 * @param boolean $_oldImapServerObject = false
379 379
 	 * @param boolean $_reuseCache = null if null it is set to the value of $_restoreSession
380 380
 	 */
381
-	private function __construct($_displayCharset='utf-8',$_restoreSession=true, $_profileID=0, $_oldImapServerObject=false, $_reuseCache=null)
381
+	private function __construct($_displayCharset = 'utf-8', $_restoreSession = true, $_profileID = 0, $_oldImapServerObject = false, $_reuseCache = null)
382 382
 	{
383 383
 		if (is_null($_reuseCache)) $_reuseCache = $_restoreSession;
384 384
 		if (!empty($_displayCharset)) self::$displayCharset = $_displayCharset;
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 			$firstMessage = $this->sessionData['previewMessage'];
399 399
 			$this->sessionData = array();
400 400
 		}
401
-		if (!$_reuseCache) $this->forcePrefReload($_profileID,!$_reuseCache);
401
+		if (!$_reuseCache) $this->forcePrefReload($_profileID, !$_reuseCache);
402 402
 		try
403 403
 		{
404 404
 			$this->profileID = self::validateProfileID($_profileID);
@@ -409,14 +409,14 @@  discard block
 block discarded – undo
409 409
 		}
410 410
 		catch (\Exception $e)
411 411
 		{
412
-			throw new Exception(__METHOD__." failed to instanciate Mail for $_profileID / ".$this->profileID." with error:".$e->getMessage());;
412
+			throw new Exception(__METHOD__." failed to instanciate Mail for $_profileID / ".$this->profileID." with error:".$e->getMessage()); ;
413 413
 		}
414 414
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($acc->imapServer()));
415
-		$this->icServer = ($_oldImapServerObject?$acc->oldImapServer():$acc->imapServer());
415
+		$this->icServer = ($_oldImapServerObject ? $acc->oldImapServer() : $acc->imapServer());
416 416
 		$this->ogServer = $acc->smtpServer();
417 417
 		// TODO: merge mailprefs into userprefs, for easy treatment
418 418
 		$this->mailPreferences = $GLOBALS['egw_info']['user']['preferences']['mail'];
419
-		$this->htmlOptions  = $this->mailPreferences['htmlOptions'];
419
+		$this->htmlOptions = $this->mailPreferences['htmlOptions'];
420 420
 		if (isset($this->icServer->ImapServerId) && !empty($this->icServer->ImapServerId))
421 421
 		{
422 422
 			$_profileID = $this->profileID = $GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'] = $this->icServer->ImapServerId;
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 	public static function &forceEAProfileLoad($_profile_id)
435 435
 	{
436 436
 		self::unsetCachedObjects($_profile_id);
437
-		$mail = self::getInstance(false, $_profile_id,false);
437
+		$mail = self::getInstance(false, $_profile_id, false);
438 438
 		//_debug_array( $_profile_id);
439 439
 		$mail->icServer = Mail\Account::read($_profile_id)->imapServer();
440 440
 		$mail->ogServer = Mail\Account::read($_profile_id)->smtpServer();
@@ -446,11 +446,11 @@  discard block
 block discarded – undo
446 446
 	 * @param int $_profile_id
447 447
 	 * @param boolean $_resetFolderObjects
448 448
 	 */
449
-	public static function forcePrefReload($_profile_id=null,$_resetFolderObjects=true)
449
+	public static function forcePrefReload($_profile_id = null, $_resetFolderObjects = true)
450 450
 	{
451 451
 		// unset the mail_preferences session object, to force the reload/rebuild
452
-		Cache::setSession('mail','mail_preferences',serialize(array()));
453
-		Cache::setSession('emailadmin','session_data',serialize(array()));
452
+		Cache::setSession('mail', 'mail_preferences', serialize(array()));
453
+		Cache::setSession('emailadmin', 'session_data', serialize(array()));
454 454
 		if ($_resetFolderObjects) self::resetFolderObjectCache($_profile_id);
455 455
 	}
456 456
 
@@ -459,8 +459,8 @@  discard block
 block discarded – undo
459 459
 	 */
460 460
 	function restoreSessionData()
461 461
 	{
462
-		$this->sessionData = array();//Cache::getCache(Cache::SESSION,'mail','session_data',$callback=null,$callback_params=array(),$expiration=60*60*1);
463
-		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
462
+		$this->sessionData = array(); //Cache::getCache(Cache::SESSION,'mail','session_data',$callback=null,$callback_params=array(),$expiration=60*60*1);
463
+		self::$activeFolderCache = Cache::getCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
464 464
 		if (!empty(self::$activeFolderCache[$this->profileID])) $this->sessionData['mailbox'] = self::$activeFolderCache[$this->profileID];
465 465
 	}
466 466
 
@@ -470,10 +470,10 @@  discard block
 block discarded – undo
470 470
 	function saveSessionData()
471 471
 	{
472 472
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($this->sessionData)));
473
-		if (!empty($this->sessionData['mailbox'])) self::$activeFolderCache[$this->profileID]=$this->sessionData['mailbox'];
473
+		if (!empty($this->sessionData['mailbox'])) self::$activeFolderCache[$this->profileID] = $this->sessionData['mailbox'];
474 474
 		if (isset(self::$activeFolderCache) && is_array(self::$activeFolderCache))
475 475
 		{
476
-			Cache::setCache(Cache::INSTANCE,'email','activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']),self::$activeFolderCache, 60*60*10);
476
+			Cache::setCache(Cache::INSTANCE, 'email', 'activeMailbox'.trim($GLOBALS['egw_info']['user']['account_id']), self::$activeFolderCache, 60 * 60 * 10);
477 477
 		}
478 478
 	}
479 479
 
@@ -489,40 +489,40 @@  discard block
 block discarded – undo
489 489
 	 * @param int $_profileID = null default profile of user as returned by getUserDefaultProfileID
490 490
 	 * @return void
491 491
 	 */
492
-	static function unsetCachedObjects($_profileID=null)
492
+	static function unsetCachedObjects($_profileID = null)
493 493
 	{
494 494
 		if (is_null($_profileID)) $_profileID = Mail\Account::get_default_acc_id();
495 495
 		if (is_array($_profileID) && $_profileID['account_id']) $account_id = $_profileID['account_id'];
496 496
 		//error_log(__METHOD__.__LINE__.' called with ProfileID:'.array2string($_profileID).' from '.function_backtrace());
497
-		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID,'tracker_')===false)))
497
+		if (!is_array($_profileID) && (is_numeric($_profileID) || !(stripos($_profileID, 'tracker_') === false)))
498 498
 		{
499 499
 			self::resetConnectionErrorCache($_profileID);
500
-			$rawHeadersCache = Cache::getCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
500
+			$rawHeadersCache = Cache::getCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
501 501
 			if (isset($rawHeadersCache[$_profileID]))
502 502
 			{
503 503
 				unset($rawHeadersCache[$_profileID]);
504
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),$rawHeadersCache, $expiration=60*60*1);
504
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), $rawHeadersCache, $expiration = 60 * 60 * 1);
505 505
 			}
506
-			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*5);
506
+			$HierarchyDelimiterCache = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 5);
507 507
 			if (isset($HierarchyDelimiterCache[$_profileID]))
508 508
 			{
509 509
 				unset($HierarchyDelimiterCache[$_profileID]);
510
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),$HierarchyDelimiterCache, $expiration=60*60*24*5);
510
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), $HierarchyDelimiterCache, $expiration = 60 * 60 * 24 * 5);
511 511
 			}
512 512
 			//reset folderObject cache, to trigger reload
513 513
 			self::resetFolderObjectCache($_profileID);
514 514
 			//reset counter of deleted messages per folder
515
-			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*1);
515
+			$eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 1);
516 516
 			if (isset($eMailListContainsDeletedMessages[$_profileID]))
517 517
 			{
518 518
 				unset($eMailListContainsDeletedMessages[$_profileID]);
519
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),$eMailListContainsDeletedMessages, $expiration=60*60*1);
519
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), $eMailListContainsDeletedMessages, $expiration = 60 * 60 * 1);
520 520
 			}
521
-			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id),$callback=null,$callback_params=array(),$expiration=60*60*24*1);
521
+			$vacationCached = Cache::getCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $callback = null, $callback_params = array(), $expiration = 60 * 60 * 24 * 1);
522 522
 			if (isset($vacationCached[$_profileID]))
523 523
 			{
524 524
 				unset($vacationCached[$_profileID]);
525
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),$vacationCached, $expiration=60*60*24*1);
525
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), $vacationCached, $expiration = 60 * 60 * 24 * 1);
526 526
 			}
527 527
 
528 528
 			if (isset(self::$instances[$_profileID])) unset(self::$instances[$_profileID]);
@@ -530,17 +530,17 @@  discard block
 block discarded – undo
530 530
 		if (is_array($_profileID) && $_profileID['location'] == 'clear_cache')
531 531
 		{
532 532
 			// called via hook
533
-			foreach($GLOBALS['egw']->accounts->search(array('type' => 'accounts','order' => 'account_lid')) as $account)
533
+			foreach ($GLOBALS['egw']->accounts->search(array('type' => 'accounts', 'order' => 'account_lid')) as $account)
534 534
 			{
535 535
 				//error_log(__METHOD__.__LINE__.array2string($account));
536 536
 				$account_id = $account['account_id'];
537 537
 				$_profileID = null;
538
-				self::resetConnectionErrorCache($_profileID,$account_id);
539
-				self::resetFolderObjectCache($_profileID,$account_id);
540
-				Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($account_id),array(), 60*60*1);
541
-				Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($account_id),array(), 60*60*24*5);
542
-				Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($account_id),array(), 60*60*1);
543
-				Cache::setCache(Cache::INSTANCE,'email','vacationNotice'.trim($account_id),array(), 60*60*24*1);
538
+				self::resetConnectionErrorCache($_profileID, $account_id);
539
+				self::resetFolderObjectCache($_profileID, $account_id);
540
+				Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($account_id), array(), 60 * 60 * 1);
541
+				Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($account_id), array(), 60 * 60 * 24 * 5);
542
+				Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($account_id), array(), 60 * 60 * 1);
543
+				Cache::setCache(Cache::INSTANCE, 'email', 'vacationNotice'.trim($account_id), array(), 60 * 60 * 24 * 1);
544 544
 			}
545 545
 		}
546 546
 	}
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 	 * @param int $_ImapServerId the profileID to look for
552 552
 	 * @param int $account_id the egw account to look for
553 553
 	 */
554
-	static function resetConnectionErrorCache($_ImapServerId=null,$account_id=null)
554
+	static function resetConnectionErrorCache($_ImapServerId = null, $account_id = null)
555 555
 	{
556 556
 		//error_log(__METHOD__.' ('.__LINE__.') '.' for Profile:'.array2string($_ImapServerId) .' for user:'.trim($account_id));
557 557
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
@@ -569,19 +569,19 @@  discard block
 block discarded – undo
569 569
 		}
570 570
 		else
571 571
 		{
572
-			$isConError = Cache::getCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id));
572
+			$isConError = Cache::getCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id));
573 573
 			if (isset($isConError[$_ImapServerId]))
574 574
 			{
575 575
 				unset($isConError[$_ImapServerId]);
576 576
 			}
577
-			$waitOnFailure = Cache::getCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),null,array(),60*60*2);
577
+			$waitOnFailure = Cache::getCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), null, array(), 60 * 60 * 2);
578 578
 			if (isset($waitOnFailure[$_ImapServerId]))
579 579
 			{
580 580
 				unset($waitOnFailure[$_ImapServerId]);
581 581
 			}
582 582
 		}
583
-		Cache::setCache(Cache::INSTANCE,'email','icServerSIEVE_connectionError'.trim($account_id),$isConError,60*15);
584
-		Cache::setCache(Cache::INSTANCE,'email','ActiveSyncWaitOnFailure'.trim($account_id),$waitOnFailure,60*60*2);
583
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerSIEVE_connectionError'.trim($account_id), $isConError, 60 * 15);
584
+		Cache::setCache(Cache::INSTANCE, 'email', 'ActiveSyncWaitOnFailure'.trim($account_id), $waitOnFailure, 60 * 60 * 2);
585 585
 	}
586 586
 
587 587
 	/**
@@ -590,13 +590,13 @@  discard block
 block discarded – undo
590 590
 	 * @param int $_ImapServerId the profileID to look for
591 591
 	 * @param int $account_id the egw account to look for
592 592
 	 */
593
-	static function resetFolderObjectCache($_ImapServerId=null,$account_id=null)
593
+	static function resetFolderObjectCache($_ImapServerId = null, $account_id = null)
594 594
 	{
595 595
 		//error_log(__METHOD__.' ('.__LINE__.') '.' called for Profile:'.array2string($_ImapServerId).'->'.function_backtrace());
596 596
 		if (is_null($account_id)) $account_id = $GLOBALS['egw_info']['user']['account_id'];
597 597
 		// on [location] => verify_settings we coud either use [prefs] => Array([ActiveProfileID] => 9, .. as $_ImapServerId
598 598
 		// or treat it as not given. we try that path
599
-		if (is_null($_ImapServerId)||is_array($_ImapServerId))
599
+		if (is_null($_ImapServerId) || is_array($_ImapServerId))
600 600
 		{
601 601
 			$folders2return = array();
602 602
 			$folderInfo = array();
@@ -605,12 +605,12 @@  discard block
 block discarded – undo
605 605
 		}
606 606
 		else
607 607
 		{
608
-			$folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),null,array(),60*60*1);
608
+			$folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), null, array(), 60 * 60 * 1);
609 609
 			if (!empty($folders2return) && isset($folders2return[$_ImapServerId]))
610 610
 			{
611 611
 				unset($folders2return[$_ImapServerId]);
612 612
 			}
613
-			$folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),null,array(),60*60*5);
613
+			$folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), null, array(), 60 * 60 * 5);
614 614
 			if (!empty($folderInfo) && isset($folderInfo[$_ImapServerId]))
615 615
 			{
616 616
 				unset($folderInfo[$_ImapServerId]);
@@ -622,23 +622,23 @@  discard block
 block discarded – undo
622 622
 				unset($lastFolderUsedForMove[$_ImapServerId]);
623 623
 			}
624 624
 			*/
625
-			$folderBasicInfo = Cache::getCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),null,array(),60*60*1);
625
+			$folderBasicInfo = Cache::getCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), null, array(), 60 * 60 * 1);
626 626
 			if (!empty($folderBasicInfo) && isset($folderBasicInfo[$_ImapServerId]))
627 627
 			{
628 628
 				unset($folderBasicInfo[$_ImapServerId]);
629 629
 			}
630
-			$_specialUseFolders = Cache::getCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),null,array(),60*60*12);
630
+			$_specialUseFolders = Cache::getCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), null, array(), 60 * 60 * 12);
631 631
 			if (!empty($_specialUseFolders) && isset($_specialUseFolders[$_ImapServerId]))
632 632
 			{
633 633
 				unset($_specialUseFolders[$_ImapServerId]);
634
-				self::$specialUseFolders=null;
634
+				self::$specialUseFolders = null;
635 635
 			}
636 636
 		}
637
-		Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($account_id),$folders2return, 60*60*1);
638
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($account_id),$folderInfo,60*60*5);
637
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($account_id), $folders2return, 60 * 60 * 1);
638
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($account_id), $folderInfo, 60 * 60 * 5);
639 639
 		//Cache::setCache(Cache::INSTANCE,'email','lastFolderUsedForMove'.trim($account_id),$lastFolderUsedForMove,$expiration=60*60*1);
640
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($account_id),$folderBasicInfo,60*60*1);
641
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($account_id),$_specialUseFolders,60*60*12);
640
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($account_id), $folderBasicInfo, 60 * 60 * 1);
641
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($account_id), $_specialUseFolders, 60 * 60 * 12);
642 642
 	}
643 643
 
644 644
 	/**
@@ -659,15 +659,15 @@  discard block
 block discarded – undo
659 659
 	 * @param string $_profileID the ID of the mailaccount to check for identities, if null current mail-account is used
660 660
 	 * @return array - array(email=>realname)
661 661
 	 */
662
-	function getUserEMailAddresses($_profileID=null)
662
+	function getUserEMailAddresses($_profileID = null)
663 663
 	{
664
-		$acc = Mail\Account::read((!empty($_profileID)?$_profileID:$this->profileID));
664
+		$acc = Mail\Account::read((!empty($_profileID) ? $_profileID : $this->profileID));
665 665
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($acc));
666 666
 		$identities = Mail\Account::identities($acc);
667 667
 
668 668
 		$userEMailAdresses = array($acc['ident_email']=>$acc['ident_realname']);
669 669
 
670
-		foreach($identities as $ik => $ident) {
670
+		foreach ($identities as $ik => $ident) {
671 671
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
672 672
 			$identity = Mail\Account::read_identity($ik);
673 673
 			if (!empty($identity['ident_email']) && !isset($userEMailAdresses[$identity['ident_email']])) $userEMailAdresses[$identity['ident_email']] = $identity['ident_realname'];
@@ -682,19 +682,19 @@  discard block
 block discarded – undo
682 682
 	 * @param boolean $resolve_placeholders wether or not resolve possible placeholders in identities
683 683
 	 * @return array - array(email=>realname)
684 684
 	 */
685
-	static function getAllIdentities($_accountToSearch=null,$resolve_placeholders=false)
685
+	static function getAllIdentities($_accountToSearch = null, $resolve_placeholders = false)
686 686
 	{
687 687
 		$userEMailAdresses = array();
688
-		foreach(Mail\Account::search($only_current_user=($_accountToSearch?$_accountToSearch:true), $just_name=true) as $acc_id => $identity_name)
688
+		foreach (Mail\Account::search($only_current_user = ($_accountToSearch ? $_accountToSearch : true), $just_name = true) as $acc_id => $identity_name)
689 689
 		{
690
-			$acc = Mail\Account::read($acc_id,($_accountToSearch?$_accountToSearch:null));
691
-			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']);
690
+			$acc = Mail\Account::read($acc_id, ($_accountToSearch ? $_accountToSearch : null));
691
+			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']);
692 692
 
693
-			foreach(Mail\Account::identities($acc) as $ik => $ident) {
693
+			foreach (Mail\Account::identities($acc) as $ik => $ident) {
694 694
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
695
-				$identity = Mail\Account::read_identity($ik,$resolve_placeholders);
695
+				$identity = Mail\Account::read_identity($ik, $resolve_placeholders);
696 696
 				//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
697
-				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']);
697
+				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']);
698 698
 			}
699 699
 		}
700 700
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($userEMailAdresses));
@@ -714,9 +714,9 @@  discard block
 block discarded – undo
714 714
 			$account = Mail\Account::read($account);
715 715
 		}
716 716
 		$userEMailAdresses = array();
717
-		foreach(Mail\Account::identities($account, true, 'params') as $ik => $ident) {
717
+		foreach (Mail\Account::identities($account, true, 'params') as $ik => $ident) {
718 718
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($ident));
719
-			$identity = Mail\Account::read_identity($ik,true,null,$account);
719
+			$identity = Mail\Account::read_identity($ik, true, null, $account);
720 720
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.$ik.'->'.array2string($identity));
721 721
 			// standardIdentity has ident_id==acc_id (as it is done within account->identities)
722 722
 			if (empty($identity['ident_id'])) $identity['ident_id'] = $identity['acc_id'];
@@ -743,9 +743,9 @@  discard block
 block discarded – undo
743 743
 	function getDefaultIdentity()
744 744
 	{
745 745
 		// retrieve the signature accociated with the identity
746
-		$id = $this->getIdentitiesWithAccounts($_accountData=array());
747
-		foreach(Mail\Account::identities($_accountData[$this->profileID] ?
748
-			$this->profileID : $_accountData[$id],false,'ident_id') as $accountData)
746
+		$id = $this->getIdentitiesWithAccounts($_accountData = array());
747
+		foreach (Mail\Account::identities($_accountData[$this->profileID] ?
748
+			$this->profileID : $_accountData[$id], false, 'ident_id') as $accountData)
749 749
 		{
750 750
 			return $accountData;
751 751
 		}
@@ -761,13 +761,13 @@  discard block
 block discarded – undo
761 761
 	{
762 762
 		// account select box
763 763
 		$selectedID = $this->profileID;
764
-		$allAccountData = Mail\Account::search($only_current_user=true, false, null);
764
+		$allAccountData = Mail\Account::search($only_current_user = true, false, null);
765 765
 		if ($allAccountData) {
766
-			$rememberFirst=$selectedFound=null;
766
+			$rememberFirst = $selectedFound = null;
767 767
 			foreach ($allAccountData as $tmpkey => $icServers)
768 768
 			{
769 769
 				if (is_null($rememberFirst)) $rememberFirst = $tmpkey;
770
-				if ($tmpkey == $selectedID) $selectedFound=true;
770
+				if ($tmpkey == $selectedID) $selectedFound = true;
771 771
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($icServers->acc_imap_host));
772 772
 				$host = $icServers->acc_imap_host;
773 773
 				if (empty($host)) continue;
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Key:'.$tmpkey.'->'.array2string($identities[$icServers->acc_id]));
776 776
 			}
777 777
 		}
778
-		return ($selectedFound?$selectedID:$rememberFirst);
778
+		return ($selectedFound ? $selectedID : $rememberFirst);
779 779
 	}
780 780
 
781 781
 	/**
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
 	 * @var boolean $fullString full or false=NamePart only is returned
786 786
 	 * @return string - constructed of identity object data as defined in mailConfig
787 787
 	 */
788
-	static function generateIdentityString($identity, $fullString=true)
788
+	static function generateIdentityString($identity, $fullString = true)
789 789
 	{
790 790
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($identity));
791 791
 		//if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
@@ -796,16 +796,16 @@  discard block
 block discarded – undo
796 796
 		{
797 797
 			case 'email';
798 798
 				//$retData = str_replace('@',' ',$identity->emailAddress).($fullString===true?' <'.$identity->emailAddress.'>':'');
799
-				$retData = $identity['ident_email'].($fullString===true?' <'.$identity['ident_email'].'>':'');
799
+				$retData = $identity['ident_email'].($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
800 800
 				break;
801 801
 			case 'nameNemail';
802
-				$retData = (!empty($identity['ident_realname'])?$identity['ident_realname']:substr_replace($identity['ident_email'],'',strpos($identity['ident_email'],'@'))).($fullString===true?' <'.$identity['ident_email'].'>':'');
802
+				$retData = (!empty($identity['ident_realname']) ? $identity['ident_realname'] : substr_replace($identity['ident_email'], '', strpos($identity['ident_email'], '@'))).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
803 803
 				break;
804 804
 			case 'orgNemail';
805
-				$retData = (!empty($identity['ident_org'])?$identity['ident_org']:substr_replace($identity['ident_email'],'',0,strpos($identity['ident_email'],'@')+1)).($fullString===true?' <'.$identity['ident_email'].'>':'');
805
+				$retData = (!empty($identity['ident_org']) ? $identity['ident_org'] : substr_replace($identity['ident_email'], '', 0, strpos($identity['ident_email'], '@') + 1)).($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
806 806
 				break;
807 807
 			default:
808
-				$retData = $identity['ident_realname'].(!empty($identity['ident_org'])?' '.$identity['ident_org']:'').($fullString===true?' <'.$identity['ident_email'].'>':'');
808
+				$retData = $identity['ident_realname'].(!empty($identity['ident_org']) ? ' '.$identity['ident_org'] : '').($fullString === true ? ' <'.$identity['ident_email'].'>' : '');
809 809
 		}
810 810
 		return $retData;
811 811
 	}
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
 	 */
831 831
 	function reopen($_foldername)
832 832
 	{
833
-		if (self::$debugTimes) $starttime = microtime (true);
833
+		if (self::$debugTimes) $starttime = microtime(true);
834 834
 
835 835
 		//error_log(__METHOD__.' ('.__LINE__.') '."('$_foldername') ".function_backtrace());
836 836
 		// TODO: trying to reduce traffic to the IMAP Server here, introduces problems with fetching the bodies of
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 			}
846 846
 			$folderOpened = $_foldername;
847 847
 		//}
848
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'Folder:'.$_foldername,__METHOD__.' ('.__LINE__.') ');
848
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'Folder:'.$_foldername, __METHOD__.' ('.__LINE__.') ');
849 849
 	}
850 850
 
851 851
 
@@ -856,15 +856,15 @@  discard block
 block discarded – undo
856 856
 	 * @throws Horde_Imap_Client_Exception on connection error or authentication failure
857 857
 	 * @throws InvalidArgumentException on missing credentials
858 858
 	 */
859
-	function openConnection($_icServerID=0)
859
+	function openConnection($_icServerID = 0)
860 860
 	{
861 861
 		//error_log( "-------------------------->open connection ".function_backtrace());
862 862
 		//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.array2string($this->icServer));
863
-		if (self::$debugTimes) $starttime = microtime (true);
864
-		$mailbox=null;
863
+		if (self::$debugTimes) $starttime = microtime(true);
864
+		$mailbox = null;
865 865
 		try
866 866
 		{
867
-			if(isset($this->sessionData['mailbox'])&&$this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
867
+			if (isset($this->sessionData['mailbox']) && $this->folderExists($this->sessionData['mailbox'])) $mailbox = $this->sessionData['mailbox'];
868 868
 			if (empty($mailbox)) $mailbox = $this->icServer->getCurrentMailbox();
869 869
 /*
870 870
 			if (isset(Mail\Imap::$supports_keywords[$_icServerID]))
@@ -891,7 +891,7 @@  discard block
 block discarded – undo
891 891
 			error_log(__METHOD__.' ('.__LINE__.') '."->open connection for Server with profileID:".$_icServerID." trying to examine ($mailbox) failed!".$e->getMessage());
892 892
 			throw new Exception(__METHOD__." failed to ".__METHOD__." on Profile to $_icServerID while trying to examine $mailbox:".$e->getMessage());
893 893
 		}
894
-		if (self::$debugTimes) self::logRunTimes($starttime,null,'ProfileID:'.$_icServerID,__METHOD__.' ('.__LINE__.') ');
894
+		if (self::$debugTimes) self::logRunTimes($starttime, null, 'ProfileID:'.$_icServerID, __METHOD__.' ('.__LINE__.') ');
895 895
 	}
896 896
 
897 897
 	/**
@@ -905,13 +905,13 @@  discard block
 block discarded – undo
905 905
 		static $quota;
906 906
 		if (isset($quota)) return $quota;
907 907
 		$this->icServer->getCurrentMailbox();
908
-		if(!$this->icServer->hasCapability('QUOTA')) {
908
+		if (!$this->icServer->hasCapability('QUOTA')) {
909 909
 			$quota = false;
910 910
 			return false;
911 911
 		}
912 912
 		$quota = $this->icServer->getStorageQuotaRoot('INBOX');
913 913
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($quota));
914
-		if(is_array($quota)) {
914
+		if (is_array($quota)) {
915 915
 			$quota = array(
916 916
 				'usage'	=> $quota['USED'],
917 917
 				'limit'	=> $quota['QMAX'],
@@ -929,10 +929,10 @@  discard block
 block discarded – undo
929 929
 	 *
930 930
 	 * @return int - timeout (either set or default 20/10)
931 931
 	 */
932
-	static function getTimeOut($_use='IMAP')
932
+	static function getTimeOut($_use = 'IMAP')
933 933
 	{
934 934
 		$timeout = $GLOBALS['egw_info']['user']['preferences']['mail']['connectionTimeout'];
935
-		if (empty($timeout)) $timeout = ($_use=='SIEVE'?10:20); // this is the default value
935
+		if (empty($timeout)) $timeout = ($_use == 'SIEVE' ? 10 : 20); // this is the default value
936 936
 		return $timeout;
937 937
 	}
938 938
 
@@ -953,18 +953,18 @@  discard block
 block discarded – undo
953 953
 		if (is_null($nameSpace)) $nameSpace = $this->icServer->getNameSpaceArray();
954 954
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($nameSpace));
955 955
 		if (is_array($nameSpace)) {
956
-			foreach($nameSpace as $type => $singleNameSpaceArray)
956
+			foreach ($nameSpace as $type => $singleNameSpaceArray)
957 957
 			{
958 958
 				foreach ($singleNameSpaceArray as $singleNameSpace)
959 959
 				{
960 960
 					$_foldersNameSpace = array();
961
-					if($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail')||$this->folderExists('INBOX')))
961
+					if ($type == 'personal' && $singleNameSpace['name'] == '#mh/' && ($this->folderExists('Mail') || $this->folderExists('INBOX')))
962 962
 					{
963 963
 						$_foldersNameSpace['prefix_present'] = 'forced';
964 964
 						// uw-imap server with mailbox prefix or dovecot maybe
965
-						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail')?'Mail':(!empty($singleNameSpace['name'])?$singleNameSpace['name']:''));
965
+						$_foldersNameSpace['prefix'] = ($this->folderExists('Mail') ? 'Mail' : (!empty($singleNameSpace['name']) ? $singleNameSpace['name'] : ''));
966 966
 					}
967
-					elseif($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
967
+					elseif ($type == 'personal' && ($singleNameSpace['name'] == '#mh/') && $this->folderExists('mail'))
968 968
 					{
969 969
 						$_foldersNameSpace['prefix_present'] = 'forced';
970 970
 						// uw-imap server with mailbox prefix or dovecot maybe
@@ -973,9 +973,9 @@  discard block
 block discarded – undo
973 973
 						$_foldersNameSpace['prefix_present'] = !empty($singleNameSpace['name']);
974 974
 						$_foldersNameSpace['prefix'] = $singleNameSpace['name'];
975 975
 					}
976
-					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter']?$singleNameSpace['delimiter']:$delimiter);
976
+					$_foldersNameSpace['delimiter'] = ($singleNameSpace['delimiter'] ? $singleNameSpace['delimiter'] : $delimiter);
977 977
 					$_foldersNameSpace['type'] = $type;
978
-					$foldersNameSpace[] =$_foldersNameSpace;
978
+					$foldersNameSpace[] = $_foldersNameSpace;
979 979
 				}
980 980
 				//echo "############## $type->".print_r($foldersNameSpace[$type],true)." ###################<br>";
981 981
 			}
@@ -993,10 +993,10 @@  discard block
 block discarded – undo
993 993
 	 */
994 994
 	function getFolderPrefixFromNamespace($nameSpace, $folderName)
995 995
 	{
996
-		foreach($nameSpace as &$singleNameSpace)
996
+		foreach ($nameSpace as &$singleNameSpace)
997 997
 		{
998 998
 			//if (substr($singleNameSpace['prefix'],0,strlen($folderName))==$folderName) return $singleNameSpace['prefix'];
999
-			if (substr($folderName,0,strlen($singleNameSpace['prefix']))==$singleNameSpace['prefix']) return $singleNameSpace['prefix'];
999
+			if (substr($folderName, 0, strlen($singleNameSpace['prefix'])) == $singleNameSpace['prefix']) return $singleNameSpace['prefix'];
1000 1000
 		}
1001 1001
 		return "";
1002 1002
 	}
@@ -1007,12 +1007,12 @@  discard block
 block discarded – undo
1007 1007
 	 * @var boolean $_useCache
1008 1008
 	 * @return string the hierarchyDelimiter
1009 1009
 	 */
1010
-	function getHierarchyDelimiter($_useCache=true)
1010
+	function getHierarchyDelimiter($_useCache = true)
1011 1011
 	{
1012 1012
 		static $HierarchyDelimiter = null;
1013
-		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*24*5);
1014
-		if ($_useCache===false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1015
-		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId])&&!empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1013
+		if (is_null($HierarchyDelimiter)) $HierarchyDelimiter = Cache::getCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 24 * 5);
1014
+		if ($_useCache === false) unset($HierarchyDelimiter[$this->icServer->ImapServerId]);
1015
+		if (isset($HierarchyDelimiter[$this->icServer->ImapServerId]) && !empty($HierarchyDelimiter[$this->icServer->ImapServerId]))
1016 1016
 		{
1017 1017
 			return $HierarchyDelimiter[$this->icServer->ImapServerId];
1018 1018
 		}
@@ -1022,12 +1022,12 @@  discard block
 block discarded – undo
1022 1022
 			$this->icServer->getCurrentMailbox();
1023 1023
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = $this->icServer->getDelimiter();
1024 1024
 		}
1025
-		catch(\Exception $e)
1025
+		catch (\Exception $e)
1026 1026
 		{
1027 1027
 			unset($e);
1028 1028
 			$HierarchyDelimiter[$this->icServer->ImapServerId] = '/';
1029 1029
 		}
1030
-		Cache::setCache(Cache::INSTANCE,'email','HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']),$HierarchyDelimiter, 60*60*24*5);
1030
+		Cache::setCache(Cache::INSTANCE, 'email', 'HierarchyDelimiter'.trim($GLOBALS['egw_info']['user']['account_id']), $HierarchyDelimiter, 60 * 60 * 24 * 5);
1031 1031
 		return $HierarchyDelimiter[$this->icServer->ImapServerId];
1032 1032
 	}
1033 1033
 
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 	{
1041 1041
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$this->icServer->ImapServerId.' Connected:'.$this->icServer->_connected);
1042 1042
 		static $_specialUseFolders = null;
1043
-		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);
1043
+		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);
1044 1044
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_trash));
1045 1045
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_sent));
1046 1046
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($this->icServer->acc_folder_draft));
@@ -1048,20 +1048,20 @@  discard block
 block discarded – undo
1048 1048
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1049 1049
 		if (isset($_specialUseFolders[$this->icServer->ImapServerId]) && !empty($_specialUseFolders[$this->icServer->ImapServerId]))
1050 1050
 			return $_specialUseFolders[$this->icServer->ImapServerId];
1051
-		$_specialUseFolders[$this->icServer->ImapServerId]=array();
1051
+		$_specialUseFolders[$this->icServer->ImapServerId] = array();
1052 1052
 		//if (!empty($this->icServer->acc_folder_trash) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]))
1053
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash]='Trash';
1053
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_trash] = 'Trash';
1054 1054
 		//if (!empty($this->icServer->acc_folder_draft) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]))
1055
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft]='Drafts';
1055
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_draft] = 'Drafts';
1056 1056
 		//if (!empty($this->icServer->acc_folder_sent) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]))
1057
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent]='Sent';
1057
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_sent] = 'Sent';
1058 1058
 		//if (!empty($this->icServer->acc_folder_template) && !isset($_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]))
1059
-			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template]='Templates';
1060
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk]='Junk';
1061
-		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive]='Archive';
1059
+			$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_template] = 'Templates';
1060
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_junk] = 'Junk';
1061
+		$_specialUseFolders[$this->icServer->ImapServerId][$this->icServer->acc_folder_archive] = 'Archive';
1062 1062
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_specialUseFolders));//.'<->'.array2string($this->icServer));
1063 1063
 		self::$specialUseFolders = $_specialUseFolders[$this->icServer->ImapServerId];
1064
-		Cache::setCache(Cache::INSTANCE,'email','specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$_specialUseFolders, 60*60*24*5);
1064
+		Cache::setCache(Cache::INSTANCE, 'email', 'specialUseFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $_specialUseFolders, 60 * 60 * 24 * 5);
1065 1065
 		return $_specialUseFolders[$this->icServer->ImapServerId];
1066 1066
 	}
1067 1067
 
@@ -1075,8 +1075,8 @@  discard block
 block discarded – undo
1075 1075
 	function folderIsSelectable($folderToSelect)
1076 1076
 	{
1077 1077
 		$retval = true;
1078
-		if($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect,false,true))) {
1079
-			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']),'noselect')!==false)
1078
+		if ($folderToSelect && ($folderStatus = $this->getFolderStatus($folderToSelect, false, true))) {
1079
+			if (!empty($folderStatus['attributes']) && stripos(array2string($folderStatus['attributes']), 'noselect') !== false)
1080 1080
 			{
1081 1081
 				$retval = false;
1082 1082
 			}
@@ -1096,7 +1096,7 @@  discard block
 block discarded – undo
1096 1096
 	 *
1097 1097
 	 * @throws Exception
1098 1098
 	 */
1099
-	function _getStatus($folderName,$ignoreStatusCache=false)
1099
+	function _getStatus($folderName, $ignoreStatusCache = false)
1100 1100
 	{
1101 1101
 		static $folderStatus = null;
1102 1102
 		if (!$ignoreStatusCache && isset($folderStatus[$this->icServer->ImapServerId][$folderName]))
@@ -1106,7 +1106,7 @@  discard block
 block discarded – undo
1106 1106
 		}
1107 1107
 		try
1108 1108
 		{
1109
-			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName,$ignoreStatusCache);
1109
+			$folderStatus[$this->icServer->ImapServerId][$folderName] = $this->icServer->getStatus($folderName, $ignoreStatusCache);
1110 1110
 		}
1111 1111
 		catch (\Exception $e)
1112 1112
 		{
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
 	 * @param fetchSubscribedInfo bool fetch Subscribed Info on folder
1127 1127
 	 * @return array
1128 1128
 	 */
1129
-	function getFolderStatus($_folderName,$ignoreStatusCache=false,$basicInfoOnly=false,$fetchSubscribedInfo=true)
1129
+	function getFolderStatus($_folderName, $ignoreStatusCache = false, $basicInfoOnly = false, $fetchSubscribedInfo = true)
1130 1130
 	{
1131 1131
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." called with:$_folderName,$ignoreStatusCache,$basicInfoOnly");
1132 1132
 		if (!is_string($_folderName) || empty($_folderName)) // something is wrong. Do not proceed
@@ -1139,7 +1139,7 @@  discard block
 block discarded – undo
1139 1139
 		{
1140 1140
 			$folderInfoCache = $folderBasicInfo[$this->profileID];
1141 1141
 		}
1142
-		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache==false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1142
+		if (isset($folderInfoCache[$_folderName]) && $ignoreStatusCache == false && $basicInfoOnly) return $folderInfoCache[$_folderName];
1143 1143
 		$retValue = array();
1144 1144
 		$retValue['subscribed'] = false;
1145 1145
 /*
@@ -1157,28 +1157,28 @@  discard block
 block discarded – undo
1157 1157
 			if (is_array($ret))
1158 1158
 			{
1159 1159
 				$retkeys = array_keys($ret);
1160
-				if ($retkeys[0]==$_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1160
+				if ($retkeys[0] == $_folderName) $folderInfoCache[$_folderName] = $ret[$retkeys[0]];
1161 1161
 			}
1162 1162
 			else
1163 1163
 			{
1164
-				$folderInfoCache[$_folderName]=false;
1164
+				$folderInfoCache[$_folderName] = false;
1165 1165
 			}
1166 1166
 		}
1167 1167
 		$folderInfo = $folderInfoCache[$_folderName];
1168 1168
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($folderInfo).'->'.function_backtrace());
1169
-		if($ignoreStatusCache||!$folderInfo|| !is_array($folderInfo)) {
1169
+		if ($ignoreStatusCache || !$folderInfo || !is_array($folderInfo)) {
1170 1170
 			try
1171 1171
 			{
1172
-				$folderInfo = $this->_getStatus($_folderName,$ignoreStatusCache);
1172
+				$folderInfo = $this->_getStatus($_folderName, $ignoreStatusCache);
1173 1173
 			}
1174 1174
 			catch (\Exception $e)
1175 1175
 			{
1176
-				$folderInfo=null;
1176
+				$folderInfo = null;
1177 1177
 			}
1178 1178
 			if (!is_array($folderInfo))
1179 1179
 			{
1180 1180
 				// no folder info, but there is a status returned for the folder: something is wrong, try to cope with it
1181
-				$folderInfo = is_array($folderInfo)?$folderInfo:array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1181
+				$folderInfo = is_array($folderInfo) ? $folderInfo : array('HIERACHY_DELIMITER'=>$this->getHierarchyDelimiter(),
1182 1182
 					'ATTRIBUTES' => '');
1183 1183
 				if (!isset($folderInfo['HIERACHY_DELIMITER']) || empty($folderInfo['HIERACHY_DELIMITER']) || (isset($folderInfo['delimiter']) && empty($folderInfo['delimiter'])))
1184 1184
 				{
@@ -1190,24 +1190,24 @@  discard block
 block discarded – undo
1190 1190
 		#if(!is_array($folderInfo)) {
1191 1191
 		#	return false;
1192 1192
 		#}
1193
-		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER']?$folderInfo['HIERACHY_DELIMITER']:$folderInfo['delimiter']);
1194
-		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES']?$folderInfo['ATTRIBUTES']:$folderInfo['attributes']);
1195
-		$shortNameParts			= explode($retValue['delimiter'], $_folderName);
1193
+		$retValue['delimiter']		= (isset($folderInfo['HIERACHY_DELIMITER']) && $folderInfo['HIERACHY_DELIMITER'] ? $folderInfo['HIERACHY_DELIMITER'] : $folderInfo['delimiter']);
1194
+		$retValue['attributes']		= (isset($folderInfo['ATTRIBUTES']) && $folderInfo['ATTRIBUTES'] ? $folderInfo['ATTRIBUTES'] : $folderInfo['attributes']);
1195
+		$shortNameParts = explode($retValue['delimiter'], $_folderName);
1196 1196
 		$retValue['shortName']		= array_pop($shortNameParts);
1197 1197
 		$retValue['displayName']	= $_folderName;
1198
-		$retValue['shortDisplayName']	= $retValue['shortName'];
1199
-		if(strtoupper($retValue['shortName']) == 'INBOX') {
1200
-			$retValue['displayName']	= lang('INBOX');
1201
-			$retValue['shortDisplayName']	= lang('INBOX');
1198
+		$retValue['shortDisplayName'] = $retValue['shortName'];
1199
+		if (strtoupper($retValue['shortName']) == 'INBOX') {
1200
+			$retValue['displayName'] = lang('INBOX');
1201
+			$retValue['shortDisplayName'] = lang('INBOX');
1202 1202
 		}
1203 1203
 		// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
1204
-		elseif (in_array($retValue['shortName'],self::$autoFolders))
1204
+		elseif (in_array($retValue['shortName'], self::$autoFolders))
1205 1205
 		{
1206 1206
 			$retValue['displayName'] = $retValue['shortDisplayName'] = lang($retValue['shortName']);
1207 1207
 		}
1208
-		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName]=$retValue;
1208
+		if ($folderInfo) $folderBasicInfo[$this->profileID][$_folderName] = $retValue;
1209 1209
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.$_folderName.array2string($retValue['attributes']));
1210
-		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']),'noselect')!==false))
1210
+		if ($basicInfoOnly || (isset($retValue['attributes']) && stripos(array2string($retValue['attributes']), 'noselect') !== false))
1211 1211
 		{
1212 1212
 			return $retValue;
1213 1213
 		}
@@ -1220,12 +1220,12 @@  discard block
 block discarded – undo
1220 1220
 		if (is_null($nameSpace) || empty($nameSpace[$this->profileID])) $nameSpace[$this->profileID] = $this->_getNameSpaces();
1221 1221
 		if (!empty($nameSpace[$this->profileID]))
1222 1222
 		{
1223
-			$nsNoPersonal=array();
1224
-			foreach($nameSpace[$this->profileID] as &$ns)
1223
+			$nsNoPersonal = array();
1224
+			foreach ($nameSpace[$this->profileID] as &$ns)
1225 1225
 			{
1226
-				if ($ns['type']!='personal') $nsNoPersonal[]=$ns;
1226
+				if ($ns['type'] != 'personal') $nsNoPersonal[] = $ns;
1227 1227
 			}
1228
-			$nameSpace[$this->profileID]=$nsNoPersonal;
1228
+			$nameSpace[$this->profileID] = $nsNoPersonal;
1229 1229
 		}
1230 1230
 		if (is_null($prefix) || empty($prefix[$this->profileID]) || empty($prefix[$this->profileID][$_folderName])) $prefix[$this->profileID][$_folderName] = $this->getFolderPrefixFromNamespace($nameSpace[$this->profileID], $_folderName);
1231 1231
 
@@ -1234,32 +1234,32 @@  discard block
 block discarded – undo
1234 1234
 			$subscribedFolders[$this->profileID] = $this->icServer->listSubscribedMailboxes();
1235 1235
 		}
1236 1236
 
1237
-		if($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName,$subscribedFolders[$this->profileID])) {
1237
+		if ($fetchSubscribedInfo && is_array($subscribedFolders[$this->profileID]) && in_array($_folderName, $subscribedFolders[$this->profileID])) {
1238 1238
 			$retValue['subscribed'] = true;
1239 1239
 		}
1240 1240
 
1241 1241
 		try
1242 1242
 		{
1243 1243
 			//$folderStatus = $this->_getStatus($_folderName,$ignoreStatusCache);
1244
-			$folderStatus = $this->getMailBoxCounters($_folderName,false);
1245
-			$retValue['messages']		= $folderStatus['MESSAGES'];
1244
+			$folderStatus = $this->getMailBoxCounters($_folderName, false);
1245
+			$retValue['messages'] = $folderStatus['MESSAGES'];
1246 1246
 			$retValue['recent']		= $folderStatus['RECENT'];
1247
-			$retValue['uidnext']		= $folderStatus['UIDNEXT'];
1248
-			$retValue['uidvalidity']	= $folderStatus['UIDVALIDITY'];
1247
+			$retValue['uidnext'] = $folderStatus['UIDNEXT'];
1248
+			$retValue['uidvalidity'] = $folderStatus['UIDVALIDITY'];
1249 1249
 			$retValue['unseen']		= $folderStatus['UNSEEN'];
1250 1250
 			if (//$retValue['unseen']==0 &&
1251 1251
 				(isset($this->mailPreferences['trustServersUnseenInfo']) && // some servers dont serve the UNSEEN information
1252
-				$this->mailPreferences['trustServersUnseenInfo']==false) ||
1252
+				$this->mailPreferences['trustServersUnseenInfo'] == false) ||
1253 1253
 				(isset($this->mailPreferences['trustServersUnseenInfo']) &&
1254
-				$this->mailPreferences['trustServersUnseenInfo']==2 &&
1255
-				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName,$prefix[$this->profileID][$_folderName]) !== false)
1254
+				$this->mailPreferences['trustServersUnseenInfo'] == 2 &&
1255
+				$prefix[$this->profileID][$_folderName] != '' && stripos($_folderName, $prefix[$this->profileID][$_folderName]) !== false)
1256 1256
 			)
1257 1257
 			{
1258 1258
 				//error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($prefix,true).' TS:'.$this->mailPreferences['trustServersUnseenInfo']);
1259 1259
 				// we filter for the combined status of unseen and undeleted, as this is what we show in list
1260 1260
 				try
1261 1261
 				{
1262
-					$sortResult = $this->getSortedList($_folderName, $_sort=0, $_reverse=1, array('status'=>array('UNSEEN','UNDELETED')),$byUid=true,false);
1262
+					$sortResult = $this->getSortedList($_folderName, $_sort = 0, $_reverse = 1, array('status'=>array('UNSEEN', 'UNDELETED')), $byUid = true, false);
1263 1263
 					$retValue['unseen'] = $sortResult['count'];
1264 1264
 				}
1265 1265
 				catch (\Exception $ee)
@@ -1270,7 +1270,7 @@  discard block
 block discarded – undo
1270 1270
 		}
1271 1271
 		catch (\Exception $e)
1272 1272
 		{
1273
-			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(),true));
1273
+			if (self::$debug) error_log(__METHOD__." returned folderStatus for Folder $_folderName:".print_r($e->getMessage(), true));
1274 1274
 		}
1275 1275
 
1276 1276
 		return $retValue;
@@ -1292,7 +1292,7 @@  discard block
 block discarded – undo
1292 1292
 	 * @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))
1293 1293
 	 * @return array result as array(header=>array,total=>int,first=>int,last=>int)
1294 1294
 	 */
1295
-	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly=null, $_cacheResult=true, $_fetchPreviews=false)
1295
+	function getHeaders($_folderName, $_startMessage, $_numberOfMessages, $_sort, $_reverse, $_filter, $_thisUIDOnly = null, $_cacheResult = true, $_fetchPreviews = false)
1296 1296
 	{
1297 1297
 		//self::$debug=true;
1298 1298
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.function_backtrace());
@@ -1305,7 +1305,7 @@  discard block
 block discarded – undo
1305 1305
 		$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
1306 1306
 		#print "<pre>";
1307 1307
 		#$this->icServer->setDebug(true);
1308
-		$total=0;
1308
+		$total = 0;
1309 1309
 		if ($_thisUIDOnly === null)
1310 1310
 		{
1311 1311
 			if (($_startMessage || $_numberOfMessages) && !isset($_filter['range']))
@@ -1318,24 +1318,24 @@  discard block
 block discarded – undo
1318 1318
 				//$_filter['range'] ="$_startMessage:*";
1319 1319
 			}
1320 1320
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_sort, $reverse, ".array2string($_filter).", $rByUid");
1321
-			if (self::$debug||self::$debugTimes) $starttime = microtime (true);
1321
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1322 1322
 			//see this example below for a 12 week datefilter (since)
1323 1323
 			//$_filter = array('status'=>array('UNDELETED'),'type'=>"SINCE",'string'=> date("d-M-Y", $starttime-(3600*24*7*12)));
1324 1324
 			$_sortResult = $this->getSortedList($_folderName, $_sort, $reverse, $_filter, $rByUid, $_cacheResult);
1325 1325
 			$sortResult = $_sortResult['match']->ids;
1326 1326
 			//$modseq = $_sortResult['modseq'];
1327 1327
 			//error_log(__METHOD__.' ('.__LINE__.') '.'Modsequence:'.$modseq);
1328
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly),__METHOD__.' ('.__LINE__.') ');
1328
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' call getSortedList for Folder:'.$_folderName.' Filter:'.array2string($_filter).' Ids:'.array2string($_thisUIDOnly), __METHOD__.' ('.__LINE__.') ');
1329 1329
 
1330 1330
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1331 1331
 			#$this->icServer->setDebug(false);
1332 1332
 			#print "</pre>";
1333 1333
 			// nothing found
1334
-			if(!is_array($sortResult) || empty($sortResult)) {
1334
+			if (!is_array($sortResult) || empty($sortResult)) {
1335 1335
 				$retValue = array();
1336 1336
 				$retValue['info']['total']	= 0;
1337 1337
 				$retValue['info']['first']	= 0;
1338
-				$retValue['info']['last']	= 0;
1338
+				$retValue['info']['last'] = 0;
1339 1339
 				return $retValue;
1340 1340
 			}
1341 1341
 
@@ -1343,54 +1343,54 @@  discard block
 block discarded – undo
1343 1343
 			#_debug_array($sortResult);
1344 1344
 			#_debug_array(array_slice($sortResult, -5, -2));
1345 1345
 			//error_log("REVERSE: $reverse");
1346
-			if($reverse === true) {
1347
-				if  ($_startMessage<=$total)
1346
+			if ($reverse === true) {
1347
+				if ($_startMessage <= $total)
1348 1348
 				{
1349
-					$startMessage = $_startMessage-1;
1349
+					$startMessage = $_startMessage - 1;
1350 1350
 				}
1351 1351
 				else
1352 1352
 				{
1353 1353
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1354
-					if ($_startMessage+$_numberOfMessages>$total)
1354
+					if ($_startMessage + $_numberOfMessages > $total)
1355 1355
 					{
1356
-						$numberOfMessages = $total%$_numberOfMessages;
1356
+						$numberOfMessages = $total % $_numberOfMessages;
1357 1357
 						//$numberOfMessages = abs($_startMessage-$total-1);
1358
-						if ($numberOfMessages>0 && $numberOfMessages<=$_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1358
+						if ($numberOfMessages > 0 && $numberOfMessages <= $_numberOfMessages) $_numberOfMessages = $numberOfMessages;
1359 1359
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Start:'.$_startMessage.' NumberOfMessages:'.$_numberOfMessages.' Total:'.$total);
1360 1360
 					}
1361
-					$startMessage=($total-$_numberOfMessages)-1;
1361
+					$startMessage = ($total - $_numberOfMessages) - 1;
1362 1362
 					//$retValue['info']['first'] = $startMessage;
1363 1363
 					//$retValue['info']['last'] = $total;
1364 1364
 
1365 1365
 				}
1366
-				if ($startMessage+$_numberOfMessages>$total)
1366
+				if ($startMessage + $_numberOfMessages > $total)
1367 1367
 				{
1368
-					$_numberOfMessages = $_numberOfMessages-($total-($startMessage+$_numberOfMessages));
1368
+					$_numberOfMessages = $_numberOfMessages - ($total - ($startMessage + $_numberOfMessages));
1369 1369
 					//$retValue['info']['first'] = $startMessage;
1370 1370
 					//$retValue['info']['last'] = $total;
1371 1371
 				}
1372
-				if($startMessage > 0) {
1373
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+$startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1374
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+$startMessage), -$startMessage);
1372
+				if ($startMessage > 0) {
1373
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + $startMessage)).', '.-$startMessage.' Number of Messages:'.count($sortResult));
1374
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + $startMessage), -$startMessage);
1375 1375
 				} else {
1376
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages+($_startMessage-1))).', AllTheRest, Number of Messages:'.count($sortResult));
1377
-					$sortResult = array_slice($sortResult, -($_numberOfMessages+($_startMessage-1)));
1376
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.(-($_numberOfMessages + ($_startMessage - 1))).', AllTheRest, Number of Messages:'.count($sortResult));
1377
+					$sortResult = array_slice($sortResult, -($_numberOfMessages + ($_startMessage - 1)));
1378 1378
 				}
1379 1379
 				$sortResult = array_reverse($sortResult);
1380 1380
 			} else {
1381
-				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage-1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1382
-				$sortResult = array_slice($sortResult, $_startMessage-1, $_numberOfMessages);
1381
+				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' StartMessage:'.($_startMessage - 1).', '.$_numberOfMessages.' Number of Messages:'.count($sortResult));
1382
+				$sortResult = array_slice($sortResult, $_startMessage - 1, $_numberOfMessages);
1383 1383
 			}
1384 1384
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.array2string($sortResult));
1385 1385
 		}
1386 1386
 		else
1387 1387
 		{
1388
-			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly:(array)$_thisUIDOnly);
1388
+			$sortResult = (is_array($_thisUIDOnly) ? $_thisUIDOnly : (array)$_thisUIDOnly);
1389 1389
 		}
1390 1390
 
1391 1391
 
1392 1392
 		// fetch the data for the selected messages
1393
-		if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1393
+		if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1394 1394
 		try
1395 1395
 		{
1396 1396
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -1399,22 +1399,22 @@  discard block
 block discarded – undo
1399 1399
 			$fquery = new Horde_Imap_Client_Fetch_Query();
1400 1400
 
1401 1401
 			// Pre-cache the headers we want, 'fetchHeaders' is a label into the cache
1402
-			$fquery->headers('fetchHeaders',array(
1403
-				'DISPOSITION-NOTIFICATION-TO','RETURN-RECEIPT-TO','X-CONFIRM-READING-TO',
1404
-				'DATE','SUBJECT','FROM','TO','CC',
1402
+			$fquery->headers('fetchHeaders', array(
1403
+				'DISPOSITION-NOTIFICATION-TO', 'RETURN-RECEIPT-TO', 'X-CONFIRM-READING-TO',
1404
+				'DATE', 'SUBJECT', 'FROM', 'TO', 'CC',
1405 1405
 				'X-PRIORITY'
1406
-			),array(
1406
+			), array(
1407 1407
 				// Cache headers, we'll look at them below
1408
-				'cache' => true,//$_cacheResult,
1408
+				'cache' => true, //$_cacheResult,
1409 1409
 				// Set peek so messages are not flagged as read
1410 1410
 				'peek' => true
1411 1411
 			));
1412 1412
 			$fquery->size();
1413 1413
 			$fquery->structure();
1414 1414
 			$fquery->flags();
1415
-			$fquery->imapDate();// needed to ensure getImapDate fetches the internaldate, not the current time
1415
+			$fquery->imapDate(); // needed to ensure getImapDate fetches the internaldate, not the current time
1416 1416
 			// if $_fetchPreviews is activated fetch part of the messages too
1417
-			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true,'length'=>((int)$_fetchPreviews<5000?5000:$_fetchPreviews),'start'=>0));
1417
+			if ($_fetchPreviews) $fquery->fullText(array('peek'=>true, 'length'=>((int)$_fetchPreviews < 5000 ? 5000 : $_fetchPreviews), 'start'=>0));
1418 1418
 			$headersNew = $this->icServer->fetch($_folderName, $fquery, array(
1419 1419
 				'ids' => $uidsToFetch,
1420 1420
 			));
@@ -1425,9 +1425,9 @@  discard block
 block discarded – undo
1425 1425
 			$headersNew = array();
1426 1426
 			$sortResult = array();
1427 1427
 		}
1428
-		if (self::$debug||self::$debugTimes)
1428
+		if (self::$debug || self::$debugTimes)
1429 1429
 		{
1430
-			self::logRunTimes($starttime,null,'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter),__METHOD__.' ('.__LINE__.') ');
1430
+			self::logRunTimes($starttime, null, 'HordeFetch: for Folder:'.$_folderName.' Filter:'.array2string($_filter), __METHOD__.' ('.__LINE__.') ');
1431 1431
 			if (self::$debug)
1432 1432
 			{
1433 1433
 				$queryString = implode(',', $sortResult);
@@ -1437,27 +1437,27 @@  discard block
 block discarded – undo
1437 1437
 
1438 1438
 		$cnt = 0;
1439 1439
 
1440
-		foreach((array)$sortResult as $uid) {
1440
+		foreach ((array)$sortResult as $uid) {
1441 1441
 			$sortOrder[$uid] = $cnt++;
1442 1442
 		}
1443 1443
 
1444 1444
 		$count = 0;
1445 1445
 		if (is_object($headersNew)) {
1446
-			if (self::$debug||self::$debugTimes) $starttime = microtime(true);
1447
-			foreach($headersNew->ids() as $id) {
1446
+			if (self::$debug || self::$debugTimes) $starttime = microtime(true);
1447
+			foreach ($headersNew->ids() as $id) {
1448 1448
 				$_headerObject = $headersNew->get($id);
1449 1449
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_headerObject));
1450 1450
 				$headerObject = array();
1451 1451
 				$bodyPreview = null;
1452
-				$uid = $headerObject['UID']= ($_headerObject->getUid()?$_headerObject->getUid():$id);
1452
+				$uid = $headerObject['UID'] = ($_headerObject->getUid() ? $_headerObject->getUid() : $id);
1453 1453
 				$headerObject['MSG_NUM'] = $_headerObject->getSeq();
1454 1454
 				$headerObject['SIZE'] = $_headerObject->getSize();
1455 1455
 				$headerObject['INTERNALDATE'] = $_headerObject->getImapDate();
1456 1456
 
1457 1457
 				// Get already cached headers, 'fetchHeaders' is a label matchimg above
1458
-				$headerForPrio = $_headerObject->getHeaders('fetchHeaders',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1458
+				$headerForPrio = $_headerObject->getHeaders('fetchHeaders', Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1459 1459
 				// Try to fetch header with key='' as some servers might have no fetchHeaders index. e.g. yandex.com
1460
-				if (empty($headerForPrio)) $headerForPrio = $_headerObject->getHeaders('',Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1460
+				if (empty($headerForPrio)) $headerForPrio = $_headerObject->getHeaders('', Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray();
1461 1461
 				//fetch the fullMsg part if all conditions match to be available in case $_headerObject->getHeaders returns
1462 1462
 				//nothing worthwhile (as it does for googlemail accounts, when preview is switched on
1463 1463
 				if ($_fetchPreviews)
@@ -1465,16 +1465,16 @@  discard block
 block discarded – undo
1465 1465
 					// on enabled preview $bodyPreview is needed lateron. fetched here, for fallback-reasons
1466 1466
 					// in case of failed Header-Retrieval
1467 1467
 					$bodyPreview = $_headerObject->getFullMsg();
1468
-					if (empty($headerForPrio)||(is_array($headerForPrio)&&count($headerForPrio)===1&&$headerForPrio['']))
1468
+					if (empty($headerForPrio) || (is_array($headerForPrio) && count($headerForPrio) === 1 && $headerForPrio['']))
1469 1469
 					{
1470 1470
 						$length = strpos($bodyPreview, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
1471
-						if ($length===false) $length = strlen($bodyPreview);
1472
-						$headerForPrio =  Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0,$length))->toArray();
1471
+						if ($length === false) $length = strlen($bodyPreview);
1472
+						$headerForPrio = Horde_Mime_Headers::parseHeaders(substr($bodyPreview, 0, $length))->toArray();
1473 1473
 					}
1474 1474
 				}
1475 1475
 				$headerForPrio = array_change_key_case($headerForPrio, CASE_UPPER);
1476 1476
 				if (self::$debug) {
1477
-					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'));
1477
+					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'));
1478 1478
 					error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerForPrio));
1479 1479
 				}
1480 1480
 				// message deleted from server but cache still reporting its existence ; may happen on QRESYNC with No permanent modsequences
@@ -1483,21 +1483,21 @@  discard block
 block discarded – undo
1483 1483
 					$total--;
1484 1484
 					continue;
1485 1485
 				}
1486
-				if ( isset($headerForPrio['DISPOSITION-NOTIFICATION-TO']) ) {
1486
+				if (isset($headerForPrio['DISPOSITION-NOTIFICATION-TO'])) {
1487 1487
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['DISPOSITION-NOTIFICATION-TO']));
1488
-				} else if ( isset($headerForPrio['RETURN-RECEIPT-TO']) ) {
1488
+				} else if (isset($headerForPrio['RETURN-RECEIPT-TO'])) {
1489 1489
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['RETURN-RECEIPT-TO']));
1490
-				} else if ( isset($headerForPrio['X-CONFIRM-READING-TO']) ) {
1490
+				} else if (isset($headerForPrio['X-CONFIRM-READING-TO'])) {
1491 1491
 					$headerObject['DISPOSITION-NOTIFICATION-TO'] = self::decode_header(trim($headerForPrio['X-CONFIRM-READING-TO']));
1492 1492
 				} /*else $sent_not = "";*/
1493 1493
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1494 1494
 				$headerObject['DATE'] = $headerForPrio['DATE'];
1495
-				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT'])?$headerForPrio['SUBJECT'][0]:$headerForPrio['SUBJECT']);
1496
-				$headerObject['FROM'] = (array)($headerForPrio['FROM']?$headerForPrio['FROM']:($headerForPrio['REPLY-TO']?$headerForPrio['REPLY-TO']:$headerForPrio['RETURN-PATH']));
1495
+				$headerObject['SUBJECT'] = (is_array($headerForPrio['SUBJECT']) ? $headerForPrio['SUBJECT'][0] : $headerForPrio['SUBJECT']);
1496
+				$headerObject['FROM'] = (array)($headerForPrio['FROM'] ? $headerForPrio['FROM'] : ($headerForPrio['REPLY-TO'] ? $headerForPrio['REPLY-TO'] : $headerForPrio['RETURN-PATH']));
1497 1497
 				$headerObject['TO'] = (array)$headerForPrio['TO'];
1498
-				$headerObject['CC'] = isset($headerForPrio['CC'])?(array)$headerForPrio['CC']:array();
1499
-				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY'])?$headerForPrio['X-PRIORITY']:null;
1500
-				foreach (array('FROM','TO','CC') as $key)
1498
+				$headerObject['CC'] = isset($headerForPrio['CC']) ? (array)$headerForPrio['CC'] : array();
1499
+				$headerObject['PRIORITY'] = isset($headerForPrio['X-PRIORITY']) ? $headerForPrio['X-PRIORITY'] : null;
1500
+				foreach (array('FROM', 'TO', 'CC') as $key)
1501 1501
 				{
1502 1502
 					$address = array();
1503 1503
 					foreach ($headerObject[$key] as $k => $ad)
@@ -1519,13 +1519,13 @@  discard block
 block discarded – undo
1519 1519
 						foreach ($rfcAddr as $_rfcAddr)
1520 1520
 						{
1521 1521
 							if (!$_rfcAddr->valid)	continue; // skip. not a valid address
1522
-							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox,$_rfcAddr->host,$_rfcAddr->personal);
1522
+							$address[] = imap_rfc822_write_address($_rfcAddr->mailbox, $_rfcAddr->host, $_rfcAddr->personal);
1523 1523
 						}
1524 1524
 					}
1525 1525
 					$headerObject[$key] = $address;
1526 1526
 				}
1527 1527
 				$headerObject['FLAGS'] = $_headerObject->getFlags();
1528
-				$headerObject['BODYPREVIEW']=null;
1528
+				$headerObject['BODYPREVIEW'] = null;
1529 1529
 				// this section fetches part of the message-body (if enabled) for some kind of preview
1530 1530
 				// if we fail to succeed, we fall back to the retrieval of the message-body with
1531 1531
 				// fetchPartContents (see below, when we iterate over the structure to determine the
@@ -1537,17 +1537,17 @@  discard block
 block discarded – undo
1537 1537
 					if (empty($bodyPreview)) $bodyPreview = $_headerObject->getFullMsg();
1538 1538
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($bodyPreview));
1539 1539
 					$base = Horde_Mime_Part::parseMessage($bodyPreview);
1540
-					foreach($base->partIterator() as $part)
1540
+					foreach ($base->partIterator() as $part)
1541 1541
 					{
1542 1542
 						//error_log(__METHOD__.__LINE__.'Part:'.$part->getPrimaryType());
1543
-						if (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'text')
1543
+						if (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'text')
1544 1544
 						{
1545 1545
 							$charset = $part->getContentTypeParameter('charset');
1546 1546
 							$buffer = Mail\Html::convertHTMLToText($part->toString(array(
1547
-												'encode' => Horde_Mime_Part::ENCODE_BINARY,	// otherwise we cant recode charset
1547
+												'encode' => Horde_Mime_Part::ENCODE_BINARY, // otherwise we cant recode charset
1548 1548
 											)), $charset, 'utf-8');
1549
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Translation::convert_jsonsafe($buffer),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1550
-						} elseif (empty($headerObject['BODYPREVIEW'])&&$part->getPrimaryType()== 'multipart')
1549
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Translation::convert_jsonsafe($buffer), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1550
+						} elseif (empty($headerObject['BODYPREVIEW']) && $part->getPrimaryType() == 'multipart')
1551 1551
 						{
1552 1552
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part));
1553 1553
 						}
@@ -1558,12 +1558,12 @@  discard block
 block discarded – undo
1558 1558
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($headerObject));
1559 1559
 				//error_log(__METHOD__.' ('.__LINE__.') '.' MimeMap:'.array2string($mailStructureObject->contentTypeMap()));
1560 1560
 				//foreach ($_headerObject->getStructure()->getParts() as $p => $part)
1561
-				$headerObject['ATTACHMENTS']=null;
1562
-				$skipParts=array();
1563
-				$messageMimeType='';
1561
+				$headerObject['ATTACHMENTS'] = null;
1562
+				$skipParts = array();
1563
+				$messageMimeType = '';
1564 1564
 				foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
1565 1565
 				{
1566
-					if ($mime_id==0 || $messageMimeType==='') $messageMimeType = $mime_type;
1566
+					if ($mime_id == 0 || $messageMimeType === '') $messageMimeType = $mime_type;
1567 1567
 					$part = $mailStructureObject->getPart($mime_id);
1568 1568
 					$partdisposition = $part->getDisposition();
1569 1569
 					$partPrimaryType = $part->getPrimaryType();
@@ -1571,16 +1571,16 @@  discard block
 block discarded – undo
1571 1571
 					// drawback here it is talking to the mailserver for each mail thus consuming
1572 1572
 					// more time than expected; so we call this section only when there is no
1573 1573
 					// bodypreview could be found (multipart/....)
1574
-					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW'])&&($partPrimaryType == 'text') &&
1574
+					if ($_fetchPreviews && empty($headerObject['BODYPREVIEW']) && ($partPrimaryType == 'text') &&
1575 1575
 						((intval($mime_id) === 1) || !$mime_id) &&
1576 1576
 						($partdisposition !== 'attachment')) {
1577
-							$_structure=$part;
1578
-							$this->fetchPartContents($uid, $_structure, false,true);
1579
-							$headerObject['BODYPREVIEW']=trim(str_replace(array("\r\n","\r","\n"),' ',mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()),0,((int)$_fetchPreviews<300?300:$_fetchPreviews))));
1580
-							$charSet=Translation::detect_encoding($headerObject['BODYPREVIEW']);
1577
+							$_structure = $part;
1578
+							$this->fetchPartContents($uid, $_structure, false, true);
1579
+							$headerObject['BODYPREVIEW'] = trim(str_replace(array("\r\n", "\r", "\n"), ' ', mb_substr(Mail\Html::convertHTMLToText($_structure->getContents()), 0, ((int)$_fetchPreviews < 300 ? 300 : $_fetchPreviews))));
1580
+							$charSet = Translation::detect_encoding($headerObject['BODYPREVIEW']);
1581 1581
 							// add line breaks to $bodyParts
1582 1582
 							//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
1583
-							$headerObject['BODYPREVIEW']  = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1583
+							$headerObject['BODYPREVIEW'] = Translation::convert_jsonsafe($headerObject['BODYPREVIEW'], $charSet);
1584 1584
 							//error_log(__METHOD__.__LINE__.$headerObject['BODYPREVIEW']);
1585 1585
 					}
1586 1586
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType);
@@ -1590,28 +1590,28 @@  discard block
 block discarded – undo
1590 1590
 						// the presence of an cid does not necessarily indicate its inline. it may lack the needed
1591 1591
 						// link to show the image. Considering this: we "list" everything that matches the above criteria
1592 1592
 						// as attachment in order to not loose/miss information on our data
1593
-						$partdisposition='attachment';//($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1593
+						$partdisposition = 'attachment'; //($partPrimaryType == 'image'&&!empty($cid)?'inline':'attachment');
1594 1594
 					}
1595
-					if ($mime_type=='message/rfc822')
1595
+					if ($mime_type == 'message/rfc822')
1596 1596
 					{
1597 1597
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
1598
-						foreach($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
1598
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
1599 1599
 					}
1600 1600
 					//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.' Disp:'.$partdisposition.' Type:'.$partPrimaryType.' Skip:'.array2string($skipParts));
1601
-					if (array_key_exists($mime_id,$skipParts)) continue;
1602
-					if ($partdisposition=='attachment' ||
1603
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&$mime_type=='image/tiff') || // as we are not able to display tiffs
1604
-						($partdisposition=='inline'&&$partPrimaryType == 'image'&&empty($cid)) ||
1605
-						($partdisposition=='inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1601
+					if (array_key_exists($mime_id, $skipParts)) continue;
1602
+					if ($partdisposition == 'attachment' ||
1603
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && $mime_type == 'image/tiff') || // as we are not able to display tiffs
1604
+						($partdisposition == 'inline' && $partPrimaryType == 'image' && empty($cid)) ||
1605
+						($partdisposition == 'inline' && $partPrimaryType != 'image' && $partPrimaryType != 'multipart' && $partPrimaryType != 'text'))
1606 1606
 					{
1607
-						$headerObject['ATTACHMENTS'][$mime_id]=$part->getAllDispositionParameters();
1608
-						$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=$mime_type;
1609
-						$headerObject['ATTACHMENTS'][$mime_id]['uid']=$uid;
1607
+						$headerObject['ATTACHMENTS'][$mime_id] = $part->getAllDispositionParameters();
1608
+						$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] = $mime_type;
1609
+						$headerObject['ATTACHMENTS'][$mime_id]['uid'] = $uid;
1610 1610
 						$headerObject['ATTACHMENTS'][$mime_id]['cid'] = $cid;
1611
-						$headerObject['ATTACHMENTS'][$mime_id]['partID']=$mime_id;
1612
-						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))$headerObject['ATTACHMENTS'][$mime_id]['name']=$part->getName();
1613
-						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'],'winmail.dat') ||
1614
-							$headerObject['ATTACHMENTS'][$mime_id]['mimeType']=='application/ms-tnef')
1611
+						$headerObject['ATTACHMENTS'][$mime_id]['partID'] = $mime_id;
1612
+						if (!isset($headerObject['ATTACHMENTS'][$mime_id]['name']))$headerObject['ATTACHMENTS'][$mime_id]['name'] = $part->getName();
1613
+						if (!strcasecmp($headerObject['ATTACHMENTS'][$mime_id]['name'], 'winmail.dat') ||
1614
+							$headerObject['ATTACHMENTS'][$mime_id]['mimeType'] == 'application/ms-tnef')
1615 1615
 						{
1616 1616
 							$headerObject['ATTACHMENTS'][$mime_id]['is_winmail'] = true;
1617 1617
 						}
@@ -1626,54 +1626,54 @@  discard block
 block discarded – undo
1626 1626
 				if (empty($headerObject['UID'])) continue;
1627 1627
 				//$uid = ($rByUid ? $headerObject['UID'] : $headerObject['MSG_NUM']);
1628 1628
 				// make dates like "Mon, 23 Apr 2007 10:11:06 UT" working with strtotime
1629
-				if(substr($headerObject['DATE'],-2) === 'UT') {
1629
+				if (substr($headerObject['DATE'], -2) === 'UT') {
1630 1630
 					$headerObject['DATE'] .= 'C';
1631 1631
 				}
1632
-				if(substr($headerObject['INTERNALDATE'],-2) === 'UT') {
1632
+				if (substr($headerObject['INTERNALDATE'], -2) === 'UT') {
1633 1633
 					$headerObject['INTERNALDATE'] .= 'C';
1634 1634
 				}
1635 1635
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$headerObject['SUBJECT'].'->'.$headerObject['DATE'].'<->'.$headerObject['INTERNALDATE'] .'#');
1636 1636
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.$this->decode_subject($headerObject['SUBJECT']).'->'.$headerObject['DATE']);
1637
-				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][]=$a;}
1638
-				$retValue['header'][$sortOrder[$uid]]['subject']	= $this->decode_subject($headerObject['SUBJECT']);
1639
-				$retValue['header'][$sortOrder[$uid]]['size'] 		= $headerObject['SIZE'];
1640
-				$retValue['header'][$sortOrder[$uid]]['date']		= self::_strtotime(($headerObject['DATE']&&!($headerObject['DATE']=='NIL')?$headerObject['DATE']:$headerObject['INTERNALDATE']),'ts',true);
1641
-				$retValue['header'][$sortOrder[$uid]]['internaldate']= self::_strtotime($headerObject['INTERNALDATE'],'ts',true);
1642
-				$retValue['header'][$sortOrder[$uid]]['mimetype']	= $messageMimeType;
1643
-				$retValue['header'][$sortOrder[$uid]]['id']		= $headerObject['MSG_NUM'];
1644
-				$retValue['header'][$sortOrder[$uid]]['uid']		= $headerObject['UID'];
1645
-				$retValue['header'][$sortOrder[$uid]]['bodypreview']		= $headerObject['BODYPREVIEW'];
1646
-				$retValue['header'][$sortOrder[$uid]]['priority']		= ($headerObject['PRIORITY']?$headerObject['PRIORITY']:3);
1637
+				if (isset($headerObject['ATTACHMENTS']) && count($headerObject['ATTACHMENTS'])) foreach ($headerObject['ATTACHMENTS'] as &$a) { $retValue['header'][$sortOrder[$uid]]['attachments'][] = $a; }
1638
+				$retValue['header'][$sortOrder[$uid]]['subject'] = $this->decode_subject($headerObject['SUBJECT']);
1639
+				$retValue['header'][$sortOrder[$uid]]['size'] = $headerObject['SIZE'];
1640
+				$retValue['header'][$sortOrder[$uid]]['date'] = self::_strtotime(($headerObject['DATE'] && !($headerObject['DATE'] == 'NIL') ? $headerObject['DATE'] : $headerObject['INTERNALDATE']), 'ts', true);
1641
+				$retValue['header'][$sortOrder[$uid]]['internaldate'] = self::_strtotime($headerObject['INTERNALDATE'], 'ts', true);
1642
+				$retValue['header'][$sortOrder[$uid]]['mimetype'] = $messageMimeType;
1643
+				$retValue['header'][$sortOrder[$uid]]['id'] = $headerObject['MSG_NUM'];
1644
+				$retValue['header'][$sortOrder[$uid]]['uid'] = $headerObject['UID'];
1645
+				$retValue['header'][$sortOrder[$uid]]['bodypreview'] = $headerObject['BODYPREVIEW'];
1646
+				$retValue['header'][$sortOrder[$uid]]['priority'] = ($headerObject['PRIORITY'] ? $headerObject['PRIORITY'] : 3);
1647 1647
 				//error_log(__METHOD__.' ('.__LINE__.') '.' '.array2string($retValue['header'][$sortOrder[$uid]]));
1648 1648
 				if (isset($headerObject['DISPOSITION-NOTIFICATION-TO'])) $retValue['header'][$sortOrder[$uid]]['disposition-notification-to'] = $headerObject['DISPOSITION-NOTIFICATION-TO'];
1649 1649
 				if (is_array($headerObject['FLAGS'])) {
1650
-					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]],self::prepareFlagsArray($headerObject));
1650
+					$retValue['header'][$sortOrder[$uid]] = array_merge($retValue['header'][$sortOrder[$uid]], self::prepareFlagsArray($headerObject));
1651 1651
 				}
1652 1652
 				//error_log(__METHOD__.' ('.__LINE__.') '.$headerObject['SUBJECT'].'->'.array2string($_headerObject->getEnvelope()->__get('from')));
1653
-				if(is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1654
-					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0],true);
1653
+				if (is_array($headerObject['FROM']) && $headerObject['FROM'][0]) {
1654
+					$retValue['header'][$sortOrder[$uid]]['sender_address'] = self::decode_header($headerObject['FROM'][0], true);
1655 1655
 				}
1656
-				if(is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1657
-					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0],true);
1658
-					if (count($headerObject['TO'])>1)
1656
+				if (is_array($headerObject['TO']) && $headerObject['TO'][0]) {
1657
+					$retValue['header'][$sortOrder[$uid]]['to_address'] = self::decode_header($headerObject['TO'][0], true);
1658
+					if (count($headerObject['TO']) > 1)
1659 1659
 					{
1660
-						$ki=0;
1661
-						foreach($headerObject['TO'] as $k => $add)
1660
+						$ki = 0;
1661
+						foreach ($headerObject['TO'] as $k => $add)
1662 1662
 						{
1663
-							if ($k==0) continue;
1663
+							if ($k == 0) continue;
1664 1664
 							//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1665
-							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add,true);
1665
+							$retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki] = self::decode_header($add, true);
1666 1666
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1667 1667
 							$ki++;
1668 1668
 						}
1669 1669
 					}
1670 1670
 				}
1671
-				if(is_array($headerObject['CC']) && count($headerObject['CC'])>0) {
1672
-					$ki=0;
1673
-					foreach($headerObject['CC'] as $k => $add)
1671
+				if (is_array($headerObject['CC']) && count($headerObject['CC']) > 0) {
1672
+					$ki = 0;
1673
+					foreach ($headerObject['CC'] as $k => $add)
1674 1674
 					{
1675 1675
 						//error_log(__METHOD__.' ('.__LINE__.') '."-> $k:".array2string($add));
1676
-						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add,true);
1676
+						$retValue['header'][$sortOrder[$uid]]['cc_addresses'][$ki] = self::decode_header($add, true);
1677 1677
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue['header'][$sortOrder[$uid]]['additional_to_addresses'][$ki]));
1678 1678
 						$ki++;
1679 1679
 					}
@@ -1682,27 +1682,27 @@  discard block
 block discarded – undo
1682 1682
 
1683 1683
 				$count++;
1684 1684
 			}
1685
-			if (self::$debug||self::$debugTimes) self::logRunTimes($starttime,null,' fetching Headers and stuff for Folder:'.$_folderName,__METHOD__.' ('.__LINE__.') ');
1685
+			if (self::$debug || self::$debugTimes) self::logRunTimes($starttime, null, ' fetching Headers and stuff for Folder:'.$_folderName, __METHOD__.' ('.__LINE__.') ');
1686 1686
 			//self::$debug=false;
1687 1687
 			// sort the messages to the requested displayorder
1688
-			if(is_array($retValue['header'])) {
1688
+			if (is_array($retValue['header'])) {
1689 1689
 				$countMessages = $total;
1690 1690
 				if (isset($_filter['range'])) $countMessages = self::$folderStatusCache[$this->profileID][$_folderName]['messages'];
1691 1691
 				ksort($retValue['header']);
1692 1692
 				$retValue['info']['total']	= $total;
1693 1693
 				//if ($_startMessage>$total) $_startMessage = $total-($count-1);
1694 1694
 				$retValue['info']['first']	= $_startMessage;
1695
-				$retValue['info']['last']	= $_startMessage + $count - 1 ;
1695
+				$retValue['info']['last'] = $_startMessage + $count - 1;
1696 1696
 				return $retValue;
1697 1697
 			} else {
1698 1698
 				$retValue = array();
1699 1699
 				$retValue['info']['total']	= 0;
1700 1700
 				$retValue['info']['first']	= 0;
1701
-				$retValue['info']['last']	= 0;
1701
+				$retValue['info']['last'] = 0;
1702 1702
 				return $retValue;
1703 1703
 			}
1704 1704
 		} else {
1705
-			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew,TRUE));
1705
+			if ($headersNew == null && empty($_thisUIDOnly)) error_log(__METHOD__." -> retrieval of Message Details to Query $queryString failed: ".print_r($headersNew, TRUE));
1706 1706
 			$retValue = array();
1707 1707
 			$retValue['info']['total']  = 0;
1708 1708
 			$retValue['info']['first']  = 0;
@@ -1719,17 +1719,17 @@  discard block
 block discarded – undo
1719 1719
 	 */
1720 1720
 	static function prepareFlagsArray($headerObject)
1721 1721
 	{
1722
-		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower',$headerObject['FLAGS']);
1722
+		if (is_array($headerObject['FLAGS'])) $headerFlags = array_map('strtolower', $headerObject['FLAGS']);
1723 1723
 		$retValue = array();
1724 1724
 		$retValue['recent']		= in_array('\\recent', $headerFlags);
1725 1725
 		$retValue['flagged']	= in_array('\\flagged', $headerFlags);
1726
-		$retValue['answered']	= in_array('\\answered', $headerFlags);
1727
-		$retValue['forwarded']   = in_array('$forwarded', $headerFlags);
1726
+		$retValue['answered'] = in_array('\\answered', $headerFlags);
1727
+		$retValue['forwarded'] = in_array('$forwarded', $headerFlags);
1728 1728
 		$retValue['deleted']	= in_array('\\deleted', $headerFlags);
1729
-		$retValue['seen']		= in_array('\\seen', $headerFlags);
1730
-		$retValue['draft']		= in_array('\\draft', $headerFlags);
1731
-		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags)||in_array('mdnsent', $headerFlags);
1732
-		$retValue['mdnnotsent']	= in_array('$mdnnotsent', $headerFlags)||in_array('mdnnotsent', $headerFlags);
1729
+		$retValue['seen'] = in_array('\\seen', $headerFlags);
1730
+		$retValue['draft'] = in_array('\\draft', $headerFlags);
1731
+		$retValue['mdnsent']	= in_array('$mdnsent', $headerFlags) || in_array('mdnsent', $headerFlags);
1732
+		$retValue['mdnnotsent'] = in_array('$mdnnotsent', $headerFlags) || in_array('mdnnotsent', $headerFlags);
1733 1733
 		$retValue['label1']   = in_array('$label1', $headerFlags);
1734 1734
 		$retValue['label2']   = in_array('$label2', $headerFlags);
1735 1735
 		$retValue['label3']   = in_array('$label3', $headerFlags);
@@ -1753,12 +1753,12 @@  discard block
 block discarded – undo
1753 1753
 	 * @param bool $setSession if set to true the session will be populated with the result of the query
1754 1754
 	 * @return mixed bool/array false or array of ids
1755 1755
 	 */
1756
-	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid=true, $setSession=true)
1756
+	function getSortedList($_folderName, $_sort, &$_reverse, $_filter, &$resultByUid = true, $setSession = true)
1757 1757
 	{
1758 1758
 		static $cachedFolderStatus = null;
1759 1759
 		// in the past we needed examineMailbox to figure out if the server with the serverID support keywords
1760 1760
 		// this information is filled/provided by examineMailbox; but caching within one request seems o.k.
1761
-		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]) )
1761
+		if (is_null($cachedFolderStatus) || !isset($cachedFolderStatus[$this->profileID][$_folderName]))
1762 1762
 		{
1763 1763
 			$folderStatus = $cachedFolderStatus[$this->profileID][$_folderName] = $this->icServer->examineMailbox($_folderName);
1764 1764
 		}
@@ -1770,27 +1770,27 @@  discard block
 block discarded – undo
1770 1770
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Filter:'.array2string($_filter));
1771 1771
 		$try2useCache = true;
1772 1772
 		static $eMailListContainsDeletedMessages = null;
1773
-		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
1773
+		if (is_null($eMailListContainsDeletedMessages)) $eMailListContainsDeletedMessages = Cache::getCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
1774 1774
 		// this indicates, that there is no Filter set, and the returned set/subset should not contain DELETED Messages, nor filtered for UNDELETED
1775
-		if ($setSession==true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1775
+		if ($setSession == true && ((strpos(array2string($_filter), 'UNDELETED') === false && strpos(array2string($_filter), 'DELETED') === false)))
1776 1776
 		{
1777 1777
 			if (self::$debugTimes) $starttime = microtime(true);
1778
-			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);
1779
-			$deletedMessages = $this->getSortedList($_folderName, 0, $three=1, array('status'=>array('DELETED')),$five=true,false);
1778
+			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);
1779
+			$deletedMessages = $this->getSortedList($_folderName, 0, $three = 1, array('status'=>array('DELETED')), $five = true, false);
1780 1780
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') Found DeletedMessages:'.array2string($eMailListContainsDeletedMessages));
1781
-			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] =$deletedMessages['count'];
1782
-			Cache::setCache(Cache::INSTANCE,'email','eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']),$eMailListContainsDeletedMessages, 60*60*1);
1783
-			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']);
1781
+			$eMailListContainsDeletedMessages[$this->profileID][$_folderName] = $deletedMessages['count'];
1782
+			Cache::setCache(Cache::INSTANCE, 'email', 'eMailListContainsDeletedMessages'.trim($GLOBALS['egw_info']['user']['account_id']), $eMailListContainsDeletedMessages, 60 * 60 * 1);
1783
+			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']);
1784 1784
 		}
1785 1785
 		$try2useCache = false;
1786 1786
 		//self::$supportsORinQuery[$this->profileID]=true;
1787 1787
 		if (is_null(self::$supportsORinQuery) || !isset(self::$supportsORinQuery[$this->profileID]))
1788 1788
 		{
1789
-			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*10);
1790
-			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID]=true;
1789
+			self::$supportsORinQuery = Cache::getCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 10);
1790
+			if (!isset(self::$supportsORinQuery[$this->profileID])) self::$supportsORinQuery[$this->profileID] = true;
1791 1791
 		}
1792 1792
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_filter).' SupportsOrInQuery:'.self::$supportsORinQuery[$this->profileID]);
1793
-		$filter = $this->createIMAPFilter($_folderName, $_filter,self::$supportsORinQuery[$this->profileID]);
1793
+		$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1794 1794
 		if (self::$debug)
1795 1795
 		{
1796 1796
 			$query_str = $filter->build();
@@ -1798,14 +1798,14 @@  discard block
 block discarded – undo
1798 1798
 		}
1799 1799
 		//_debug_array($filter);
1800 1800
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($filter).'#'.array2string($this->icServer->capability()));
1801
-		if($this->icServer->hasCapability('SORT')) {
1801
+		if ($this->icServer->hasCapability('SORT')) {
1802 1802
 			// when using an orQuery and we sort by date. sort seems to fail on certain servers => ZIMBRA with Horde_Imap_Client
1803 1803
 			// thus we translate the search request from date to Horde_Imap_Client::SORT_SEQUENCE (which should be the same, if
1804 1804
 			// there is no messing with the dates)
1805 1805
 			//if (self::$supportsORinQuery[$this->profileID]&&$_sort=='date'&&$_filter['type']=='quick'&&!empty($_filter['string']))$_sort='INTERNALDATE';
1806 1806
 			if (self::$debug) error_log(__METHOD__." Mailserver has SORT Capability, SortBy: ".array2string($_sort)." Reverse: $_reverse");
1807 1807
 			$sortOrder = $this->_getSortString($_sort, $_reverse);
1808
-			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE,$sortOrder)) $_reverse=false; // as we reversed the result already
1808
+			if ($_reverse && in_array(Horde_Imap_Client::SORT_REVERSE, $sortOrder)) $_reverse = false; // as we reversed the result already
1809 1809
 			if (self::$debug) error_log(__METHOD__." Mailserver runs SORT: SortBy:".array2string($_sort)."->".array2string($sortOrder)." Filter: ".array2string($filter));
1810 1810
 			try
1811 1811
 			{
@@ -1813,24 +1813,24 @@  discard block
 block discarded – undo
1813 1813
 					'sort' => $sortOrder,));
1814 1814
 			// if there is an Error, we assume that the server is not capable of sorting
1815 1815
 			}
1816
-			catch(\Exception $e)
1816
+			catch (\Exception $e)
1817 1817
 			{
1818 1818
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1819 1819
 				$resultByUid = false;
1820 1820
 				$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
1821
-				if ($_reverse) array_unshift($sortOrder,Horde_Imap_Client::SORT_REVERSE);
1821
+				if ($_reverse) array_unshift($sortOrder, Horde_Imap_Client::SORT_REVERSE);
1822 1822
 				try
1823 1823
 				{
1824 1824
 					$sortResult = $this->icServer->search($_folderName, $filter, array(
1825 1825
 						'sort' => $sortOrder));
1826 1826
 				}
1827
-				catch(\Exception $e)
1827
+				catch (\Exception $e)
1828 1828
 				{
1829 1829
 					error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1830 1830
 					$sortResult = self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'];
1831 1831
 				}
1832 1832
 			}
1833
-			if (self::$debug) error_log(__METHOD__.print_r($sortResult,true));
1833
+			if (self::$debug) error_log(__METHOD__.print_r($sortResult, true));
1834 1834
 		} else {
1835 1835
 			if (self::$debug) error_log(__METHOD__." Mailserver has NO SORT Capability");
1836 1836
 			//$sortOrder = array(Horde_Imap_Client::SORT_SEQUENCE);
@@ -1840,12 +1840,12 @@  discard block
 block discarded – undo
1840 1840
 				$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
1841 1841
 					'sort' => $sortOrder)*/);
1842 1842
 			}
1843
-			catch(\Exception $e)
1843
+			catch (\Exception $e)
1844 1844
 			{
1845 1845
 				//error_log(__METHOD__.'('.__LINE__.'):'.$e->getMessage());
1846 1846
 				// possible error OR Query. But Horde gives no detailed Info :-(
1847
-				self::$supportsORinQuery[$this->profileID]=false;
1848
-				Cache::setCache(Cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']),self::$supportsORinQuery,60*60*10);
1847
+				self::$supportsORinQuery[$this->profileID] = false;
1848
+				Cache::setCache(Cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), self::$supportsORinQuery, 60 * 60 * 10);
1849 1849
 				if (self::$debug) error_log(__METHOD__.__LINE__." Mailserver seems to have NO OR Capability for Search:".$sortResult->message);
1850 1850
 				$filter = $this->createIMAPFilter($_folderName, $_filter, self::$supportsORinQuery[$this->profileID]);
1851 1851
 				try
@@ -1853,25 +1853,25 @@  discard block
 block discarded – undo
1853 1853
 					$sortResult = $this->icServer->search($_folderName, $filter, array()/*array(
1854 1854
 						'sort' => $sortOrder)*/);
1855 1855
 				}
1856
-				catch(\Exception $e)
1856
+				catch (\Exception $e)
1857 1857
 				{
1858 1858
 				}
1859 1859
 			}
1860
-			if(is_array($sortResult['match'])) {
1860
+			if (is_array($sortResult['match'])) {
1861 1861
 					// not sure that this is going so succeed as $sortResult['match'] is a hordeObject
1862 1862
 					sort($sortResult['match'], SORT_NUMERIC);
1863 1863
 			}
1864
-			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
1864
+			if (self::$debug) error_log(__METHOD__." using Filter:".print_r($filter, true)." ->".print_r($sortResult, true));
1865 1865
 		}
1866 1866
 		if ($setSession)
1867 1867
 		{
1868 1868
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidValidity'] = $folderStatus['UIDVALIDITY'];
1869
-			self::$folderStatusCache[$this->profileID][$_folderName]['messages']	= $folderStatus['MESSAGES'];
1869
+			self::$folderStatusCache[$this->profileID][$_folderName]['messages'] = $folderStatus['MESSAGES'];
1870 1870
 			self::$folderStatusCache[$this->profileID][$_folderName]['deleted']	= $eMailListContainsDeletedMessages[$this->profileID][$_folderName];
1871 1871
 			self::$folderStatusCache[$this->profileID][$_folderName]['uidnext']	= $folderStatus['UIDNEXT'];
1872
-			self::$folderStatusCache[$this->profileID][$_folderName]['filter']	= $_filter;
1872
+			self::$folderStatusCache[$this->profileID][$_folderName]['filter'] = $_filter;
1873 1873
 			self::$folderStatusCache[$this->profileID][$_folderName]['sortResult'] = $sortResult;
1874
-			self::$folderStatusCache[$this->profileID][$_folderName]['sort']	= $_sort;
1874
+			self::$folderStatusCache[$this->profileID][$_folderName]['sort'] = $_sort;
1875 1875
 		}
1876 1876
 		//error_log(__METHOD__." using Filter:".print_r($filter,true)." ->".print_r($sortResult,true));
1877 1877
 		//_debug_array($sortResult['match']->ids);
@@ -1885,12 +1885,12 @@  discard block
 block discarded – undo
1885 1885
 	 * @param bool _reverse wether to add REVERSE to the Sort String or not
1886 1886
 	 * @return the sort sequence for horde search
1887 1887
 	 */
1888
-	function _getSortString($_sort, $_reverse=false)
1888
+	function _getSortString($_sort, $_reverse = false)
1889 1889
 	{
1890
-		$_reverse=false;
1890
+		$_reverse = false;
1891 1891
 		if (is_numeric($_sort))
1892 1892
 		{
1893
-			switch($_sort) {
1893
+			switch ($_sort) {
1894 1894
 				case 2:
1895 1895
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1896 1896
 					break;
@@ -1912,7 +1912,7 @@  discard block
 block discarded – undo
1912 1912
 		}
1913 1913
 		else
1914 1914
 		{
1915
-			switch(strtoupper($_sort)) {
1915
+			switch (strtoupper($_sort)) {
1916 1916
 				case 'FROMADDRESS':
1917 1917
 					$retValue = array(Horde_Imap_Client::SORT_FROM);
1918 1918
 					break;
@@ -1938,7 +1938,7 @@  discard block
 block discarded – undo
1938 1938
 					break;
1939 1939
 			}
1940 1940
 		}
1941
-		if ($_reverse) array_unshift($retValue,Horde_Imap_Client::SORT_REVERSE);
1941
+		if ($_reverse) array_unshift($retValue, Horde_Imap_Client::SORT_REVERSE);
1942 1942
 		//error_log(__METHOD__.' ('.__LINE__.') '.' '.($_reverse?'REVERSE ':'').$_sort.'->'.$retValue);
1943 1943
 		return $retValue;
1944 1944
 	}
@@ -1951,28 +1951,28 @@  discard block
 block discarded – undo
1951 1951
 	 * @param boolean $_supportsOrInQuery wether to use the OR Query on QuickSearch
1952 1952
 	 * @return Horde_Imap_Client_Search_Query the IMAP filter
1953 1953
 	 */
1954
-	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery=true)
1954
+	function createIMAPFilter($_folder, $_criterias, $_supportsOrInQuery = true)
1955 1955
 	{
1956 1956
 		$imapFilter = new Horde_Imap_Client_Search_Query();
1957 1957
 		$imapFilter->charset('UTF-8');
1958 1958
 
1959 1959
 		//_debug_array($_criterias);
1960
-		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
1961
-		if((!is_array($_criterias) || $_criterias['status']=='any') &&
1960
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' Criterias:'.(!is_array($_criterias) ? " none -> returning" : array2string($_criterias)));
1961
+		if ((!is_array($_criterias) || $_criterias['status'] == 'any') &&
1962 1962
 			(!isset($_criterias['string']) || empty($_criterias['string'])) &&
1963
-			(!isset($_criterias['range'])|| empty($_criterias['range']) ||
1964
-			( !empty($_criterias['range'])&& ($_criterias['range']!='BETWEEN' && empty($_criterias['date'])||
1965
-			($_criterias['range']=='BETWEEN' && empty($_criterias['since'])&& empty($_criterias['before']))))))
1963
+			(!isset($_criterias['range']) || empty($_criterias['range']) ||
1964
+			(!empty($_criterias['range']) && ($_criterias['range'] != 'BETWEEN' && empty($_criterias['date']) ||
1965
+			($_criterias['range'] == 'BETWEEN' && empty($_criterias['since']) && empty($_criterias['before']))))))
1966 1966
 		{
1967 1967
 			//error_log(__METHOD__.' ('.__LINE__.') returning early Criterias:'.print_r($_criterias, true));
1968
-			$imapFilter->flag('DELETED', $set=false);
1968
+			$imapFilter->flag('DELETED', $set = false);
1969 1969
 			return $imapFilter;
1970 1970
 		}
1971 1971
 		$queryValid = false;
1972 1972
 		// statusQuery MUST be placed first, as search for subject/mailbody and such is
1973 1973
 		// depending on charset. flagSearch is not BUT messes the charset if called afterwards
1974 1974
 		$statusQueryValid = false;
1975
-		foreach((array)$_criterias['status'] as $k => $criteria) {
1975
+		foreach ((array)$_criterias['status'] as $k => $criteria) {
1976 1976
 			$imapStatusFilter = new Horde_Imap_Client_Search_Query();
1977 1977
 			$imapStatusFilter->charset('UTF-8');
1978 1978
 			$criteria = strtoupper($criteria);
@@ -1982,12 +1982,12 @@  discard block
 block discarded – undo
1982 1982
 				case 'FLAGGED':
1983 1983
 				case 'RECENT':
1984 1984
 				case 'SEEN':
1985
-					$imapStatusFilter->flag($criteria, $set=true);
1986
-					$queryValid = $statusQueryValid =true;
1985
+					$imapStatusFilter->flag($criteria, $set = true);
1986
+					$queryValid = $statusQueryValid = true;
1987 1987
 					break;
1988 1988
 				case 'READ':
1989
-					$imapStatusFilter->flag('SEEN', $set=true);
1990
-					$queryValid = $statusQueryValid =true;
1989
+					$imapStatusFilter->flag('SEEN', $set = true);
1990
+					$queryValid = $statusQueryValid = true;
1991 1991
 					break;
1992 1992
 				case 'LABEL1':
1993 1993
 				case 'KEYWORD1':
@@ -1999,38 +1999,38 @@  discard block
 block discarded – undo
1999 1999
 				case 'KEYWORD4':
2000 2000
 				case 'LABEL5':
2001 2001
 				case 'KEYWORD5':
2002
-					$imapStatusFilter->flag(str_ireplace('KEYWORD','$LABEL',$criteria), $set=true);
2003
-					$queryValid = $statusQueryValid =true;
2002
+					$imapStatusFilter->flag(str_ireplace('KEYWORD', '$LABEL', $criteria), $set = true);
2003
+					$queryValid = $statusQueryValid = true;
2004 2004
 					break;
2005 2005
 				case 'NEW':
2006
-					$imapStatusFilter->flag('RECENT', $set=true);
2007
-					$imapStatusFilter->flag('SEEN', $set=false);
2008
-					$queryValid = $statusQueryValid =true;
2006
+					$imapStatusFilter->flag('RECENT', $set = true);
2007
+					$imapStatusFilter->flag('SEEN', $set = false);
2008
+					$queryValid = $statusQueryValid = true;
2009 2009
 					break;
2010 2010
 				case 'OLD':
2011
-					$imapStatusFilter->flag('RECENT', $set=false);
2012
-					$queryValid = $statusQueryValid =true;
2011
+					$imapStatusFilter->flag('RECENT', $set = false);
2012
+					$queryValid = $statusQueryValid = true;
2013 2013
 					break;
2014 2014
 // operate only on system flags
2015 2015
 //        $systemflags = array(
2016 2016
 //            'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'RECENT', 'SEEN'
2017 2017
 //        );
2018 2018
 				case 'UNANSWERED':
2019
-					$imapStatusFilter->flag('ANSWERED', $set=false);
2020
-					$queryValid = $statusQueryValid =true;
2019
+					$imapStatusFilter->flag('ANSWERED', $set = false);
2020
+					$queryValid = $statusQueryValid = true;
2021 2021
 					break;
2022 2022
 				case 'UNDELETED':
2023
-					$imapFilter->flag('DELETED', $set=false);
2023
+					$imapFilter->flag('DELETED', $set = false);
2024 2024
 					$queryValid = true;
2025 2025
 					break;
2026 2026
 				case 'UNFLAGGED':
2027
-					$imapStatusFilter->flag('FLAGGED', $set=false);
2028
-					$queryValid = $statusQueryValid =true;
2027
+					$imapStatusFilter->flag('FLAGGED', $set = false);
2028
+					$queryValid = $statusQueryValid = true;
2029 2029
 					break;
2030 2030
 				case 'UNREAD':
2031 2031
 				case 'UNSEEN':
2032
-					$imapStatusFilter->flag('SEEN', $set=false);
2033
-					$queryValid = $statusQueryValid =true;
2032
+					$imapStatusFilter->flag('SEEN', $set = false);
2033
+					$queryValid = $statusQueryValid = true;
2034 2034
 					break;
2035 2035
 				case 'UNLABEL1':
2036 2036
 				case 'UNKEYWORD1':
@@ -2042,8 +2042,8 @@  discard block
 block discarded – undo
2042 2042
 				case 'UNKEYWORD4':
2043 2043
 				case 'UNLABEL5':
2044 2044
 				case 'UNKEYWORD5':
2045
-					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD','UNLABEL'),'$LABEL',$criteria), $set=false);
2046
-					$queryValid = $statusQueryValid =true;
2045
+					$imapStatusFilter->flag(str_ireplace(array('UNKEYWORD', 'UNLABEL'), '$LABEL', $criteria), $set = false);
2046
+					$queryValid = $statusQueryValid = true;
2047 2047
 					break;
2048 2048
 				default:
2049 2049
 					$statusQueryValid = false;
@@ -2059,20 +2059,20 @@  discard block
 block discarded – undo
2059 2059
 		$imapSearchFilter = new Horde_Imap_Client_Search_Query();
2060 2060
 		$imapSearchFilter->charset('UTF-8');
2061 2061
 
2062
-		if(!empty($_criterias['string'])) {
2062
+		if (!empty($_criterias['string'])) {
2063 2063
 			$criteria = strtoupper($_criterias['type']);
2064 2064
 			switch ($criteria) {
2065 2065
 				case 'BYDATE':
2066 2066
 				case 'QUICK':
2067 2067
 				case 'QUICKWITHCC':
2068
-					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not=false);
2068
+					$imapSearchFilter->headerText('SUBJECT', $_criterias['string'], $not = false);
2069 2069
 					//$imapSearchFilter->charset('UTF-8');
2070 2070
 					$imapFilter2 = new Horde_Imap_Client_Search_Query();
2071 2071
 					$imapFilter2->charset('UTF-8');
2072
-					if($this->isSentFolder($_folder)) {
2073
-						$imapFilter2->headerText('TO', $_criterias['string'], $not=false);
2072
+					if ($this->isSentFolder($_folder)) {
2073
+						$imapFilter2->headerText('TO', $_criterias['string'], $not = false);
2074 2074
 					} else {
2075
-						$imapFilter2->headerText('FROM', $_criterias['string'], $not=false);
2075
+						$imapFilter2->headerText('FROM', $_criterias['string'], $not = false);
2076 2076
 					}
2077 2077
 					if ($_supportsOrInQuery)
2078 2078
 					{
@@ -2082,31 +2082,31 @@  discard block
 block discarded – undo
2082 2082
 					{
2083 2083
 						$imapSearchFilter->andSearch($imapFilter2);
2084 2084
 					}
2085
-					if ($_supportsOrInQuery && $criteria=='QUICKWITHCC')
2085
+					if ($_supportsOrInQuery && $criteria == 'QUICKWITHCC')
2086 2086
 					{
2087 2087
 						$imapFilter3 = new Horde_Imap_Client_Search_Query();
2088 2088
 						$imapFilter3->charset('UTF-8');
2089
-						$imapFilter3->headerText('CC', $_criterias['string'], $not=false);
2089
+						$imapFilter3->headerText('CC', $_criterias['string'], $not = false);
2090 2090
 						$imapSearchFilter->orSearch($imapFilter3);
2091 2091
 					}
2092 2092
 					$queryValid = true;
2093 2093
 					break;
2094 2094
 				case 'LARGER':
2095 2095
 				case 'SMALLER':
2096
-					if (strlen(trim($_criterias['string'])) != strlen((float) trim($_criterias['string'])))
2096
+					if (strlen(trim($_criterias['string'])) != strlen((float)trim($_criterias['string'])))
2097 2097
 					{
2098 2098
 						//examine string to evaluate size
2099
-						$unit = strtoupper(trim(substr(trim($_criterias['string']),strlen((float) trim($_criterias['string'])))));
2100
-						$multipleBy = array('KB'=>1024,'K'=>1024,
2101
-											'MB'=>1024*1000,'M'=>1024*1000,
2102
-											'GB'=>1024*1000*1000,'G'=>1024*1000*1000,
2103
-											'TB'=>1024*1000*1000*1000,'T'=>1024*1000*1000*1000);
2104
-						$numberinBytes=(float)$_criterias['string'];
2105
-						if (isset($multipleBy[$unit])) $numberinBytes=(float)$_criterias['string']*$multipleBy[$unit];
2099
+						$unit = strtoupper(trim(substr(trim($_criterias['string']), strlen((float)trim($_criterias['string'])))));
2100
+						$multipleBy = array('KB'=>1024, 'K'=>1024,
2101
+											'MB'=>1024 * 1000, 'M'=>1024 * 1000,
2102
+											'GB'=>1024 * 1000 * 1000, 'G'=>1024 * 1000 * 1000,
2103
+											'TB'=>1024 * 1000 * 1000 * 1000, 'T'=>1024 * 1000 * 1000 * 1000);
2104
+						$numberinBytes = (float)$_criterias['string'];
2105
+						if (isset($multipleBy[$unit])) $numberinBytes = (float)$_criterias['string'] * $multipleBy[$unit];
2106 2106
 						//error_log(__METHOD__.__LINE__.'#'.$_criterias['string'].'->'.(float)$_criterias['string'].'#'.$unit.' ='.$numberinBytes);
2107
-						$_criterias['string']=$numberinBytes;
2107
+						$_criterias['string'] = $numberinBytes;
2108 2108
 					}
2109
-					$imapSearchFilter->size( $_criterias['string'], ($criteria=='LARGER'?true:false), $not=false);
2109
+					$imapSearchFilter->size($_criterias['string'], ($criteria == 'LARGER' ? true : false), $not = false);
2110 2110
 					//$imapSearchFilter->charset('UTF-8');
2111 2111
 					$queryValid = true;
2112 2112
 					break;
@@ -2115,31 +2115,31 @@  discard block
 block discarded – undo
2115 2115
 				case 'CC':
2116 2116
 				case 'BCC':
2117 2117
 				case 'SUBJECT':
2118
-					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not=false);
2118
+					$imapSearchFilter->headerText($criteria, $_criterias['string'], $not = false);
2119 2119
 					//$imapSearchFilter->charset('UTF-8');
2120 2120
 					$queryValid = true;
2121 2121
 					break;
2122 2122
 				case 'BODY':
2123 2123
 				case 'TEXT':
2124
-					$imapSearchFilter->text($_criterias['string'],($criteria=='BODY'?true:false), $not=false);
2124
+					$imapSearchFilter->text($_criterias['string'], ($criteria == 'BODY' ? true : false), $not = false);
2125 2125
 					//$imapSearchFilter->charset('UTF-8');
2126 2126
 					$queryValid = true;
2127 2127
 					break;
2128 2128
 				case 'SINCE':
2129
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2129
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2130 2130
 					$queryValid = true;
2131 2131
 					break;
2132 2132
 				case 'BEFORE':
2133
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2133
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2134 2134
 					$queryValid = true;
2135 2135
 					break;
2136 2136
 				case 'ON':
2137
-					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2137
+					$imapSearchFilter->dateSearch(new DateTime($_criterias['string']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2138 2138
 					$queryValid = true;
2139 2139
 					break;
2140 2140
 			}
2141 2141
 		}
2142
-		if ($statusQueryValid && !$queryValid) $queryValid=true;
2142
+		if ($statusQueryValid && !$queryValid) $queryValid = true;
2143 2143
 		if ($queryValid) $imapFilter->andSearch($imapSearchFilter);
2144 2144
 
2145 2145
 		if (isset($_criterias['range']) && !empty($_criterias['range']))
@@ -2148,12 +2148,12 @@  discard block
 block discarded – undo
2148 2148
 			$imapRangeFilter = new Horde_Imap_Client_Search_Query();
2149 2149
 			$imapRangeFilter->charset('UTF-8');
2150 2150
 			$criteria = strtoupper($_criterias['range']);
2151
-			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since']==$_criterias['before'])
2151
+			if ($_criterias['range'] == "BETWEEN" && isset($_criterias['since']) && isset($_criterias['before']) && $_criterias['since'] == $_criterias['before'])
2152 2152
 			{
2153
-				$_criterias['date']=$_criterias['since'];
2153
+				$_criterias['date'] = $_criterias['since'];
2154 2154
 				unset($_criterias['since']);
2155 2155
 				unset($_criterias['before']);
2156
-				$criteria=$_criterias['range']='ON';
2156
+				$criteria = $_criterias['range'] = 'ON';
2157 2157
 			}
2158 2158
 			switch ($criteria) {
2159 2159
 				case 'BETWEEN':
@@ -2161,7 +2161,7 @@  discard block
 block discarded – undo
2161 2161
 					//enddate
2162 2162
 					if ($_criterias['since'])
2163 2163
 					{
2164
-						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2164
+						$imapRangeFilter->dateSearch(new DateTime($_criterias['since']), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2165 2165
 						$rangeValid = true;
2166 2166
 					}
2167 2167
 					//startdate
@@ -2170,28 +2170,28 @@  discard block
 block discarded – undo
2170 2170
 						$imapRangeFilter2 = new Horde_Imap_Client_Search_Query();
2171 2171
 						$imapRangeFilter2->charset('UTF-8');
2172 2172
 						//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2173
-						$_criterias['before'] = date("d-M-Y",DateTime::to($_criterias['before'],'ts')+(3600*24));
2174
-						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2173
+						$_criterias['before'] = date("d-M-Y", DateTime::to($_criterias['before'], 'ts') + (3600 * 24));
2174
+						$imapRangeFilter2->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2175 2175
 						$imapRangeFilter->andSearch($imapRangeFilter2);
2176 2176
 						$rangeValid = true;
2177 2177
 					}
2178 2178
 					break;
2179 2179
 				case 'SINCE'://enddate
2180
-					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since']?$_criterias['since']:$_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header=true, $not=false);
2180
+					$imapRangeFilter->dateSearch(new DateTime(($_criterias['since'] ? $_criterias['since'] : $_criterias['date'])), Horde_Imap_Client_Search_Query::DATE_SINCE, $header = true, $not = false);
2181 2181
 					$rangeValid = true;
2182 2182
 					break;
2183 2183
 				case 'BEFORE'://startdate
2184 2184
 					//our before (startdate) is inklusive, as we work with "d-M-Y", we must add a day
2185
-					$_criterias['before'] = date("d-M-Y",DateTime::to(($_criterias['before']?$_criterias['before']:$_criterias['date']),'ts')+(3600*24));
2186
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header=true, $not=false);
2185
+					$_criterias['before'] = date("d-M-Y", DateTime::to(($_criterias['before'] ? $_criterias['before'] : $_criterias['date']), 'ts') + (3600 * 24));
2186
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['before']), Horde_Imap_Client_Search_Query::DATE_BEFORE, $header = true, $not = false);
2187 2187
 					$rangeValid = true;
2188 2188
 					break;
2189 2189
 				case 'ON':
2190
-					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header=true, $not=false);
2190
+					$imapRangeFilter->dateSearch(new DateTime($_criterias['date']), Horde_Imap_Client_Search_Query::DATE_ON, $header = true, $not = false);
2191 2191
 					$rangeValid = true;
2192 2192
 					break;
2193 2193
 			}
2194
-			if ($rangeValid && !$queryValid) $queryValid=true;
2194
+			if ($rangeValid && !$queryValid) $queryValid = true;
2195 2195
 			if ($rangeValid) $imapFilter->andSearch($imapRangeFilter);
2196 2196
 		}
2197 2197
 		if (self::$debug)
@@ -2200,8 +2200,8 @@  discard block
 block discarded – undo
2200 2200
 			$query_str = $imapFilter->build();
2201 2201
 			//error_log(__METHOD__.' ('.__LINE__.') '.' '.$query_str['query'].' created by Criterias:'.(!is_array($_criterias)?" none -> returning":array2string($_criterias)));
2202 2202
 		}
2203
-		if($queryValid==false) {
2204
-			$imapFilter->flag('DELETED', $set=false);
2203
+		if ($queryValid == false) {
2204
+			$imapFilter->flag('DELETED', $set = false);
2205 2205
 			return $imapFilter;
2206 2206
 		} else {
2207 2207
 			return $imapFilter;
@@ -2215,11 +2215,11 @@  discard block
 block discarded – undo
2215 2215
 	 * @param  mixed/boolean $_tryIDNConversion (true/false AND FORCE): try IDN Conversion on domainparts of emailADRESSES
2216 2216
 	 * @return mixed - based on the input type
2217 2217
 	 */
2218
-	static function decode_header($_string, $_tryIDNConversion=false)
2218
+	static function decode_header($_string, $_tryIDNConversion = false)
2219 2219
 	{
2220 2220
 		if (is_array($_string))
2221 2221
 		{
2222
-			foreach($_string as $k=>$v)
2222
+			foreach ($_string as $k=>$v)
2223 2223
 			{
2224 2224
 				$_string[$k] = self::decode_header($v, $_tryIDNConversion);
2225 2225
 			}
@@ -2227,18 +2227,18 @@  discard block
 block discarded – undo
2227 2227
 		}
2228 2228
 		else
2229 2229
 		{
2230
-			$_string = Mail\Html::decodeMailHeader($_string,self::$displayCharset);
2230
+			$_string = Mail\Html::decodeMailHeader($_string, self::$displayCharset);
2231 2231
 			$test = @json_encode($_string);
2232 2232
 			//error_log(__METHOD__.__LINE__.' ->'.strlen($singleBodyPart['body']).' Error:'.json_last_error().'<- BodyPart:#'.$test.'#');
2233
-			if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2233
+			if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2234 2234
 			{
2235 2235
 				// try to fix broken utf8
2236 2236
 				$x = utf8_encode($_string);
2237 2237
 				$test = @json_encode($x);
2238
-				if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2238
+				if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2239 2239
 				{
2240 2240
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
2241
-					$_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));
2241
+					$_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));
2242 2242
 				}
2243 2243
 				else
2244 2244
 				{
@@ -2246,7 +2246,7 @@  discard block
 block discarded – undo
2246 2246
 				}
2247 2247
 			}
2248 2248
 
2249
-			if ($_tryIDNConversion===true && stripos($_string,'@')!==false)
2249
+			if ($_tryIDNConversion === true && stripos($_string, '@') !== false)
2250 2250
 			{
2251 2251
 				$rfcAddr = self::parseAddressList($_string);
2252 2252
 				$stringA = array();
@@ -2258,11 +2258,11 @@  discard block
 block discarded – undo
2258 2258
 						$stringA = array();
2259 2259
 						break; // skip idna conversion if we encounter an error here
2260 2260
 					}
2261
-					$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox,Horde_Idna::decode($_rfcAddr->host),$_rfcAddr->personal);
2261
+					$stringA[] = imap_rfc822_write_address($_rfcAddr->mailbox, Horde_Idna::decode($_rfcAddr->host), $_rfcAddr->personal);
2262 2262
 				}
2263
-				if (!empty($stringA)) $_string = implode(',',$stringA);
2263
+				if (!empty($stringA)) $_string = implode(',', $stringA);
2264 2264
 			}
2265
-			if ($_tryIDNConversion==='FORCE')
2265
+			if ($_tryIDNConversion === 'FORCE')
2266 2266
 			{
2267 2267
 				//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_string.'='.Horde_Idna::decode($_string));
2268 2268
 				$_string = Horde_Idna::decode($_string);
@@ -2278,17 +2278,17 @@  discard block
 block discarded – undo
2278 2278
 	 * @param  boolean $decode try decoding
2279 2279
 	 * @return mixed - based on the input type
2280 2280
 	 */
2281
-	function decode_subject($_string,$decode=true)
2281
+	function decode_subject($_string, $decode = true)
2282 2282
 	{
2283 2283
 		#$string = $_string;
2284
-		if($_string=='NIL')
2284
+		if ($_string == 'NIL')
2285 2285
 		{
2286 2286
 			return 'No Subject';
2287 2287
 		}
2288 2288
 		if ($decode) $_string = self::decode_header($_string);
2289 2289
 		// make sure its utf-8
2290 2290
 		$test = @json_encode($_string);
2291
-		if (($test=="null" || $test === false || is_null($test)) && strlen($_string)>0)
2291
+		if (($test == "null" || $test === false || is_null($test)) && strlen($_string) > 0)
2292 2292
 		{
2293 2293
 			$_string = utf8_encode($_string);
2294 2294
 		}
@@ -2340,18 +2340,18 @@  discard block
 block discarded – undo
2340 2340
 	function createFolder($_parent, $_folderName, &$_error)
2341 2341
 	{
2342 2342
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."->"."$_parent, $_folderName called from:".function_backtrace());
2343
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2344
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2343
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2344
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2345 2345
 
2346
-		if(empty($parent)) {
2346
+		if (empty($parent)) {
2347 2347
 			$newFolderName = $folderName;
2348 2348
 		} else {
2349 2349
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2350
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2350
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2351 2351
 		}
2352 2352
 		if (empty($newFolderName)) return false;
2353 2353
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.'->'.$newFolderName);
2354
-		if ($this->folderExists($newFolderName,true))
2354
+		if ($this->folderExists($newFolderName, true))
2355 2355
 		{
2356 2356
 			if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '." Folder $newFolderName already exists.");
2357 2357
 			return $newFolderName;
@@ -2368,7 +2368,7 @@  discard block
 block discarded – undo
2368 2368
 		}
2369 2369
 		catch (\Exception $e)
2370 2370
 		{
2371
-			$_error = lang('Could not create Folder %1 Reason: %2',$newFolderName,$e->getMessage());
2371
+			$_error = lang('Could not create Folder %1 Reason: %2', $newFolderName, $e->getMessage());
2372 2372
 			error_log(__METHOD__.' ('.__LINE__.') '.' create Folder '.$newFolderName.'->'.$e->getMessage().' ('.$e->details.') Namespace:'.array2string($this->icServer->getNameSpaces()).function_backtrace());
2373 2373
 			return false;
2374 2374
 		}
@@ -2397,15 +2397,15 @@  discard block
 block discarded – undo
2397 2397
 	 */
2398 2398
 	function renameFolder($_oldFolderName, $_parent, $_folderName)
2399 2399
 	{
2400
-		$oldFolderName	= $_oldFolderName;//$this->_encodeFolderName($_oldFolderName);
2401
-		$parent		= $_parent;//$this->_encodeFolderName($_parent);
2402
-		$folderName	= $_folderName;//$this->_encodeFolderName($_folderName);
2400
+		$oldFolderName = $_oldFolderName; //$this->_encodeFolderName($_oldFolderName);
2401
+		$parent = $_parent; //$this->_encodeFolderName($_parent);
2402
+		$folderName = $_folderName; //$this->_encodeFolderName($_folderName);
2403 2403
 
2404
-		if(empty($parent)) {
2404
+		if (empty($parent)) {
2405 2405
 			$newFolderName = $folderName;
2406 2406
 		} else {
2407 2407
 			$HierarchyDelimiter = $this->getHierarchyDelimiter();
2408
-			$newFolderName = $parent . $HierarchyDelimiter . $folderName;
2408
+			$newFolderName = $parent.$HierarchyDelimiter.$folderName;
2409 2409
 		}
2410 2410
 		if (self::$debug) error_log("create folder: $newFolderName");
2411 2411
 		try
@@ -2414,10 +2414,10 @@  discard block
 block discarded – undo
2414 2414
 		}
2415 2415
 		catch (\Exception $e)
2416 2416
 		{
2417
-			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage());;
2417
+			throw new Exception(__METHOD__." failed for $oldFolderName (rename to: $newFolderName) with error:".$e->getMessage()); ;
2418 2418
 		}
2419 2419
 		// clear FolderExistsInfoCache
2420
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2420
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2421 2421
 
2422 2422
 		return $newFolderName;
2423 2423
 
@@ -2436,15 +2436,15 @@  discard block
 block discarded – undo
2436 2436
 		//$folderName = $this->_encodeFolderName($_folderName);
2437 2437
 		try
2438 2438
 		{
2439
-			$this->icServer->subscribeMailbox($_folderName,false);
2439
+			$this->icServer->subscribeMailbox($_folderName, false);
2440 2440
 			$this->icServer->deleteMailbox($_folderName);
2441 2441
 		}
2442 2442
 		catch (\Exception $e)
2443 2443
 		{
2444
-			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage());;
2444
+			throw new Exception("Deleting Folder $_folderName failed! Error:".$e->getMessage()); ;
2445 2445
 		}
2446 2446
 		// clear FolderExistsInfoCache
2447
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,60*60*5);
2447
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, 60 * 60 * 5);
2448 2448
 
2449 2449
 		return true;
2450 2450
 	}
@@ -2479,10 +2479,10 @@  discard block
 block discarded – undo
2479 2479
 	 *
2480 2480
 	 * @return array with folder objects. eg.: INBOX => {inbox object}
2481 2481
 	 */
2482
-	function getFolderObjects($_subscribedOnly=false, $_getCounters=false, $_alwaysGetDefaultFolders=false,$_useCacheIfPossible=true)
2482
+	function getFolderObjects($_subscribedOnly = false, $_getCounters = false, $_alwaysGetDefaultFolders = false, $_useCacheIfPossible = true)
2483 2483
 	{
2484 2484
 		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' ServerID:'.$this->icServer->ImapServerId.", subscribedOnly:$_subscribedOnly, getCounters:$_getCounters, alwaysGetDefaultFolders:$_alwaysGetDefaultFolders, _useCacheIfPossible:$_useCacheIfPossible");
2485
-		if (self::$debugTimes) $starttime = microtime (true);
2485
+		if (self::$debugTimes) $starttime = microtime(true);
2486 2486
 		static $folders2return;
2487 2487
 		//$_subscribedOnly=false;
2488 2488
 		// always use static on single request if info is available;
@@ -2490,42 +2490,42 @@  discard block
 block discarded – undo
2490 2490
 		// set $_useCacheIfPossible to false !
2491 2491
 		if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2492 2492
 		{
2493
-			if (self::$debugTimes) self::logRunTimes($starttime,null,'using static',__METHOD__.' ('.__LINE__.') ');
2493
+			if (self::$debugTimes) self::logRunTimes($starttime, null, 'using static', __METHOD__.' ('.__LINE__.') ');
2494 2494
 			return $folders2return[$this->icServer->ImapServerId];
2495 2495
 		}
2496 2496
 
2497
-		if ($_subscribedOnly && $_getCounters===false)
2497
+		if ($_subscribedOnly && $_getCounters === false)
2498 2498
 		{
2499
-			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),60*60*1);
2499
+			if (is_null($folders2return)) $folders2return = Cache::getCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60 * 60 * 1);
2500 2500
 			if ($_useCacheIfPossible && isset($folders2return[$this->icServer->ImapServerId]) && !empty($folders2return[$this->icServer->ImapServerId]))
2501 2501
 			{
2502 2502
 				//error_log(__METHOD__.' ('.__LINE__.') '.' using Cached folderObjects'.array2string($folders2return[$this->icServer->ImapServerId]));
2503
-				if (self::$debugTimes) self::logRunTimes($starttime,null,'from Cache',__METHOD__.' ('.__LINE__.') ');
2503
+				if (self::$debugTimes) self::logRunTimes($starttime, null, 'from Cache', __METHOD__.' ('.__LINE__.') ');
2504 2504
 				return $folders2return[$this->icServer->ImapServerId];
2505 2505
 			}
2506 2506
 		}
2507 2507
 		// use $folderBasicInfo for holding attributes and other basic folderinfo $folderBasicInfo[$this->icServer->ImapServerId]
2508 2508
 		static $folderBasicInfo;
2509
-		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);
2509
+		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);
2510 2510
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string(array_keys($folderBasicInfo[$this->icServer->ImapServerId])));
2511 2511
 
2512 2512
 		$delimiter = $this->getHierarchyDelimiter();
2513 2513
 
2514 2514
 		$inboxData = new \stdClass;
2515
-		$inboxData->name 		= 'INBOX';
2515
+		$inboxData->name = 'INBOX';
2516 2516
 		$inboxData->folderName		= 'INBOX';
2517
-		$inboxData->displayName		= lang('INBOX');
2517
+		$inboxData->displayName = lang('INBOX');
2518 2518
 		$inboxData->delimiter 		= $delimiter;
2519
-		$inboxData->shortFolderName	= 'INBOX';
2520
-		$inboxData->shortDisplayName	= lang('INBOX');
2519
+		$inboxData->shortFolderName = 'INBOX';
2520
+		$inboxData->shortDisplayName = lang('INBOX');
2521 2521
 		$inboxData->subscribed = true;
2522
-		if($_getCounters == true) {
2522
+		if ($_getCounters == true) {
2523 2523
 			$inboxData->counter = $this->getMailBoxCounters('INBOX');
2524 2524
 		}
2525 2525
 		// force unsubscribed by preference showAllFoldersInFolderPane
2526 2526
 		if ($_subscribedOnly == true &&
2527 2527
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2528
-			$this->mailPreferences['showAllFoldersInFolderPane']==1)
2528
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1)
2529 2529
 		{
2530 2530
 			$_subscribedOnly = false;
2531 2531
 		}
@@ -2538,12 +2538,12 @@  discard block
 block discarded – undo
2538 2538
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2539 2539
 		if (is_array($nameSpace))
2540 2540
 		{
2541
-			foreach($nameSpace as $k => $singleNameSpace) {
2541
+			foreach ($nameSpace as $k => $singleNameSpace) {
2542 2542
 				$type = $singleNameSpace['type'];
2543 2543
 				// the following line (assumption that for the same namespace the delimiter should be equal) may be wrong
2544
-				$foldersNameSpace[$type]['delimiter']  = $singleNameSpace['delimiter'];
2544
+				$foldersNameSpace[$type]['delimiter'] = $singleNameSpace['delimiter'];
2545 2545
 
2546
-				if(is_array($singleNameSpace)&&$fetchedAllInOneGo==false) {
2546
+				if (is_array($singleNameSpace) && $fetchedAllInOneGo == false) {
2547 2547
 					// fetch and sort the subscribed folders
2548 2548
 					// we alway fetch the subscribed, as this provides the only way to tell
2549 2549
 					// if a folder is subscribed or not
@@ -2551,22 +2551,22 @@  discard block
 block discarded – undo
2551 2551
 					{
2552 2552
 						try
2553 2553
 						{
2554
-							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('',0,true);
2554
+							$subscribedMailboxes = $this->icServer->listSubscribedMailboxes('', 0, true);
2555 2555
 							if (!empty($subscribedMailboxes))
2556 2556
 							{
2557 2557
 								$fetchedAllInOneGo = true;
2558 2558
 							}
2559 2559
 							else
2560 2560
 							{
2561
-								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'],0,true);
2561
+								$subscribedMailboxes = $this->icServer->listSubscribedMailboxes($singleNameSpace['prefix'], 0, true);
2562 2562
 							}
2563 2563
 						}
2564
-						catch(Exception $e)
2564
+						catch (Exception $e)
2565 2565
 						{
2566 2566
 							continue;
2567 2567
 						}
2568 2568
 						//echo "subscribedMailboxes";_debug_array($subscribedMailboxes);
2569
-						$subscribedFoldersPerNS = (!empty($subscribedMailboxes)?array_keys($subscribedMailboxes):array());
2569
+						$subscribedFoldersPerNS = (!empty($subscribedMailboxes) ? array_keys($subscribedMailboxes) : array());
2570 2570
 						//if (is_array($foldersNameSpace[$type]['subscribed'])) sort($foldersNameSpace[$type]['subscribed']);
2571 2571
 						//_debug_array($foldersNameSpace);
2572 2572
 						//error_log(__METHOD__.__LINE__.array2string($singleNameSpace).':#:'.array2string($subscribedFoldersPerNS));
@@ -2576,18 +2576,18 @@  discard block
 block discarded – undo
2576 2576
 							foreach ($subscribedMailboxes as $k => $finfo)
2577 2577
 							{
2578 2578
 								//error_log(__METHOD__.__LINE__.$k.':#:'.array2string($finfo));
2579
-								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k]=
2580
-								$folderBasicInfo[$this->icServer->ImapServerId][$k]=array(
2579
+								$subscribedFoldersForCache[$this->icServer->ImapServerId][$k] =
2580
+								$folderBasicInfo[$this->icServer->ImapServerId][$k] = array(
2581 2581
 									'MAILBOX'=>$finfo['MAILBOX'],
2582 2582
 									'ATTRIBUTES'=>$finfo['ATTRIBUTES'],
2583
-									'delimiter'=>$finfo['delimiter'],//lowercase for some reason???
2584
-									'SUBSCRIBED'=>$finfo['SUBSCRIBED'],//seeded by getMailboxes
2583
+									'delimiter'=>$finfo['delimiter'], //lowercase for some reason???
2584
+									'SUBSCRIBED'=>$finfo['SUBSCRIBED'], //seeded by getMailboxes
2585 2585
 								);
2586
-								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k,$foldersNameSpace[$type]['subscribed']))
2586
+								if (empty($foldersNameSpace[$type]['subscribed']) || !in_array($k, $foldersNameSpace[$type]['subscribed']))
2587 2587
 								{
2588 2588
 									$foldersNameSpace[$type]['subscribed'][] = $k;
2589 2589
 								}
2590
-								if (empty($foldersNameSpace[$type]['all']) || !in_array($k,$foldersNameSpace[$type]['all']))
2590
+								if (empty($foldersNameSpace[$type]['all']) || !in_array($k, $foldersNameSpace[$type]['all']))
2591 2591
 								{
2592 2592
 									$foldersNameSpace[$type]['all'][] = $k;
2593 2593
 								}
@@ -2610,7 +2610,7 @@  discard block
 block discarded – undo
2610 2610
 						// that may produce problems, when encountering recursions probably
2611 2611
 						// horde is handling that, so we do not; keep that in mind!
2612 2612
 						//$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],2,true);
2613
-						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'],0,true);
2613
+						$allMailboxesExt = $this->icServer->getMailboxes($singleNameSpace['prefix'], 0, true);
2614 2614
 					}
2615 2615
 					catch (\Exception $e)
2616 2616
 					{
@@ -2628,26 +2628,26 @@  discard block
 block discarded – undo
2628 2628
 					foreach ($allMailboxesExt as $mbx) {
2629 2629
 						if (!isset($folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2630 2630
 						{
2631
-							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']]=array(
2631
+							$folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']] = array(
2632 2632
 								'MAILBOX'=>$mbx['MAILBOX'],
2633 2633
 								'ATTRIBUTES'=>$mbx['ATTRIBUTES'],
2634
-								'delimiter'=>$mbx['delimiter'],//lowercase for some reason???
2635
-								'SUBSCRIBED'=>$mbx['SUBSCRIBED'],//seeded by getMailboxes
2634
+								'delimiter'=>$mbx['delimiter'], //lowercase for some reason???
2635
+								'SUBSCRIBED'=>$mbx['SUBSCRIBED'], //seeded by getMailboxes
2636 2636
 							);
2637 2637
 							if ($mbx['SUBSCRIBED'] && !isset($subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']]))
2638 2638
 							{
2639 2639
 								$subscribedFoldersForCache[$this->icServer->ImapServerId][$mbx['MAILBOX']] = $folderBasicInfo[$this->icServer->ImapServerId][$mbx['MAILBOX']];
2640 2640
 							}
2641 2641
 						}
2642
-						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'],$foldersNameSpace[$type]['subscribed'])))
2642
+						if ($mbx['SUBSCRIBED'] && (empty($foldersNameSpace[$type]['subscribed']) || !in_array($mbx['MAILBOX'], $foldersNameSpace[$type]['subscribed'])))
2643 2643
 						{
2644 2644
 							$foldersNameSpace[$type]['subscribed'][] = $mbx['MAILBOX'];
2645 2645
 						}
2646 2646
 						//echo __METHOD__;_debug_array($mbx);
2647 2647
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
2648
-						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']])||
2649
-							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']])||
2650
-							(substr($mbx['MAILBOX'],-1)==$foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'],0,-1)]))
2648
+						if (isset($allMailBoxesExtSorted[$mbx['MAILBOX']]) ||
2649
+							isset($allMailBoxesExtSorted[$mbx['MAILBOX'].$foldersNameSpace[$type]['delimiter']]) ||
2650
+							(substr($mbx['MAILBOX'], -1) == $foldersNameSpace[$type]['delimiter'] && isset($allMailBoxesExtSorted[substr($mbx['MAILBOX'], 0, -1)]))
2651 2651
 						) continue;
2652 2652
 
2653 2653
 						//echo '#'.$mbx['MAILBOX'].':'.array2string($mbx)."#<br>";
@@ -2657,7 +2657,7 @@  discard block
 block discarded – undo
2657 2657
 					//_debug_array(array_keys($allMailBoxesExtSorted));
2658 2658
 					$allMailboxes = array();
2659 2659
 					foreach ((array)$allMailBoxesExtSorted as $mbx) {
2660
-						if (!in_array($mbx['MAILBOX'],$allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2660
+						if (!in_array($mbx['MAILBOX'], $allMailboxes)) $allMailboxes[] = $mbx['MAILBOX'];
2661 2661
 						//echo "Result:";_debug_array($allMailboxes);
2662 2662
 					}
2663 2663
 					$foldersNameSpace[$type]['all'] = $allMailboxes;
@@ -2666,57 +2666,57 @@  discard block
 block discarded – undo
2666 2666
 			}
2667 2667
 		}
2668 2668
 		//subscribed folders may be used in getFolderStatus
2669
-		Cache::setCache(Cache::INSTANCE,'email','subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']),$subscribedFoldersForCache,$expiration=60*60*1);
2669
+		Cache::setCache(Cache::INSTANCE, 'email', 'subscribedFolders'.trim($GLOBALS['egw_info']['user']['account_id']), $subscribedFoldersForCache, $expiration = 60 * 60 * 1);
2670 2670
 		//echo "<br>FolderNameSpace To Process:";_debug_array($foldersNameSpace);
2671 2671
 		$autoFolderObjects = $folders = array();
2672 2672
 		$autofolder_exists = array();
2673
-		foreach( array('personal', 'others', 'shared') as $type) {
2674
-			if(isset($foldersNameSpace[$type])) {
2675
-				if($_subscribedOnly) {
2676
-					if( !empty($foldersNameSpace[$type]['subscribed']) ) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2673
+		foreach (array('personal', 'others', 'shared') as $type) {
2674
+			if (isset($foldersNameSpace[$type])) {
2675
+				if ($_subscribedOnly) {
2676
+					if (!empty($foldersNameSpace[$type]['subscribed'])) $listOfFolders = $foldersNameSpace[$type]['subscribed'];
2677 2677
 				} else {
2678
-					if( !empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2678
+					if (!empty($foldersNameSpace[$type]['all'])) $listOfFolders = $foldersNameSpace[$type]['all'];
2679 2679
 				}
2680
-				foreach((array)$listOfFolders as $folderName) {
2680
+				foreach ((array)$listOfFolders as $folderName) {
2681 2681
 					//echo "<br>FolderToCheck:$folderName<br>";
2682 2682
 					//error_log(__METHOD__.__LINE__.'#Delimiter:'.$delimiter.':#'.$folderName);
2683
-					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue;//when subscribedonly, we fetch all folders in one go.
2684
-					if($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all'])||in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2683
+					if ($_subscribedOnly && empty($foldersNameSpace[$type]['all'])) continue; //when subscribedonly, we fetch all folders in one go.
2684
+					if ($_subscribedOnly && !(in_array($folderName, $foldersNameSpace[$type]['all']) || in_array($folderName.$foldersNameSpace[$type]['delimiter'], $foldersNameSpace[$type]['all']))) {
2685 2685
 						#echo "$folderName failed to be here <br>";
2686 2686
 						continue;
2687 2687
 					}
2688 2688
 					if (isset($folders[$folderName])) continue;
2689 2689
 					if (isset($autoFolderObjects[$folderName])) continue;
2690
-					if (empty($delimiter)||$delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2690
+					if (empty($delimiter) || $delimiter != $foldersNameSpace[$type]['delimiter']) $delimiter = $foldersNameSpace[$type]['delimiter'];
2691 2691
 					$folderParts = explode($delimiter, $folderName);
2692 2692
 					$shortName = array_pop($folderParts);
2693 2693
 
2694 2694
 					$folderObject = new \stdClass;
2695
-					$folderObject->delimiter	= $delimiter;
2696
-					$folderObject->folderName	= $folderName;
2697
-					$folderObject->shortFolderName	= $shortName;
2698
-					if(!$_subscribedOnly) {
2695
+					$folderObject->delimiter = $delimiter;
2696
+					$folderObject->folderName = $folderName;
2697
+					$folderObject->shortFolderName = $shortName;
2698
+					if (!$_subscribedOnly) {
2699 2699
 						#echo $folderName."->".$type."<br>";
2700 2700
 						#_debug_array($foldersNameSpace[$type]['subscribed']);
2701 2701
 						$folderObject->subscribed = in_array($folderName, (array)$foldersNameSpace[$type]['subscribed']);
2702 2702
 					}
2703 2703
 
2704
-					if($_getCounters == true) {
2704
+					if ($_getCounters == true) {
2705 2705
 						//error_log(__METHOD__.' ('.__LINE__.') '.' getCounter forFolder:'.$folderName);
2706 2706
 						$folderObject->counter = $this->getMailBoxCounters($folderName);
2707 2707
 					}
2708
-					if(strtoupper($folderName) == 'INBOX') {
2708
+					if (strtoupper($folderName) == 'INBOX') {
2709 2709
 						$folderName = 'INBOX';
2710
-						$folderObject->folderName	= 'INBOX';
2711
-						$folderObject->shortFolderName	= 'INBOX';
2712
-						$folderObject->displayName	= lang('INBOX');
2710
+						$folderObject->folderName = 'INBOX';
2711
+						$folderObject->shortFolderName = 'INBOX';
2712
+						$folderObject->displayName = lang('INBOX');
2713 2713
 						$folderObject->shortDisplayName = lang('INBOX');
2714
-						$folderObject->subscribed	= true;
2714
+						$folderObject->subscribed = true;
2715 2715
 					// translate the automatic Folders (Sent, Drafts, ...) like the INBOX
2716
-					} elseif (in_array($shortName,self::$autoFolders)) {
2717
-						$tmpfolderparts = explode($delimiter,$folderObject->folderName);
2716
+					} elseif (in_array($shortName, self::$autoFolders)) {
2717
+						$tmpfolderparts = explode($delimiter, $folderObject->folderName);
2718 2718
 						array_pop($tmpfolderparts);
2719
-						$folderObject->displayName = implode($delimiter,$tmpfolderparts).$delimiter.lang($shortName);
2719
+						$folderObject->displayName = implode($delimiter, $tmpfolderparts).$delimiter.lang($shortName);
2720 2720
 						$folderObject->shortDisplayName = lang($shortName);
2721 2721
 						unset($tmpfolderparts);
2722 2722
 					} else {
@@ -2724,13 +2724,13 @@  discard block
 block discarded – undo
2724 2724
 						$folderObject->shortDisplayName = $shortName;
2725 2725
 					}
2726 2726
 					//$folderName = $folderName;
2727
-					if (in_array($shortName,self::$autoFolders)&&self::searchValueInFolderObjects($shortName,$autoFolderObjects)===false) {
2727
+					if (in_array($shortName, self::$autoFolders) && self::searchValueInFolderObjects($shortName, $autoFolderObjects) === false) {
2728 2728
 						$autoFolderObjects[$folderName] = $folderObject;
2729 2729
 					} else {
2730 2730
 						$folders[$folderName] = $folderObject;
2731 2731
 					}
2732 2732
 					//error_log(__METHOD__.' ('.__LINE__.') '.':'.$folderObject->folderName);
2733
-					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders ();
2733
+					if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders();
2734 2734
 					if (isset(self::$specialUseFolders[$folderName]))
2735 2735
 					{
2736 2736
 						$autofolder_exists[$folderName] = self::$specialUseFolders[$folderName];
@@ -2739,27 +2739,27 @@  discard block
 block discarded – undo
2739 2739
 			}
2740 2740
 		}
2741 2741
 		if (is_array($autoFolderObjects) && !empty($autoFolderObjects)) {
2742
-			uasort($autoFolderObjects,array($this,"sortByAutoFolderPos"));
2742
+			uasort($autoFolderObjects, array($this, "sortByAutoFolderPos"));
2743 2743
 		}
2744 2744
 		// check if some standard folders are missing and need to be created
2745 2745
 		if (count($autofolder_exists) < count(self::$autoFolders) && $this->check_create_autofolders($autofolder_exists))
2746 2746
 		{
2747 2747
 			// if new folders have been created, re-read folders ignoring the cache
2748
-			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false);	// false = do NOT use cache
2748
+			return $this->getFolderObjects($_subscribedOnly, $_getCounters, $_alwaysGetDefaultFolders, false); // false = do NOT use cache
2749 2749
 		}
2750
-		if (is_array($folders)) uasort($folders,array($this,"sortByDisplayName"));
2750
+		if (is_array($folders)) uasort($folders, array($this, "sortByDisplayName"));
2751 2751
 		//$folders2return = array_merge($autoFolderObjects,$folders);
2752 2752
 		//_debug_array($folders2return); #exit;
2753
-		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject,(array)$autoFolderObjects,(array)$folders);
2754
-		if (($_subscribedOnly && $_getCounters===false) ||
2755
-			($_subscribedOnly == false && $_getCounters===false &&
2753
+		$folders2return[$this->icServer->ImapServerId] = array_merge((array)$inboxFolderObject, (array)$autoFolderObjects, (array)$folders);
2754
+		if (($_subscribedOnly && $_getCounters === false) ||
2755
+			($_subscribedOnly == false && $_getCounters === false &&
2756 2756
 			isset($this->mailPreferences['showAllFoldersInFolderPane']) &&
2757
-			$this->mailPreferences['showAllFoldersInFolderPane']==1))
2757
+			$this->mailPreferences['showAllFoldersInFolderPane'] == 1))
2758 2758
 		{
2759
-			Cache::setCache(Cache::INSTANCE,'email','folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']),$folders2return,$expiration=60*60*1);
2759
+			Cache::setCache(Cache::INSTANCE, 'email', 'folderObjects'.trim($GLOBALS['egw_info']['user']['account_id']), $folders2return, $expiration = 60 * 60 * 1);
2760 2760
 		}
2761
-		Cache::setCache(Cache::INSTANCE,'email','folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderBasicInfo,$expiration=60*60*1);
2762
-		if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') ');
2761
+		Cache::setCache(Cache::INSTANCE, 'email', 'folderBasicInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderBasicInfo, $expiration = 60 * 60 * 1);
2762
+		if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') ');
2763 2763
 		return $folders2return[$this->icServer->ImapServerId];
2764 2764
 	}
2765 2765
 
@@ -2780,21 +2780,21 @@  discard block
 block discarded – undo
2780 2780
 	 *
2781 2781
 	 * @return array arrays of folders
2782 2782
 	 */
2783
-	function getFolderArrays ($_nodePath = null, $_onlyTopLevel = false, $_search= 2, $_subscribedOnly = false, $_getCounter = false)
2783
+	function getFolderArrays($_nodePath = null, $_onlyTopLevel = false, $_search = 2, $_subscribedOnly = false, $_getCounter = false)
2784 2784
 	{
2785 2785
 		// delimiter
2786 2786
 		$delimiter = $this->getHierarchyDelimiter();
2787 2787
 
2788
-		$folders = $nameSpace =  array();
2788
+		$folders = $nameSpace = array();
2789 2789
 		$nameSpaceTmp = $this->_getNameSpaces();
2790
-		foreach($nameSpaceTmp as $k => $singleNameSpace) {
2791
-			$nameSpace[$singleNameSpace['type']]=$singleNameSpace;
2790
+		foreach ($nameSpaceTmp as $k => $singleNameSpace) {
2791
+			$nameSpace[$singleNameSpace['type']] = $singleNameSpace;
2792 2792
 		}
2793 2793
 		unset($nameSpaceTmp);
2794 2794
 
2795 2795
 		//error_log(__METHOD__.__LINE__.array2string($nameSpace));
2796 2796
 		// Get special use folders
2797
-		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders (); // Set self::$specialUseFolders
2797
+		if (!isset(self::$specialUseFolders)) $this->getSpecialUseFolders(); // Set self::$specialUseFolders
2798 2798
 		// topLevelQueries generally ignore the $_search param. Except for Config::examineNamespace
2799 2799
 		if ($_onlyTopLevel) // top level leaves
2800 2800
 		{
@@ -2805,20 +2805,20 @@  discard block
 block discarded – undo
2805 2805
 			if (is_null(self::$mailConfig)) self::$mailConfig = Config::read('mail');
2806 2806
 			if (self::$mailConfig['examineNamespace'])
2807 2807
 			{
2808
-				$prefixes=array();
2808
+				$prefixes = array();
2809 2809
 				if (is_array($nameSpace))
2810 2810
 				{
2811
-					foreach($nameSpace as $k => $singleNameSpace) {
2811
+					foreach ($nameSpace as $k => $singleNameSpace) {
2812 2812
 						$type = $singleNameSpace['type'];
2813 2813
 
2814
-						if(is_array($singleNameSpace) && $singleNameSpace['prefix']){
2814
+						if (is_array($singleNameSpace) && $singleNameSpace['prefix']) {
2815 2815
 							$prefixes[$type] = $singleNameSpace['prefix'];
2816 2816
 							//regard extra care for nameSpacequeries when configured AND respect $_search
2817
-							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search==0?0:2, true);
2817
+							$result = $this->icServer->getMailboxes($singleNameSpace['prefix'], $_search == 0 ? 0 : 2, true);
2818 2818
 							if (is_array($result))
2819 2819
 							{
2820 2820
 								ksort($result);
2821
-								$topFolders = array_merge($topFolders,$result);
2821
+								$topFolders = array_merge($topFolders, $result);
2822 2822
 							}
2823 2823
 						}
2824 2824
 					}
@@ -2827,7 +2827,7 @@  discard block
 block discarded – undo
2827 2827
 
2828 2828
 			$autofolders = array();
2829 2829
 
2830
-			foreach(self::$specialUseFolders as $path => $folder)
2830
+			foreach (self::$specialUseFolders as $path => $folder)
2831 2831
 			{
2832 2832
 				if ($this->folderExists($path))
2833 2833
 				{
@@ -2835,9 +2835,9 @@  discard block
 block discarded – undo
2835 2835
 				}
2836 2836
 			}
2837 2837
 			// Check if the special use folders are there, otherwise try to create them
2838
-			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders ($autofolders))
2838
+			if (count($autofolders) < count(self::$autoFolders) && $this->check_create_autofolders($autofolders))
2839 2839
 			{
2840
-				return $this->getFolderArrays ($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2840
+				return $this->getFolderArrays($_nodePath, $_onlyTopLevel, $_search, $_subscribedOnly, $_getCounter);
2841 2841
 			}
2842 2842
 
2843 2843
 			// now process topFolders for next level
@@ -2845,13 +2845,13 @@  discard block
 block discarded – undo
2845 2845
 			{
2846 2846
 				$pattern = "/\\".$delimiter."/";
2847 2847
 				$reference = preg_replace($pattern, '', $node['MAILBOX']);
2848
-				if(!empty($prefixes))
2848
+				if (!empty($prefixes))
2849 2849
 				{
2850 2850
 					$reference = '';
2851
-					$tmpArray = explode($delimiter,$node['MAILBOX']);
2852
-					foreach($tmpArray as $p)
2851
+					$tmpArray = explode($delimiter, $node['MAILBOX']);
2852
+					foreach ($tmpArray as $p)
2853 2853
 					{
2854
-						$reference = empty($reference)?$p:$reference.$delimiter.$p;
2854
+						$reference = empty($reference) ? $p : $reference.$delimiter.$p;
2855 2855
 					}
2856 2856
 				}
2857 2857
 				$mainFolder = $subFolders = array();
@@ -2887,19 +2887,19 @@  discard block
 block discarded – undo
2887 2887
 							$nFolders [$path] = $folder;
2888 2888
 						}
2889 2889
 					}
2890
-					if (is_array($aFolders)) uasort ($aFolders, array($this,'sortByAutofolder'));
2890
+					if (is_array($aFolders)) uasort($aFolders, array($this, 'sortByAutofolder'));
2891 2891
 					//ksort($aFolders);
2892 2892
 
2893 2893
 					// Sort none auto folders base on mailbox name
2894
-					uasort($nFolders,array($this,'sortByMailbox'));
2894
+					uasort($nFolders, array($this, 'sortByMailbox'));
2895 2895
 
2896
-					$subFolders = array_merge($aFolders,$nFolders);
2896
+					$subFolders = array_merge($aFolders, $nFolders);
2897 2897
 				}
2898 2898
 				else
2899 2899
 				{
2900 2900
 					if (is_array($subFolders)) ksort($subFolders);
2901 2901
 				}
2902
-				$folders = array_merge($folders,(array)$mainFolder, (array)$subFolders);
2902
+				$folders = array_merge($folders, (array)$mainFolder, (array)$subFolders);
2903 2903
 			}
2904 2904
 		}
2905 2905
 		elseif ($_nodePath) // single node
@@ -2926,9 +2926,9 @@  discard block
 block discarded – undo
2926 2926
 				$folders = $this->icServer->getMailboxes($path, $_search, true);
2927 2927
 			}
2928 2928
 
2929
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
2929
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
2930 2930
 		}
2931
-		elseif(!$_nodePath) // all
2931
+		elseif (!$_nodePath) // all
2932 2932
 		{
2933 2933
 			if ($_subscribedOnly)
2934 2934
 			{
@@ -2944,101 +2944,101 @@  discard block
 block discarded – undo
2944 2944
 		{
2945 2945
 			// SORTING FOLDERS
2946 2946
 			//self::$debugTimes=true;
2947
-			if (self::$debugTimes) $starttime = microtime (true);
2947
+			if (self::$debugTimes) $starttime = microtime(true);
2948 2948
 			// Merge of all auto folders and specialusefolders
2949 2949
 			$autoFoldersTmp = array_unique((array_merge(self::$autoFolders, array_values(self::$specialUseFolders))));
2950
-			uasort($folders,array($this,'sortByMailbox'));//ksort($folders);
2950
+			uasort($folders, array($this, 'sortByMailbox')); //ksort($folders);
2951 2951
 			$tmpFolders = $folders;
2952
-			$inboxFolderObject=$inboxSubFolderObjects=$autoFolderObjects=$typeFolderObject=$mySpecialUseFolders=array();
2953
-			$googleMailFolderObject=$googleAutoFolderObjects=$googleSubFolderObjects=array();
2954
-			$isGoogleMail=false;
2955
-			foreach($autoFoldersTmp as $afk=>$aF)
2952
+			$inboxFolderObject = $inboxSubFolderObjects = $autoFolderObjects = $typeFolderObject = $mySpecialUseFolders = array();
2953
+			$googleMailFolderObject = $googleAutoFolderObjects = $googleSubFolderObjects = array();
2954
+			$isGoogleMail = false;
2955
+			foreach ($autoFoldersTmp as $afk=>$aF)
2956 2956
 			{
2957
-				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF]=$this->getFolderByType($aF,false);
2957
+				if (!isset($mySpecialUseFolders[$aF]) && $aF) $mySpecialUseFolders[$aF] = $this->getFolderByType($aF, false);
2958 2958
 				//error_log($afk.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
2959 2959
 			}
2960 2960
 			//error_log(array2string($mySpecialUseFolders));
2961 2961
 			foreach ($tmpFolders as $k => $f) {
2962
-				$sorted=false;
2963
-				if (strtoupper(substr($k,0,5))=='INBOX') {
2964
-					if (strtoupper($k)=='INBOX') {
2962
+				$sorted = false;
2963
+				if (strtoupper(substr($k, 0, 5)) == 'INBOX') {
2964
+					if (strtoupper($k) == 'INBOX') {
2965 2965
 						//error_log(__METHOD__.__LINE__.':'.strtoupper(substr($k,0,5)).':'.$k);
2966
-						$inboxFolderObject[$k]=$f;
2966
+						$inboxFolderObject[$k] = $f;
2967 2967
 						unset($folders[$k]);
2968
-						$sorted=true;
2968
+						$sorted = true;
2969 2969
 					} else {
2970
-						$isAutoFolder=false;
2971
-						foreach($autoFoldersTmp as $afk=>$aF)
2970
+						$isAutoFolder = false;
2971
+						foreach ($autoFoldersTmp as $afk=>$aF)
2972 2972
 						{
2973 2973
 							//error_log(__METHOD__.__LINE__.$k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
2974
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
2975
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
2976
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
2974
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
2975
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
2976
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
2977 2977
 							{
2978 2978
 								//error_log(__METHOD__.__LINE__.$k.'->'.$mySpecialUseFolders[$aF]);
2979
-								$isAutoFolder=true;
2980
-								$autoFolderObjects[$k]=$f;
2979
+								$isAutoFolder = true;
2980
+								$autoFolderObjects[$k] = $f;
2981 2981
 								break;
2982 2982
 							}
2983 2983
 						}
2984
-						if ($isAutoFolder==false) $inboxSubFolderObjects[$k]=$f;
2984
+						if ($isAutoFolder == false) $inboxSubFolderObjects[$k] = $f;
2985 2985
 						unset($folders[$k]);
2986
-						$sorted=true;
2986
+						$sorted = true;
2987 2987
 					}
2988
-				} elseif (strtoupper(substr($k,0,13))=='[GOOGLE MAIL]') {
2989
-					$isGoogleMail=true;
2990
-					if (strtoupper($k)=='[GOOGLE MAIL]') {
2991
-						$googleMailFolderObject[$k]=$f;
2988
+				} elseif (strtoupper(substr($k, 0, 13)) == '[GOOGLE MAIL]') {
2989
+					$isGoogleMail = true;
2990
+					if (strtoupper($k) == '[GOOGLE MAIL]') {
2991
+						$googleMailFolderObject[$k] = $f;
2992 2992
 						unset($folders[$k]);
2993
-						$sorted=true;
2993
+						$sorted = true;
2994 2994
 					} else {
2995
-						$isAutoFolder=false;
2996
-						foreach($autoFoldersTmp as $afk=>$aF)
2995
+						$isAutoFolder = false;
2996
+						foreach ($autoFoldersTmp as $afk=>$aF)
2997 2997
 						{
2998 2998
 							//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
2999
-							if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3000
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3001
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
2999
+							if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3000
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3001
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3002 3002
 							{
3003 3003
 								//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3004
-								$isAutoFolder=true;
3005
-								$googleAutoFolderObjects[$k]=$f;
3004
+								$isAutoFolder = true;
3005
+								$googleAutoFolderObjects[$k] = $f;
3006 3006
 								break;
3007 3007
 							}
3008 3008
 						}
3009
-						if ($isAutoFolder==false) $googleSubFolderObjects[$k]=$f;
3009
+						if ($isAutoFolder == false) $googleSubFolderObjects[$k] = $f;
3010 3010
 						unset($folders[$k]);
3011
-						$sorted=true;
3011
+						$sorted = true;
3012 3012
 					}
3013 3013
 				} else {
3014
-					$isAutoFolder=false;
3015
-					foreach($autoFoldersTmp as $afk=>$aF)
3014
+					$isAutoFolder = false;
3015
+					foreach ($autoFoldersTmp as $afk=>$aF)
3016 3016
 					{
3017 3017
 						//error_log($k.':'.$aF.'->'.$mySpecialUseFolders[$aF]);
3018
-						if($aF && strlen($mySpecialUseFolders[$aF])&&/*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3019
-								($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter|| //k may be child of an autofolder
3020
-								stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false)) // k is parent of an autofolder
3018
+						if ($aF && strlen($mySpecialUseFolders[$aF]) && /*strlen($k)>=strlen($mySpecialUseFolders[$aF])&&*/
3019
+								($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter || //k may be child of an autofolder
3020
+								stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false)) // k is parent of an autofolder
3021 3021
 						{
3022 3022
 							//error_log($k.'->'.$mySpecialUseFolders[$aF]);
3023
-							$isAutoFolder=true;
3024
-							$autoFolderObjects[$k]=$f;
3023
+							$isAutoFolder = true;
3024
+							$autoFolderObjects[$k] = $f;
3025 3025
 							unset($folders[$k]);
3026
-							$sorted=true;
3026
+							$sorted = true;
3027 3027
 							break;
3028 3028
 						}
3029 3029
 					}
3030 3030
 				}
3031 3031
 
3032
-				if ($sorted==false)
3032
+				if ($sorted == false)
3033 3033
 				{
3034
-					foreach(array('others','shared') as $type)
3034
+					foreach (array('others', 'shared') as $type)
3035 3035
 					{
3036
-						if ($nameSpace[$type]['prefix_present']&&$nameSpace[$type]['prefix'])
3036
+						if ($nameSpace[$type]['prefix_present'] && $nameSpace[$type]['prefix'])
3037 3037
 						{
3038
-							if (substr($k,0,strlen($nameSpace[$type]['prefix']))==$nameSpace[$type]['prefix']||
3039
-								substr($k,0,strlen($nameSpace[$type]['prefix'])-strlen($nameSpace[$type]['delimiter']))==substr($nameSpace[$type]['prefix'],0,strlen($nameSpace[$type]['delimiter'])*-1)) {
3038
+							if (substr($k, 0, strlen($nameSpace[$type]['prefix'])) == $nameSpace[$type]['prefix'] ||
3039
+								substr($k, 0, strlen($nameSpace[$type]['prefix']) - strlen($nameSpace[$type]['delimiter'])) == substr($nameSpace[$type]['prefix'], 0, strlen($nameSpace[$type]['delimiter']) * -1)) {
3040 3040
 								//error_log(__METHOD__.__LINE__.':'.substr($k,0,strlen($nameSpace[$type]['prefix'])).':'.$k);
3041
-								$typeFolderObject[$type][$k]=$f;
3041
+								$typeFolderObject[$type][$k] = $f;
3042 3042
 								unset($folders[$k]);
3043 3043
 							}
3044 3044
 						}
@@ -3049,40 +3049,40 @@  discard block
 block discarded – undo
3049 3049
 			// avoid calling sortByAutoFolder as it is not regarding subfolders
3050 3050
 			$autoFolderObjectsTmp = $autoFolderObjects;
3051 3051
 			unset($autoFolderObjects);
3052
-			uasort($autoFolderObjectsTmp, array($this,'sortByMailbox'));
3053
-			foreach($autoFoldersTmp as $afk=>$aF)
3052
+			uasort($autoFolderObjectsTmp, array($this, 'sortByMailbox'));
3053
+			foreach ($autoFoldersTmp as $afk=>$aF)
3054 3054
 			{
3055
-				foreach($autoFolderObjectsTmp as $k => $f)
3055
+				foreach ($autoFolderObjectsTmp as $k => $f)
3056 3056
 				{
3057
-					if($aF && ($mySpecialUseFolders[$aF]==$k ||
3058
-						substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter ||
3059
-						stristr($mySpecialUseFolders[$aF],$k.$delimiter)!==false))
3057
+					if ($aF && ($mySpecialUseFolders[$aF] == $k ||
3058
+						substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter ||
3059
+						stristr($mySpecialUseFolders[$aF], $k.$delimiter) !== false))
3060 3060
 					{
3061
-						$autoFolderObjects[$k]=$f;
3061
+						$autoFolderObjects[$k] = $f;
3062 3062
 					}
3063 3063
 				}
3064 3064
 			}
3065 3065
 			//error_log(__METHOD__.__LINE__.array2string($autoFolderObjects));
3066 3066
 			if (!$isGoogleMail) {
3067
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$inboxSubFolderObjects,(array)$folders,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3067
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$inboxSubFolderObjects, (array)$folders, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3068 3068
 			} else {
3069 3069
 				// avoid calling sortByAutoFolder as it is not regarding subfolders
3070 3070
 				$gAutoFolderObjectsTmp = $googleAutoFolderObjects;
3071 3071
 				unset($googleAutoFolderObjects);
3072
-				uasort($gAutoFolderObjectsTmp, array($this,'sortByMailbox'));
3073
-				foreach($autoFoldersTmp as $afk=>$aF)
3072
+				uasort($gAutoFolderObjectsTmp, array($this, 'sortByMailbox'));
3073
+				foreach ($autoFoldersTmp as $afk=>$aF)
3074 3074
 				{
3075
-					foreach($gAutoFolderObjectsTmp as $k => $f)
3075
+					foreach ($gAutoFolderObjectsTmp as $k => $f)
3076 3076
 					{
3077
-						if($aF && ($mySpecialUseFolders[$aF]==$k || substr($k,0,strlen($mySpecialUseFolders[$aF].$delimiter))==$mySpecialUseFolders[$aF].$delimiter))
3077
+						if ($aF && ($mySpecialUseFolders[$aF] == $k || substr($k, 0, strlen($mySpecialUseFolders[$aF].$delimiter)) == $mySpecialUseFolders[$aF].$delimiter))
3078 3078
 						{
3079
-							$googleAutoFolderObjects[$k]=$f;
3079
+							$googleAutoFolderObjects[$k] = $f;
3080 3080
 						}
3081 3081
 					}
3082 3082
 				}
3083
-				$folders = array_merge($inboxFolderObject,$autoFolderObjects,(array)$folders,(array)$googleMailFolderObject,$googleAutoFolderObjects,$googleSubFolderObjects,(array)$typeFolderObject['others'],(array)$typeFolderObject['shared']);
3083
+				$folders = array_merge($inboxFolderObject, $autoFolderObjects, (array)$folders, (array)$googleMailFolderObject, $googleAutoFolderObjects, $googleSubFolderObjects, (array)$typeFolderObject['others'], (array)$typeFolderObject['shared']);
3084 3084
 			}
3085
-			if (self::$debugTimes) self::logRunTimes($starttime,null,function_backtrace(),__METHOD__.' ('.__LINE__.') Sorting:');
3085
+			if (self::$debugTimes) self::logRunTimes($starttime, null, function_backtrace(), __METHOD__.' ('.__LINE__.') Sorting:');
3086 3086
 			//self::$debugTimes=false;
3087 3087
 		}
3088 3088
 		// Get counter information and add them to each fetched folders array
@@ -3104,10 +3104,10 @@  discard block
 block discarded – undo
3104 3104
 	 * @param array $autofolders_exists existing folders, no need to check their existance again
3105 3105
 	 * @return int number of new folders created
3106 3106
 	 */
3107
-	function check_create_autofolders(array $autofolders_exists=array())
3107
+	function check_create_autofolders(array $autofolders_exists = array())
3108 3108
 	{
3109 3109
 		$num_created = 0;
3110
-		foreach(self::$autoFolders as $folder)
3110
+		foreach (self::$autoFolders as $folder)
3111 3111
 		{
3112 3112
 			$created = false;
3113 3113
 			if (!in_array($folder, $autofolders_exists) && $this->_getSpecialUseFolder($folder, true, $created) &&
@@ -3132,7 +3132,7 @@  discard block
 block discarded – undo
3132 3132
 		$rv = false;
3133 3133
 		foreach ($haystack as $k => $v)
3134 3134
 		{
3135
-			foreach($v as &$sv) {if (trim($sv)==trim($needle)) return $k;}
3135
+			foreach ($v as &$sv) {if (trim($sv) == trim($needle)) return $k; }
3136 3136
 		}
3137 3137
 		return $rv;
3138 3138
 	}
@@ -3145,9 +3145,9 @@  discard block
 block discarded – undo
3145 3145
 	 * @param array $b array of folders
3146 3146
 	 * @return int expect values (0, 1 or -1)
3147 3147
 	 */
3148
-	function sortByMailbox($a,$b)
3148
+	function sortByMailbox($a, $b)
3149 3149
 	{
3150
-		return strcasecmp($a['MAILBOX'],$b['MAILBOX']);
3150
+		return strcasecmp($a['MAILBOX'], $b['MAILBOX']);
3151 3151
 	}
3152 3152
 
3153 3153
 	/**
@@ -3157,13 +3157,13 @@  discard block
 block discarded – undo
3157 3157
 	 * @param string $_hDelimiter hierarchy delimiter
3158 3158
 	 * @return array returns an array of data extracted from given node path
3159 3159
 	 */
3160
-	static function pathToFolderData ($_path, $_hDelimiter)
3160
+	static function pathToFolderData($_path, $_hDelimiter)
3161 3161
 	{
3162 3162
 		if (!strpos($_path, self::DELIMITER)) $_path = self::DELIMITER.$_path;
3163 3163
 		list(,$path) = explode(self::DELIMITER, $_path);
3164 3164
 		$path_chain = $parts = explode($_hDelimiter, $path);
3165 3165
 		$name = array_pop($parts);
3166
-		return array (
3166
+		return array(
3167 3167
 			'name' => $name,
3168 3168
 			'mailbox' => $path,
3169 3169
 			'parent' => implode($_hDelimiter, $parts),
@@ -3186,8 +3186,8 @@  discard block
 block discarded – undo
3186 3186
 		// 0, 1 und -1
3187 3187
 		$a = self::pathToFolderData($_a['MAILBOX'], $_a['delimiter']);
3188 3188
 		$b = self::pathToFolderData($_b['MAILBOX'], $_b['delimiter']);
3189
-		$pos1 = array_search(trim($a['name']),self::$autoFolders);
3190
-		$pos2 = array_search(trim($b['name']),self::$autoFolders);
3189
+		$pos1 = array_search(trim($a['name']), self::$autoFolders);
3190
+		$pos2 = array_search(trim($b['name']), self::$autoFolders);
3191 3191
 		if ($pos1 == $pos2) return 0;
3192 3192
 		return ($pos1 < $pos2) ? -1 : 1;
3193 3193
 	}
@@ -3200,10 +3200,10 @@  discard block
 block discarded – undo
3200 3200
 	 * @param object $b array of folderobjects
3201 3201
 	 * @return int expect values (0, 1 or -1)
3202 3202
 	 */
3203
-	function sortByDisplayName($a,$b)
3203
+	function sortByDisplayName($a, $b)
3204 3204
 	{
3205 3205
 		// 0, 1 und -1
3206
-		return strcasecmp($a->displayName,$b->displayName);
3206
+		return strcasecmp($a->displayName, $b->displayName);
3207 3207
 	}
3208 3208
 
3209 3209
 	/**
@@ -3214,11 +3214,11 @@  discard block
 block discarded – undo
3214 3214
 	 * @param object $b array of folderobjects
3215 3215
 	 * @return int expect values (0, 1 or -1)
3216 3216
 	 */
3217
-	function sortByAutoFolderPos($a,$b)
3217
+	function sortByAutoFolderPos($a, $b)
3218 3218
 	{
3219 3219
 		// 0, 1 und -1
3220
-		$pos1 = array_search(trim($a->shortFolderName),self::$autoFolders);
3221
-		$pos2 = array_search(trim($b->shortFolderName),self::$autoFolders);
3220
+		$pos1 = array_search(trim($a->shortFolderName), self::$autoFolders);
3221
+		$pos2 = array_search(trim($b->shortFolderName), self::$autoFolders);
3222 3222
 		if ($pos1 == $pos2) return 0;
3223 3223
 		return ($pos1 < $pos2) ? -1 : 1;
3224 3224
 	}
@@ -3231,7 +3231,7 @@  discard block
 block discarded – undo
3231 3231
 	 * @param boolean $_returnObject return the counters as object rather than an array
3232 3232
 	 * @return mixed false or array of counters array(MESSAGES,UNSEEN,RECENT,UIDNEXT,UIDVALIDITY) or object
3233 3233
 	 */
3234
-	function getMailBoxCounters($folderName,$_returnObject=true)
3234
+	function getMailBoxCounters($folderName, $_returnObject = true)
3235 3235
 	{
3236 3236
 		try
3237 3237
 		{
@@ -3243,9 +3243,9 @@  discard block
 block discarded – undo
3243 3243
 			if (self::$debug) error_log(__METHOD__." returned FolderStatus for Folder $folderName:".$e->getMessage());
3244 3244
 			return false;
3245 3245
 		}
3246
-		if(is_array($folderStatus)) {
3247
-			if ($_returnObject===false) return $folderStatus;
3248
-			$status =  new \stdClass;
3246
+		if (is_array($folderStatus)) {
3247
+			if ($_returnObject === false) return $folderStatus;
3248
+			$status = new \stdClass;
3249 3249
 			$status->messages   = $folderStatus['MESSAGES'];
3250 3250
 			$status->unseen     = $folderStatus['UNSEEN'];
3251 3251
 			$status->recent     = $folderStatus['RECENT'];
@@ -3267,42 +3267,42 @@  discard block
 block discarded – undo
3267 3267
 	 * @param string $reclevel 0, counter to keep track of the current recursionlevel
3268 3268
 	 * @return array of mailboxes
3269 3269
 	 */
3270
-	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel=0)
3270
+	function getMailBoxesRecursive($_mailbox, $delimiter, $prefix, $reclevel = 0)
3271 3271
 	{
3272 3272
 		#echo __METHOD__." retrieve SubFolders for $_mailbox$delimiter <br>";
3273
-		$maxreclevel=25;
3273
+		$maxreclevel = 25;
3274 3274
 		if ($reclevel > $maxreclevel) {
3275
-			error_log( __METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3275
+			error_log(__METHOD__." Recursion Level Exeeded ($reclevel) while looking up $_mailbox$delimiter ");
3276 3276
 			return array();
3277 3277
 		}
3278 3278
 		$reclevel++;
3279 3279
 		// clean up double delimiters
3280
-		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$_mailbox);
3280
+		$_mailbox = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $_mailbox);
3281 3281
 		//get that mailbox in question
3282
-		$mbx = $this->icServer->getMailboxes($_mailbox,1,true);
3282
+		$mbx = $this->icServer->getMailboxes($_mailbox, 1, true);
3283 3283
 		$mbxkeys = array_keys($mbx);
3284 3284
 		#_debug_array($mbx);
3285 3285
 //error_log(__METHOD__.' ('.__LINE__.') '.' Delimiter:'.array2string($delimiter));
3286 3286
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbx));
3287 3287
 		// Example: Array([INBOX/GaGa] => Array([MAILBOX] => INBOX/GaGa[ATTRIBUTES] => Array([0] => \\unmarked)[delimiter] => /))
3288
-		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"]))) {
3288
+		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"]))) {
3289 3289
 			// if there are children fetch them
3290 3290
 			//echo $mbx[$mbxkeys[0]]['MAILBOX']."<br>";
3291 3291
 
3292
-			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '':$delimiter),2,false);
3292
+			$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'].($mbx[$mbxkeys[0]]['MAILBOX'] == $prefix ? '' : $delimiter), 2, false);
3293 3293
 			//$buff = $this->icServer->getMailboxes($mbx[$mbxkeys[0]]['MAILBOX'],2,false);
3294 3294
 			//_debug_array($buff);
3295 3295
 			$allMailboxes = array();
3296 3296
 			foreach ($buff as $mbxname) {
3297 3297
 //error_log(__METHOD__.' ('.__LINE__.') '.array2string($mbxname));
3298
-				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter:$delimiter).'+~s',$delimiter,$mbxname['MAILBOX']);
3298
+				$mbxname = preg_replace('~'.($delimiter == '.' ? "\\".$delimiter : $delimiter).'+~s', $delimiter, $mbxname['MAILBOX']);
3299 3299
 				#echo "About to recur in level $reclevel:".$mbxname."<br>";
3300
-				if ( $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix  && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3300
+				if ($mbxname != $mbx[$mbxkeys[0]]['MAILBOX'] && $mbxname != $prefix && $mbxname != $mbx[$mbxkeys[0]]['MAILBOX'].$delimiter)
3301 3301
 				{
3302 3302
 					$allMailboxes = array_merge($allMailboxes, self::getMailBoxesRecursive($mbxname, $delimiter, $prefix, $reclevel));
3303 3303
 				}
3304 3304
 			}
3305
-			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'];
3305
+			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'];
3306 3306
 			return $allMailboxes;
3307 3307
 		} else {
3308 3308
 			return array($_mailbox);
@@ -3317,18 +3317,18 @@  discard block
 block discarded – undo
3317 3317
 	 * @param boolean& $created =null on return true: if folder was just created, false if not
3318 3318
 	 * @return mixed string or false
3319 3319
 	 */
3320
-	function _getSpecialUseFolder($_type, $_checkexistance=TRUE, &$created=null)
3320
+	function _getSpecialUseFolder($_type, $_checkexistance = TRUE, &$created = null)
3321 3321
 	{
3322 3322
 		static $types = array(
3323
-			'Drafts'   => array('profileKey'=>'acc_folder_draft','autoFolderName'=>'Drafts'),
3324
-			'Template' => array('profileKey'=>'acc_folder_template','autoFolderName'=>'Templates'),
3325
-			'Trash'    => array('profileKey'=>'acc_folder_trash','autoFolderName'=>'Trash'),
3326
-			'Sent'     => array('profileKey'=>'acc_folder_sent','autoFolderName'=>'Sent'),
3327
-			'Junk'     => array('profileKey'=>'acc_folder_junk','autoFolderName'=>'Junk'),
3328
-			'Outbox'   => array('profileKey'=>'acc_folder_outbox','autoFolderName'=>'Outbox'),
3329
-			'Archive'   => array('profileKey'=>'acc_folder_archive','autoFolderName'=>'Archive'),
3323
+			'Drafts'   => array('profileKey'=>'acc_folder_draft', 'autoFolderName'=>'Drafts'),
3324
+			'Template' => array('profileKey'=>'acc_folder_template', 'autoFolderName'=>'Templates'),
3325
+			'Trash'    => array('profileKey'=>'acc_folder_trash', 'autoFolderName'=>'Trash'),
3326
+			'Sent'     => array('profileKey'=>'acc_folder_sent', 'autoFolderName'=>'Sent'),
3327
+			'Junk'     => array('profileKey'=>'acc_folder_junk', 'autoFolderName'=>'Junk'),
3328
+			'Outbox'   => array('profileKey'=>'acc_folder_outbox', 'autoFolderName'=>'Outbox'),
3329
+			'Archive'   => array('profileKey'=>'acc_folder_archive', 'autoFolderName'=>'Archive'),
3330 3330
 		);
3331
-		if ($_type == 'Templates') $_type = 'Template';	// for some reason self::$autofolders uses 'Templates'!
3331
+		if ($_type == 'Templates') $_type = 'Template'; // for some reason self::$autofolders uses 'Templates'!
3332 3332
 		$created = false;
3333 3333
 		if (!isset($types[$_type]))
3334 3334
 		{
@@ -3350,7 +3350,7 @@  discard block
 block discarded – undo
3350 3350
 		}
3351 3351
 		// do not try to autocreate configured Archive-Folder. Return false if configured folder does not exist
3352 3352
 		if ($_type == 'Archive') {
3353
-			if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3353
+			if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3354 3354
 				return false;
3355 3355
 			} else {
3356 3356
 				return $_folderName;
@@ -3358,38 +3358,38 @@  discard block
 block discarded – undo
3358 3358
 
3359 3359
 		}
3360 3360
 		// does the folder exist??? (is configured/preset, but non-existent)
3361
-		if ($_folderName && $_checkexistance && strtolower($_folderName) !='none' && !$this->folderExists($_folderName,true)) {
3361
+		if ($_folderName && $_checkexistance && strtolower($_folderName) != 'none' && !$this->folderExists($_folderName, true)) {
3362 3362
 			try
3363 3363
 			{
3364 3364
 				$error = null;
3365 3365
 				if (($_folderName = $this->createFolder('', $_folderName, $error))) $created = true;
3366 3366
 				if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3367 3367
 			}
3368
-			catch(Exception $e)
3368
+			catch (Exception $e)
3369 3369
 			{
3370 3370
 				error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage().':'.function_backtrace());
3371 3371
 				$_folderName = false;
3372 3372
 			}
3373 3373
 		}
3374 3374
 		// not sure yet if false is the correct behavior on none
3375
-		if ($_folderName =='none') return 'none' ; //false;
3375
+		if ($_folderName == 'none') return 'none'; //false;
3376 3376
 		//no (valid) folder found yet; try specialUseFolders
3377
-		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type,self::$specialUseFolders))) $_folderName = $f;
3377
+		if (empty($_folderName) && is_array(self::$specialUseFolders) && ($f = array_search($_type, self::$specialUseFolders))) $_folderName = $f;
3378 3378
 		//no specialUseFolder; try some Defaults
3379 3379
 		if (empty($_folderName) && isset($types[$_type]))
3380 3380
 		{
3381 3381
 			$nameSpace = $this->_getNameSpaces();
3382
-			$prefix='';
3382
+			$prefix = '';
3383 3383
 			foreach ($nameSpace as $nSp)
3384 3384
 			{
3385
-				if ($nSp['type']=='personal')
3385
+				if ($nSp['type'] == 'personal')
3386 3386
 				{
3387 3387
 					//error_log(__METHOD__.__LINE__.array2string($nSp));
3388 3388
 					$prefix = $nSp['prefix'];
3389 3389
 					break;
3390 3390
 				}
3391 3391
 			}
3392
-			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'],true))
3392
+			if ($this->folderExists($prefix.$types[$_type]['autoFolderName'], true))
3393 3393
 			{
3394 3394
 				$_folderName = $prefix.$types[$_type]['autoFolderName'];
3395 3395
 			}
@@ -3398,11 +3398,11 @@  discard block
 block discarded – undo
3398 3398
 				try
3399 3399
 				{
3400 3400
 					$error = null;
3401
-					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'],$error);
3401
+					$this->createFolder('', $prefix.$types[$_type]['autoFolderName'], $error);
3402 3402
 					$_folderName = $prefix.$types[$_type]['autoFolderName'];
3403 3403
 					if ($error) error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$error);
3404 3404
 				}
3405
-				catch(Exception $e)
3405
+				catch (Exception $e)
3406 3406
 				{
3407 3407
 					error_log(__METHOD__.' ('.__LINE__.') '.' Failed to create Folder '.$_folderName." for $_type:".$e->getMessage());
3408 3408
 					$_folderName = false;
@@ -3418,7 +3418,7 @@  discard block
 block discarded – undo
3418 3418
 	 * @param boolean $_checkexistance trigger check for existance
3419 3419
 	 * @return mixed string or false
3420 3420
 	 */
3421
-	function getFolderByType($type, $_checkexistance=false)
3421
+	function getFolderByType($type, $_checkexistance = false)
3422 3422
 	{
3423 3423
 		return $this->_getSpecialUseFolder($type, $_checkexistance);
3424 3424
 	}
@@ -3428,7 +3428,7 @@  discard block
 block discarded – undo
3428 3428
 	 * @param boolean $_checkexistance trigger check for existance
3429 3429
 	 * @return mixed string or false
3430 3430
 	 */
3431
-	function getJunkFolder($_checkexistance=TRUE)
3431
+	function getJunkFolder($_checkexistance = TRUE)
3432 3432
 	{
3433 3433
 		return $this->_getSpecialUseFolder('Junk', $_checkexistance);
3434 3434
 	}
@@ -3438,7 +3438,7 @@  discard block
 block discarded – undo
3438 3438
 	 * @param boolean $_checkexistance trigger check for existance
3439 3439
 	 * @return mixed string or false
3440 3440
 	 */
3441
-	function getDraftFolder($_checkexistance=TRUE)
3441
+	function getDraftFolder($_checkexistance = TRUE)
3442 3442
 	{
3443 3443
 		return $this->_getSpecialUseFolder('Drafts', $_checkexistance);
3444 3444
 	}
@@ -3448,7 +3448,7 @@  discard block
 block discarded – undo
3448 3448
 	 * @param boolean $_checkexistance trigger check for existance
3449 3449
 	 * @return mixed string or false
3450 3450
 	 */
3451
-	function getTemplateFolder($_checkexistance=TRUE)
3451
+	function getTemplateFolder($_checkexistance = TRUE)
3452 3452
 	{
3453 3453
 		return $this->_getSpecialUseFolder('Template', $_checkexistance);
3454 3454
 	}
@@ -3458,7 +3458,7 @@  discard block
 block discarded – undo
3458 3458
 	 * @param boolean $_checkexistance trigger check for existance
3459 3459
 	 * @return mixed string or false
3460 3460
 	 */
3461
-	function getTrashFolder($_checkexistance=TRUE)
3461
+	function getTrashFolder($_checkexistance = TRUE)
3462 3462
 	{
3463 3463
 		return $this->_getSpecialUseFolder('Trash', $_checkexistance);
3464 3464
 	}
@@ -3468,7 +3468,7 @@  discard block
 block discarded – undo
3468 3468
 	 * @param boolean $_checkexistance trigger check for existance
3469 3469
 	 * @return mixed string or false
3470 3470
 	 */
3471
-	function getSentFolder($_checkexistance=TRUE)
3471
+	function getSentFolder($_checkexistance = TRUE)
3472 3472
 	{
3473 3473
 		return $this->_getSpecialUseFolder('Sent', $_checkexistance);
3474 3474
 	}
@@ -3478,7 +3478,7 @@  discard block
 block discarded – undo
3478 3478
 	 * @param boolean $_checkexistance trigger check for existance
3479 3479
 	 * @return mixed string or false
3480 3480
 	 */
3481
-	function getOutboxFolder($_checkexistance=TRUE)
3481
+	function getOutboxFolder($_checkexistance = TRUE)
3482 3482
 	{
3483 3483
 		return $this->_getSpecialUseFolder('Outbox', $_checkexistance);
3484 3484
 	}
@@ -3488,7 +3488,7 @@  discard block
 block discarded – undo
3488 3488
 	 * @param boolean $_checkexistance trigger check for existance . We do no autocreation for configured Archive folder
3489 3489
 	 * @return mixed string or false
3490 3490
 	 */
3491
-	function getArchiveFolder($_checkexistance=TRUE)
3491
+	function getArchiveFolder($_checkexistance = TRUE)
3492 3492
 	{
3493 3493
 		return $this->_getSpecialUseFolder('Archive', $_checkexistance);
3494 3494
 	}
@@ -3499,10 +3499,10 @@  discard block
 block discarded – undo
3499 3499
 	 * @param boolean $_checkexistance trigger check for existance
3500 3500
 	 * @return boolean
3501 3501
 	 */
3502
-	function isSentFolder($_folderName, $_checkexistance=TRUE)
3502
+	function isSentFolder($_folderName, $_checkexistance = TRUE)
3503 3503
 	{
3504 3504
 		$sentFolder = $this->getSentFolder($_checkexistance);
3505
-		if(empty($sentFolder)) {
3505
+		if (empty($sentFolder)) {
3506 3506
 			return false;
3507 3507
 		}
3508 3508
 		// does the folder exist???
@@ -3510,7 +3510,7 @@  discard block
 block discarded – undo
3510 3510
 			return false;
3511 3511
 		}
3512 3512
 
3513
-		if(false !== stripos($_folderName, $sentFolder)) {
3513
+		if (false !== stripos($_folderName, $sentFolder)) {
3514 3514
 			return true;
3515 3515
 		} else {
3516 3516
 			return false;
@@ -3523,15 +3523,15 @@  discard block
 block discarded – undo
3523 3523
 	 * @param boolean $_checkexistance trigger check for existance
3524 3524
 	 * @return boolean
3525 3525
 	 */
3526
-	function isOutbox($_folderName, $_checkexistance=TRUE)
3526
+	function isOutbox($_folderName, $_checkexistance = TRUE)
3527 3527
 	{
3528
-		if (stripos($_folderName, 'Outbox')===false) {
3528
+		if (stripos($_folderName, 'Outbox') === false) {
3529 3529
 			return false;
3530 3530
 		}
3531 3531
 		// does the folder exist???
3532 3532
 		if ($_checkexistance && $GLOBALS['egw_info']['user']['apps']['activesync'] && !$this->folderExists($_folderName)) {
3533 3533
 			$outboxFolder = $this->getOutboxFolder($_checkexistance);
3534
-			if(false !== stripos($_folderName, $outboxFolder)) {
3534
+			if (false !== stripos($_folderName, $outboxFolder)) {
3535 3535
 				return true;
3536 3536
 			} else {
3537 3537
 				return false;
@@ -3546,18 +3546,18 @@  discard block
 block discarded – undo
3546 3546
 	 * @param boolean $_checkexistance trigger check for existance
3547 3547
 	 * @return boolean
3548 3548
 	 */
3549
-	function isDraftFolder($_folderName, $_checkexistance=TRUE)
3549
+	function isDraftFolder($_folderName, $_checkexistance = TRUE)
3550 3550
 	{
3551 3551
 		$draftFolder = $this->getDraftFolder($_checkexistance);
3552
-		if(empty($draftFolder)) {
3552
+		if (empty($draftFolder)) {
3553 3553
 			return false;
3554 3554
 		}
3555 3555
 		// does the folder exist???
3556 3556
 		if ($_checkexistance && !$this->folderExists($_folderName)) {
3557 3557
 			return false;
3558 3558
 		}
3559
-		if (is_a($_folderName,"Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3560
-		if(false !== stripos($_folderName, $draftFolder)) {
3559
+		if (is_a($_folderName, "Horde_Imap_Client_Mailbox")) $_folderName = $_folderName->utf8;
3560
+		if (false !== stripos($_folderName, $draftFolder)) {
3561 3561
 			return true;
3562 3562
 		} else {
3563 3563
 			return false;
@@ -3570,10 +3570,10 @@  discard block
 block discarded – undo
3570 3570
 	 * @param boolean $_checkexistance trigger check for existance
3571 3571
 	 * @return boolean
3572 3572
 	 */
3573
-	function isTrashFolder($_folderName, $_checkexistance=TRUE)
3573
+	function isTrashFolder($_folderName, $_checkexistance = TRUE)
3574 3574
 	{
3575 3575
 		$trashFolder = $this->getTrashFolder($_checkexistance);
3576
-		if(empty($trashFolder)) {
3576
+		if (empty($trashFolder)) {
3577 3577
 			return false;
3578 3578
 		}
3579 3579
 		// does the folder exist???
@@ -3581,7 +3581,7 @@  discard block
 block discarded – undo
3581 3581
 			return false;
3582 3582
 		}
3583 3583
 
3584
-		if(false !== stripos($_folderName, $trashFolder)) {
3584
+		if (false !== stripos($_folderName, $trashFolder)) {
3585 3585
 			return true;
3586 3586
 		} else {
3587 3587
 			return false;
@@ -3594,10 +3594,10 @@  discard block
 block discarded – undo
3594 3594
 	 * @param boolean $_checkexistance trigger check for existance
3595 3595
 	 * @return boolean
3596 3596
 	 */
3597
-	function isTemplateFolder($_folderName, $_checkexistance=TRUE)
3597
+	function isTemplateFolder($_folderName, $_checkexistance = TRUE)
3598 3598
 	{
3599 3599
 		$templateFolder = $this->getTemplateFolder($_checkexistance);
3600
-		if(empty($templateFolder)) {
3600
+		if (empty($templateFolder)) {
3601 3601
 			return false;
3602 3602
 		}
3603 3603
 		// does the folder exist???
@@ -3605,7 +3605,7 @@  discard block
 block discarded – undo
3605 3605
 			return false;
3606 3606
 		}
3607 3607
 
3608
-		if(false !== stripos($_folderName, $templateFolder)) {
3608
+		if (false !== stripos($_folderName, $templateFolder)) {
3609 3609
 			return true;
3610 3610
 		} else {
3611 3611
 			return false;
@@ -3618,24 +3618,24 @@  discard block
 block discarded – undo
3618 3618
 	 * @param boolean $_forceCheck trigger check for existance on icServer
3619 3619
 	 * @return mixed string or false
3620 3620
 	 */
3621
-	function folderExists($_folder, $_forceCheck=false)
3621
+	function folderExists($_folder, $_forceCheck = false)
3622 3622
 	{
3623 3623
 		static $folderInfo;
3624 3624
 		$forceCheck = $_forceCheck;
3625 3625
 		if (empty($_folder))
3626 3626
 		{
3627 3627
 			// this error is more or less without significance, unless we force the check
3628
-			if ($_forceCheck===true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3628
+			if ($_forceCheck === true) error_log(__METHOD__.' ('.__LINE__.') '.' Called with empty Folder:'.$_folder.function_backtrace());
3629 3629
 			return false;
3630 3630
 		}
3631 3631
 		// when check is not enforced , we assume a folder represented as Horde_Imap_Client_Mailbox as existing folder
3632
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")&&$_forceCheck===false) return true;
3633
-		if (is_a($_folder,"Horde_Imap_Client_Mailbox")) $_folder =  $_folder->utf8;
3632
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox") && $_forceCheck === false) return true;
3633
+		if (is_a($_folder, "Horde_Imap_Client_Mailbox")) $_folder = $_folder->utf8;
3634 3634
 		// reduce traffic within the Instance per User; Expire every 5 hours
3635 3635
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Called with Folder:'.$_folder.function_backtrace());
3636
-		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),$expiration=60*60*5);
3636
+		if (is_null($folderInfo)) $folderInfo = Cache::getCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), $expiration = 60 * 60 * 5);
3637 3637
 		//error_log(__METHOD__.' ('.__LINE__.') '.'Cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID.($forceCheck?'(forcedCheck)':'').':'.array2string($folderInfo));
3638
-		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck===false)
3638
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID]) && isset($folderInfo[$this->profileID][$_folder]) && $forceCheck === false)
3639 3639
 		{
3640 3640
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Using cached Info on Folder:'.$_folder.' for Profile:'.$this->profileID);
3641 3641
 			return $folderInfo[$this->profileID][$_folder];
@@ -3651,7 +3651,7 @@  discard block
 block discarded – undo
3651 3651
 
3652 3652
 		// does the folder exist???
3653 3653
 		//error_log(__METHOD__."->Connected?".$this->icServer->_connected.", ".$_folder.", ".($forceCheck?' forceCheck activated':'dont check on server'));
3654
-		if ( $forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3654
+		if ($forceCheck || empty($folderInfo) || !isset($folderInfo[$this->profileID]) || !isset($folderInfo[$this->profileID][$_folder])) {
3655 3655
 			//error_log(__METHOD__."->NotConnected and forceCheck with profile:".$this->profileID);
3656 3656
 			//return false;
3657 3657
 			//try to connect
@@ -3667,12 +3667,12 @@  discard block
 block discarded – undo
3667 3667
 		}
3668 3668
 		//error_log(__METHOD__.' ('.__LINE__.') '.' Folder Exists:'.$folderInfo[$this->profileID][$_folder].function_backtrace());
3669 3669
 
3670
-		if(!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3670
+		if (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) &&
3671 3671
 			$folderInfo[$this->profileID][$_folder] !== true)
3672 3672
 		{
3673 3673
 			$folderInfo[$this->profileID][$_folder] = false; // set to false, whatever it was (to have a valid returnvalue for the static return)
3674 3674
 		}
3675
-		Cache::setCache(Cache::INSTANCE,'email','icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']),$folderInfo,$expiration=60*60*5);
3675
+		Cache::setCache(Cache::INSTANCE, 'email', 'icServerFolderExistsInfo'.trim($GLOBALS['egw_info']['user']['account_id']), $folderInfo, $expiration = 60 * 60 * 5);
3676 3676
 		return (!empty($folderInfo) && isset($folderInfo[$this->profileID][$_folder]) ? $folderInfo[$this->profileID][$_folder] : false);
3677 3677
 	}
3678 3678
 
@@ -3685,14 +3685,14 @@  discard block
 block discarded – undo
3685 3685
 	 */
3686 3686
 	function compressFolder($_folderName = false)
3687 3687
 	{
3688
-		$folderName	= ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3689
-		$deleteOptions	= $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3690
-		$trashFolder	= $this->getTrashFolder();
3688
+		$folderName = ($_folderName ? $_folderName : $this->sessionData['mailbox']);
3689
+		$deleteOptions = $GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions'];
3690
+		$trashFolder = $this->getTrashFolder();
3691 3691
 
3692 3692
 		$this->icServer->openMailbox($folderName);
3693 3693
 
3694
-		if(strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3695
-			$this->deleteMessages('all',$folderName,'remove_immediately');
3694
+		if (strtolower($folderName) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") {
3695
+			$this->deleteMessages('all', $folderName, 'remove_immediately');
3696 3696
 		} else {
3697 3697
 			$this->icServer->expunge($folderName);
3698 3698
 		}
@@ -3708,19 +3708,19 @@  discard block
 block discarded – undo
3708 3708
 	 * @return bool true, as we do not handle return values yet
3709 3709
 	 * @throws Exception
3710 3710
 	 */
3711
-	function deleteMessages($_messageUID, $_folder=NULL, $_forceDeleteMethod='no')
3711
+	function deleteMessages($_messageUID, $_folder = NULL, $_forceDeleteMethod = 'no')
3712 3712
 	{
3713 3713
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.array2string($_folder).', '.$_forceDeleteMethod);
3714 3714
 		$oldMailbox = '';
3715 3715
 		if (is_null($_folder) || empty($_folder)) $_folder = $this->sessionData['mailbox'];
3716 3716
 		if (empty($_messageUID))
3717 3717
 		{
3718
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
3718
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
3719 3719
 			return false;
3720 3720
 		}
3721
-		elseif ($_messageUID==='all')
3721
+		elseif ($_messageUID === 'all')
3722 3722
 		{
3723
-			$_messageUID= null;
3723
+			$_messageUID = null;
3724 3724
 		}
3725 3725
 		else
3726 3726
 		{
@@ -3729,32 +3729,32 @@  discard block
 block discarded – undo
3729 3729
 			$uidsToDelete->add($_messageUID);
3730 3730
 		}
3731 3731
 		$deleteOptions = $_forceDeleteMethod; // use forceDeleteMethod if not "no", or unknown method
3732
-		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");
3732
+		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");
3733 3733
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3734 3734
 		$trashFolder    = $this->getTrashFolder();
3735
-		$draftFolder	= $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3735
+		$draftFolder = $this->getDraftFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['draftFolder'];
3736 3736
 		$templateFolder = $this->getTemplateFolder(); //$GLOBALS['egw_info']['user']['preferences']['mail']['templateFolder'];
3737
-		if((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") ||
3737
+		if ((strtolower($_folder) == strtolower($trashFolder) && $deleteOptions == "move_to_trash") ||
3738 3738
 		   (strtolower($_folder) == strtolower($draftFolder))) {
3739 3739
 			$deleteOptions = "remove_immediately";
3740 3740
 		}
3741
-		if($this->icServer->getCurrentMailbox() != $_folder) {
3741
+		if ($this->icServer->getCurrentMailbox() != $_folder) {
3742 3742
 			$oldMailbox = $this->icServer->getCurrentMailbox();
3743 3743
 			$this->icServer->openMailbox($_folder);
3744 3744
 		}
3745 3745
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.array2string($_messageUID).','.$_folder.'/'.$this->sessionData['mailbox'].' Option:'.$deleteOptions);
3746 3746
 		$updateCache = false;
3747
-		switch($deleteOptions) {
3747
+		switch ($deleteOptions) {
3748 3748
 			case "move_to_trash":
3749 3749
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3750 3750
 				$updateCache = true;
3751
-				if(!empty($trashFolder)) {
3751
+				if (!empty($trashFolder)) {
3752 3752
 					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.implode(' : ', $_messageUID));
3753
-					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ". $this->sessionData['mailbox']);
3753
+					if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '."$trashFolder <= $_folder / ".$this->sessionData['mailbox']);
3754 3754
 					// copy messages
3755 3755
 					try
3756 3756
 					{
3757
-						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete,'move'=>true));
3757
+						$this->icServer->copy($_folder, $trashFolder, array('ids'=>$uidsToDelete, 'move'=>true));
3758 3758
 					}
3759 3759
 					catch (\Exception $e)
3760 3760
 					{
@@ -3766,18 +3766,18 @@  discard block
 block discarded – undo
3766 3766
 			case "mark_as_deleted":
3767 3767
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3768 3768
 				// mark messages as deleted
3769
-				if (is_null($_messageUID)) $_messageUID='all';
3770
-				foreach((array)$_messageUID as $key =>$uid)
3769
+				if (is_null($_messageUID)) $_messageUID = 'all';
3770
+				foreach ((array)$_messageUID as $key =>$uid)
3771 3771
 				{
3772 3772
 					//flag messages, that are flagged for deletion as seen too
3773 3773
 					$this->flagMessages('read', $uid, $_folder);
3774 3774
 					$flags = $this->getFlags($uid);
3775 3775
 					$this->flagMessages('delete', $uid, $_folder);
3776 3776
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
3777
-					if (strpos( array2string($flags),'Deleted')!==false) $undelete[] = $uid;
3777
+					if (strpos(array2string($flags), 'Deleted') !== false) $undelete[] = $uid;
3778 3778
 					unset($flags);
3779 3779
 				}
3780
-				foreach((array)$undelete as $key =>$uid)
3780
+				foreach ((array)$undelete as $key =>$uid)
3781 3781
 				{
3782 3782
 					$this->flagMessages('undelete', $uid, $_folder);
3783 3783
 				}
@@ -3786,14 +3786,14 @@  discard block
 block discarded – undo
3786 3786
 			case "remove_immediately":
3787 3787
 				//error_log(__METHOD__.' ('.__LINE__.') ');
3788 3788
 				$updateCache = true;
3789
-				if (is_null($_messageUID)) $_messageUID='all';
3789
+				if (is_null($_messageUID)) $_messageUID = 'all';
3790 3790
 				if (is_object($_messageUID))
3791 3791
 				{
3792 3792
 					$this->flagMessages('delete', $_messageUID, $_folder);
3793 3793
 				}
3794 3794
 				else
3795 3795
 				{
3796
-					foreach((array)$_messageUID as $key =>$uid)
3796
+					foreach ((array)$_messageUID as $key =>$uid)
3797 3797
 					{
3798 3798
 						//flag messages, that are flagged for deletion as seen too
3799 3799
 						$this->flagMessages('delete', $uid, $_folder);
@@ -3803,7 +3803,7 @@  discard block
 block discarded – undo
3803 3803
 				$this->icServer->expunge($_folder);
3804 3804
 				break;
3805 3805
 		}
3806
-		if($oldMailbox != '') {
3806
+		if ($oldMailbox != '') {
3807 3807
 			$this->icServer->openMailbox($oldMailbox);
3808 3808
 		}
3809 3809
 
@@ -3817,7 +3817,7 @@  discard block
 block discarded – undo
3817 3817
 	 *
3818 3818
 	 * @return null/array flags
3819 3819
 	 */
3820
-	function getFlags ($_messageUID) {
3820
+	function getFlags($_messageUID) {
3821 3821
 		try
3822 3822
 		{
3823 3823
 			$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -3830,7 +3830,7 @@  discard block
 block discarded – undo
3830 3830
 				'ids' => $uidsToFetch,
3831 3831
 			));
3832 3832
 			if (is_object($headersNew)) {
3833
-				foreach($headersNew->ids() as $id) {
3833
+				foreach ($headersNew->ids() as $id) {
3834 3834
 					$_headerObject = $headersNew->get($id);
3835 3835
 					$flags = $_headerObject->getFlags();
3836 3836
 				}
@@ -3853,22 +3853,22 @@  discard block
 block discarded – undo
3853 3853
 	 *
3854 3854
 	 * @return null/boolean
3855 3855
 	 */
3856
-	function getNotifyFlags ($_messageUID, $flags=null)
3856
+	function getNotifyFlags($_messageUID, $flags = null)
3857 3857
 	{
3858 3858
 		if (self::$debug) error_log(__METHOD__.$_messageUID.' Flags:'.array2string($flags));
3859 3859
 		try
3860 3860
 		{
3861
-			if($flags===null) $flags =  $this->getFlags($_messageUID);
3861
+			if ($flags === null) $flags = $this->getFlags($_messageUID);
3862 3862
 		}
3863 3863
 		catch (\Exception $e)
3864 3864
 		{
3865 3865
 			return null;
3866 3866
 		}
3867 3867
 
3868
-		if ( stripos( array2string($flags),'MDNSent')!==false)
3868
+		if (stripos(array2string($flags), 'MDNSent') !== false)
3869 3869
 			return true;
3870 3870
 
3871
-		if ( stripos( array2string($flags),'MDNnotSent')!==false)
3871
+		if (stripos(array2string($flags), 'MDNnotSent') !== false)
3872 3872
 			return false;
3873 3873
 
3874 3874
 		return null;
@@ -3885,45 +3885,45 @@  discard block
 block discarded – undo
3885 3885
 	 *
3886 3886
 	 * @return bool true, as we do not handle icserver->setFlags returnValue
3887 3887
 	 */
3888
-	function flagMessages($_flag, $_messageUID,$_folder=NULL)
3888
+	function flagMessages($_flag, $_messageUID, $_folder = NULL)
3889 3889
 	{
3890 3890
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",$_folder /".$this->sessionData['mailbox']);
3891 3891
 		if (empty($_messageUID))
3892 3892
 		{
3893
-			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',',$_messageUID));
3893
+			if (self::$debug) error_log(__METHOD__." no messages Message(s): ".implode(',', $_messageUID));
3894 3894
 			return false;
3895 3895
 		}
3896
-		$this->icServer->openMailbox(($_folder?$_folder:$this->sessionData['mailbox']));
3896
+		$this->icServer->openMailbox(($_folder ? $_folder : $this->sessionData['mailbox']));
3897 3897
 		$folder = $this->icServer->getCurrentMailbox();
3898
-		if (is_array($_messageUID)&& count($_messageUID)>50)
3898
+		if (is_array($_messageUID) && count($_messageUID) > 50)
3899 3899
 		{
3900
-			$count = $this->getMailBoxCounters($folder,true);
3901
-			if ($count->messages == count($_messageUID)) $_messageUID='all';
3900
+			$count = $this->getMailBoxCounters($folder, true);
3901
+			if ($count->messages == count($_messageUID)) $_messageUID = 'all';
3902 3902
 		}
3903 3903
 
3904
-		if ($_messageUID==='all')
3904
+		if ($_messageUID === 'all')
3905 3905
 		{
3906 3906
 			$messageUIDs = array('all');
3907 3907
 		}
3908 3908
 		else
3909 3909
 		{
3910 3910
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
3911
-			$messageUIDs = array_chunk($_messageUID,50,true);
3911
+			$messageUIDs = array_chunk($_messageUID, 50, true);
3912 3912
 		}
3913 3913
 		try
3914 3914
 		{
3915
-			foreach($messageUIDs as &$uids)
3915
+			foreach ($messageUIDs as &$uids)
3916 3916
 			{
3917
-				if ($uids==='all')
3917
+				if ($uids === 'all')
3918 3918
 				{
3919
-					$uidsToModify=null;
3919
+					$uidsToModify = null;
3920 3920
 				}
3921 3921
 				else
3922 3922
 				{
3923 3923
 					$uidsToModify = new Horde_Imap_Client_Ids();
3924 3924
 					$uidsToModify->add($uids);
3925 3925
 				}
3926
-				switch($_flag) {
3926
+				switch ($_flag) {
3927 3927
 					case "delete":
3928 3928
 						$ret = $this->icServer->store($folder, array('add'=>array('\\Deleted'), 'ids'=> $uidsToModify));
3929 3929
 						break;
@@ -3947,7 +3947,7 @@  discard block
 block discarded – undo
3947 3947
 						break;
3948 3948
 					case "unread":
3949 3949
 					case "unseen":
3950
-						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen','\\Answered','$Forwarded'), 'ids'=> $uidsToModify));
3950
+						$ret = $this->icServer->store($folder, array('remove'=>array('\\Seen', '\\Answered', '$Forwarded'), 'ids'=> $uidsToModify));
3951 3951
 						break;
3952 3952
 					case "mdnsent":
3953 3953
 						$ret = $this->icServer->store($folder, array('add'=>array('MDNSent'), 'ids'=> $uidsToModify));
@@ -4005,13 +4005,13 @@  discard block
 block discarded – undo
4005 4005
 				}
4006 4006
 			}
4007 4007
 		}
4008
-		catch(Exception $e)
4008
+		catch (Exception $e)
4009 4009
 		{
4010 4010
 			error_log(__METHOD__.__LINE__.' Error, could not flag messages in folder '.$folder.' Reason:'.$e->getMessage());
4011 4011
 		}
4012 4012
 		if ($folder instanceof Horde_Imap_Client_Mailbox) $_folder = $folder->utf8;
4013 4013
 		//error_log(__METHOD__.__LINE__.'#'.$this->icServer->ImapServerId.'#'.array2string($_folder).'#');
4014
-		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder)?$_folder: $this->sessionData['mailbox'])]['uidValidity'] = 0;
4014
+		self::$folderStatusCache[$this->icServer->ImapServerId][(!empty($_folder) ? $_folder : $this->sessionData['mailbox'])]['uidValidity'] = 0;
4015 4015
 
4016 4016
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->' .$_flag." ".array2string($_messageUID).",".($_folder?$_folder:$this->sessionData['mailbox']));
4017 4017
 		return true; // as we do not catch/examine setFlags returnValue
@@ -4032,19 +4032,19 @@  discard block
 block discarded – undo
4032 4032
 	 * @return mixed/bool true,false or new uid
4033 4033
 	 * @throws Exception
4034 4034
 	 */
4035
-	function moveMessages($_foldername, $_messageUID, $deleteAfterMove=true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4035
+	function moveMessages($_foldername, $_messageUID, $deleteAfterMove = true, $currentFolder = Null, $returnUIDs = false, $_sourceProfileID = Null, $_targetProfileID = Null)
4036 4036
 	{
4037
-		$source = Mail\Account::read(($_sourceProfileID?$_sourceProfileID:$this->icServer->ImapServerId))->imapServer();
4037
+		$source = Mail\Account::read(($_sourceProfileID ? $_sourceProfileID : $this->icServer->ImapServerId))->imapServer();
4038 4038
 		//$deleteOptions  = $GLOBALS['egw_info']["user"]["preferences"]["mail"]["deleteOptions"];
4039 4039
 		if (empty($_messageUID))
4040 4040
 		{
4041
-			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',',$_messageUID));
4041
+			if (self::$debug) error_log(__METHOD__." no Message(s): ".implode(',', $_messageUID));
4042 4042
 			return false;
4043 4043
 		}
4044
-		elseif ($_messageUID==='all')
4044
+		elseif ($_messageUID === 'all')
4045 4045
 		{
4046 4046
 			//error_log(__METHOD__." all Message(s): ".implode(',',$_messageUID));
4047
-			$uidsToMove= null;
4047
+			$uidsToMove = null;
4048 4048
 		}
4049 4049
 		else
4050 4050
 		{
@@ -4053,7 +4053,7 @@  discard block
 block discarded – undo
4053 4053
 			if (!(is_object($_messageUID) || is_array($_messageUID))) $_messageUID = (array)$_messageUID;
4054 4054
 			$uidsToMove->add($_messageUID);
4055 4055
 		}
4056
-		$sourceFolder = (!empty($currentFolder)?$currentFolder: $this->sessionData['mailbox']);
4056
+		$sourceFolder = (!empty($currentFolder) ? $currentFolder : $this->sessionData['mailbox']);
4057 4057
 		//error_log(__METHOD__.__LINE__."$_targetProfileID !== ".array2string($source->ImapServerId));
4058 4058
 		if (!is_null($_targetProfileID) && $_targetProfileID !== $source->ImapServerId)
4059 4059
 		{
@@ -4073,19 +4073,19 @@  discard block
 block discarded – undo
4073 4073
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' mailheaders:'.array2string($headersNew));
4074 4074
 
4075 4075
 			if (is_object($headersNew)) {
4076
-				$c=0;
4076
+				$c = 0;
4077 4077
 				$retUid = new Horde_Imap_Client_Ids();
4078 4078
 				// we copy chunks of 5 to avoid too much memory and/or server stress
4079 4079
 				// some servers seem not to allow/support the appendig of multiple messages. so we are down to one
4080
-				foreach($headersNew as &$_headerObject) {
4080
+				foreach ($headersNew as &$_headerObject) {
4081 4081
 					$c++;
4082 4082
 					$flags = $_headerObject->getFlags(); //unseen status seems to be lost when retrieving the full message
4083 4083
 					$date = $_headerObject->getImapDate();
4084
-					$currentDate =  new Horde_Imap_Client_DateTime();
4084
+					$currentDate = new Horde_Imap_Client_DateTime();
4085 4085
 					// if the internal Date of the message equals the current date; try using the header date
4086
-					if ($date==$currentDate)
4086
+					if ($date == $currentDate)
4087 4087
 					{
4088
-						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4088
+						$headerForPrio = array_change_key_case($_headerObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray(), CASE_UPPER);
4089 4089
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#'.$headerForPrio['DATE']);
4090 4090
 						$date = new Horde_Imap_Client_DateTime($headerForPrio['DATE']);
4091 4091
 						//error_log(__METHOD__.__LINE__.'#'.array2string($date).'#'.array2string($currentDate).'#');
@@ -4094,20 +4094,20 @@  discard block
 block discarded – undo
4094 4094
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($flags));
4095 4095
 					$body = $_headerObject->getFullMsg();
4096 4096
 					$dataNflags[] = array('data'=>$body, 'flags'=>$flags, 'internaldate'=>$date);
4097
-					if ($c==1)
4097
+					if ($c == 1)
4098 4098
 					{
4099 4099
 						$target = Mail\Account::read($_targetProfileID)->imapServer();
4100 4100
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Sourceserver:'.$source->ImapServerId.' TargetServer:'.$_targetProfileID.' TargetFolderObject:'.array2string($_foldername));
4101 4101
 						$foldername = $target->getMailbox($_foldername);
4102 4102
 						// make sure the target folder is open and ready
4103 4103
 						$target->openMailbox($foldername);
4104
-						$ret = $target->append($foldername,$dataNflags);
4104
+						$ret = $target->append($foldername, $dataNflags);
4105 4105
 						$retUid->add($ret);
4106 4106
 						unset($dataNflags);
4107 4107
 						// sleep 500 miliseconds; AS some sERVERs seem not to be capable of the load this is
4108 4108
 						// inflicting in them. they "reply" with an unspecific IMAP Error
4109
-						time_nanosleep(0,500000);
4110
-						$c=0;
4109
+						time_nanosleep(0, 500000);
4110
+						$c = 0;
4111 4111
 					}
4112 4112
 				}
4113 4113
 				if (isset($dataNflags))
@@ -4117,7 +4117,7 @@  discard block
 block discarded – undo
4117 4117
 					$foldername = $target->getMailbox($_foldername);
4118 4118
 					// make sure the target folder is open and ready
4119 4119
 					$target->openMailbox($foldername);
4120
-					$ret = $target->append($foldername,$dataNflags);
4120
+					$ret = $target->append($foldername, $dataNflags);
4121 4121
 					$retUid->add($ret);
4122 4122
 					unset($dataNflags);
4123 4123
 				}
@@ -4128,7 +4128,7 @@  discard block
 block discarded – undo
4128 4128
 				{
4129 4129
 					$remember = $this->icServer;
4130 4130
 					$this->icServer = $source;
4131
-					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod='remove_immediately');
4131
+					$this->deleteMessages($_messageUID, $sourceFolder, $_forceDeleteMethod = 'remove_immediately');
4132 4132
 					$this->icServer = $remember;
4133 4133
 				}
4134 4134
 			}
@@ -4137,7 +4137,7 @@  discard block
 block discarded – undo
4137 4137
 		{
4138 4138
 			try
4139 4139
 			{
4140
-				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove,'move'=>$deleteAfterMove));
4140
+				$retUid = $source->copy($sourceFolder, $_foldername, array('ids'=>$uidsToMove, 'move'=>$deleteAfterMove));
4141 4141
 			}
4142 4142
 			catch (exception $e)
4143 4143
 			{
@@ -4157,19 +4157,19 @@  discard block
 block discarded – undo
4157 4157
 	 * @param string $format ='' if none is passed, use user prefs
4158 4158
 	 * @return string returns the date as it is parseable by strtotime, or current timestamp if everything fails
4159 4159
 	 */
4160
-	static function _strtotime($_date='', $format='', $convert2usertime=false)
4160
+	static function _strtotime($_date = '', $format = '', $convert2usertime = false)
4161 4161
 	{
4162 4162
 		try {
4163
-			$date = new DateTime($_date);	// parse date & time including timezone (throws exception, if not parsable)
4164
-			if ($convert2usertime) $date->setUser();	// convert to user-time
4163
+			$date = new DateTime($_date); // parse date & time including timezone (throws exception, if not parsable)
4164
+			if ($convert2usertime) $date->setUser(); // convert to user-time
4165 4165
 			$date2return = $date->format($format);
4166 4166
 		}
4167
-		catch(\Exception $e)
4167
+		catch (\Exception $e)
4168 4168
 		{
4169
-			unset($e);	// not used
4169
+			unset($e); // not used
4170 4170
 
4171 4171
 			// remove last space-separated part and retry
4172
-			$parts = explode(' ',$_date);
4172
+			$parts = explode(' ', $_date);
4173 4173
 			if (count($parts) > 1)
4174 4174
 			{
4175 4175
 				array_pop($parts);
@@ -4190,12 +4190,12 @@  discard block
 block discarded – undo
4190 4190
 	 * @param mixed $_charset false or string -> Target charset, if false Mail displayCharset will be used
4191 4191
 	 * @return string
4192 4192
 	 */
4193
-	static function htmlentities($_string, $_charset=false)
4193
+	static function htmlentities($_string, $_charset = false)
4194 4194
 	{
4195 4195
 		//setting the charset (if not given)
4196
-		if ($_charset===false) $_charset = self::$displayCharset;
4196
+		if ($_charset === false) $_charset = self::$displayCharset;
4197 4197
 		$string = @htmlentities($_string, ENT_QUOTES, $_charset, false);
4198
-		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string,Translation::detect_encoding($_string),$_charset),ENT_QUOTES | ENT_IGNORE,$_charset, false);
4198
+		if (empty($string) && !empty($_string)) $string = @htmlentities(Translation::convert($_string, Translation::detect_encoding($_string), $_charset), ENT_QUOTES|ENT_IGNORE, $_charset, false);
4199 4199
 		return $string;
4200 4200
 	}
4201 4201
 
@@ -4212,21 +4212,21 @@  discard block
 block discarded – undo
4212 4212
 		//$_html = str_replace("\t",' ',$_html);
4213 4213
 		//error_log(__METHOD__.__LINE__.':'.$_html);
4214 4214
 		//repair doubleencoded ampersands, and some stuff htmLawed stumbles upon with balancing switched on
4215
-		$_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>'),
4216
-							 array('&amp;',    '<BR>',           '<BR>',             '<BR>',             '</font></td>','<td>',    '',         '',           '',  ''),$_html);
4215
+		$_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>'),
4216
+							 array('&amp;', '<BR>', '<BR>', '<BR>', '</font></td>', '<td>', '', '', '', ''), $_html);
4217 4217
 		//$_html = str_replace(array('&amp;amp;'),array('&amp;'),$_html);
4218
-		if (stripos($_html,'style')!==false) Mail\Html::replaceTagsCompletley($_html,'style'); // clean out empty or pagewide style definitions / left over tags
4219
-		if (stripos($_html,'head')!==false) Mail\Html::replaceTagsCompletley($_html,'head'); // Strip out stuff in head
4218
+		if (stripos($_html, 'style') !== false) Mail\Html::replaceTagsCompletley($_html, 'style'); // clean out empty or pagewide style definitions / left over tags
4219
+		if (stripos($_html, 'head') !== false) Mail\Html::replaceTagsCompletley($_html, 'head'); // Strip out stuff in head
4220 4220
 		//if (stripos($_html,'![if')!==false && stripos($_html,'<![endif]>')!==false) Mail\Html::replaceTagsCompletley($_html,'!\[if','<!\[endif\]>',false); // Strip out stuff in ifs
4221 4221
 		//if (stripos($_html,'!--[if')!==false && stripos($_html,'<![endif]-->')!==false) Mail\Html::replaceTagsCompletley($_html,'!--\[if','<!\[endif\]-->',false); // Strip out stuff in ifs
4222 4222
 		//error_log(__METHOD__.' ('.__LINE__.') '.$_html);
4223 4223
 
4224 4224
 		if (get_magic_quotes_gpc() === 1) $_html = stripslashes($_html);
4225 4225
 		// Strip out doctype in head, as htmlLawed cannot handle it TODO: Consider extracting it and adding it afterwards
4226
-		if (stripos($_html,'!doctype')!==false) Mail\Html::replaceTagsCompletley($_html,'!doctype');
4227
-		if (stripos($_html,'?xml:namespace')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml:namespace','/>',false);
4228
-		if (stripos($_html,'?xml version')!==false) Mail\Html::replaceTagsCompletley($_html,'\?xml version','\?>',false);
4229
-		if (strpos($_html,'!CURSOR')!==false) Mail\Html::replaceTagsCompletley($_html,'!CURSOR');
4226
+		if (stripos($_html, '!doctype') !== false) Mail\Html::replaceTagsCompletley($_html, '!doctype');
4227
+		if (stripos($_html, '?xml:namespace') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml:namespace', '/>', false);
4228
+		if (stripos($_html, '?xml version') !== false) Mail\Html::replaceTagsCompletley($_html, '\?xml version', '\?>', false);
4229
+		if (strpos($_html, '!CURSOR') !== false) Mail\Html::replaceTagsCompletley($_html, '!CURSOR');
4230 4230
 		// htmLawed filter only the 'body'
4231 4231
 		//preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $_html, $matches);
4232 4232
 		//if ($matches[2])
@@ -4237,16 +4237,16 @@  discard block
 block discarded – undo
4237 4237
 		// purify got switched to htmLawed
4238 4238
 		// some testcode to test purifying / htmlawed
4239 4239
 		//$_html = "<BLOCKQUOTE>hi <div> there </div> kram <br> </blockquote>".$_html;
4240
-		$_html = Html\HtmLawed::purify($_html,self::$htmLawed_config,array(),true);
4240
+		$_html = Html\HtmLawed::purify($_html, self::$htmLawed_config, array(), true);
4241 4241
 		//if ($hasOther) $_html = $matches[1]. $_html. $matches[3];
4242 4242
 		// clean out comments , should not be needed as purify should do the job.
4243 4243
 		$search = array(
4244
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
4245
-			'@<!--[\s\S]*?[ \t\n\r]*-->@',         // Strip multi-line comments including CDATA
4244
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
4245
+			'@<!--[\s\S]*?[ \t\n\r]*-->@', // Strip multi-line comments including CDATA
4246 4246
 		);
4247
-		$_html = preg_replace($search,"",$_html);
4247
+		$_html = preg_replace($search, "", $_html);
4248 4248
 		// remove non printable chars
4249
-		$_html = preg_replace('/([\000-\011])/','',$_html);
4249
+		$_html = preg_replace('/([\000-\011])/', '', $_html);
4250 4250
 		//error_log(__METHOD__.':'.__LINE__.':'.$_html);
4251 4251
 	}
4252 4252
 
@@ -4263,12 +4263,12 @@  discard block
 block discarded – undo
4263 4263
 	function getMimePartCharset($_mimePartObject)
4264 4264
 	{
4265 4265
 		//$charSet = 'iso-8859-1';//self::$displayCharset; //'iso-8859-1'; // self::displayCharset seems to be asmarter fallback than iso-8859-1
4266
-		$CharsetFound=false;
4266
+		$CharsetFound = false;
4267 4267
 		//echo "#".$_mimePartObject->encoding.'#<br>';
4268
-		if(is_array($_mimePartObject->parameters)) {
4269
-			if(isset($_mimePartObject->parameters['CHARSET'])) {
4268
+		if (is_array($_mimePartObject->parameters)) {
4269
+			if (isset($_mimePartObject->parameters['CHARSET'])) {
4270 4270
 				$charSet = $_mimePartObject->parameters['CHARSET'];
4271
-				$CharsetFound=true;
4271
+				$CharsetFound = true;
4272 4272
 			}
4273 4273
 		}
4274 4274
 		// this one is dirty, but until I find something that does the trick of detecting the encoding, ....
@@ -4287,7 +4287,7 @@  discard block
 block discarded – undo
4287 4287
 	function decodeMimePart($_mimeMessage, $_encoding, $_charset = '')
4288 4288
 	{
4289 4289
 		// decode the part
4290
-		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage,true));
4290
+		if (self::$debug) error_log(__METHOD__."() with $_encoding and $_charset:".print_r($_mimeMessage, true));
4291 4291
 		switch (strtoupper($_encoding))
4292 4292
 		{
4293 4293
 			case 'BASE64':
@@ -4327,10 +4327,10 @@  discard block
 block discarded – undo
4327 4327
 		// sometimes there are 3 parts, when there is an ics/ical attached/included-> we want to show that
4328 4328
 		// as attachment AND as abstracted ical information (we use our notification style here).
4329 4329
 		$partText = $partCalendar = $partHTML = null;
4330
-		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__,"LINE"=>__LINE__,"STRUCTURE"=>$_structure));
4330
+		if (self::$debug) _debug_array(array("METHOD"=>__METHOD__, "LINE"=>__LINE__, "STRUCTURE"=>$_structure));
4331 4331
 		//error_log(__METHOD__.' ('.__LINE__.') ');
4332 4332
 		$ignore_first_part = true;
4333
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4333
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4334 4334
 		{
4335 4335
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type"." ignoreFirstPart:".$ignore_first_part);
4336 4336
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4338,15 +4338,15 @@  discard block
 block discarded – undo
4338 4338
 			if ($ignore_first_part)
4339 4339
 			{
4340 4340
 				$ignore_first_part = false;
4341
-				continue;	// ignore multipart/alternative itself
4341
+				continue; // ignore multipart/alternative itself
4342 4342
 			}
4343 4343
 
4344 4344
 			$mimePart = $_structure->getPart($mime_id);
4345 4345
 
4346
-			switch($mimePart->getPrimaryType())
4346
+			switch ($mimePart->getPrimaryType())
4347 4347
 			{
4348 4348
 				case 'text':
4349
-					switch($mimePart->getSubType())
4349
+					switch ($mimePart->getSubType())
4350 4350
 					{
4351 4351
 						case 'plain':
4352 4352
 							if ($mimePart->getBytes() > 0) $partText = $mimePart;
@@ -4359,7 +4359,7 @@  discard block
 block discarded – undo
4359 4359
 					break;
4360 4360
 
4361 4361
 				case 'multipart':
4362
-					switch($mimePart->getSubType())
4362
+					switch ($mimePart->getSubType())
4363 4363
 					{
4364 4364
 						case 'related':
4365 4365
 						case 'mixed':
@@ -4381,13 +4381,13 @@  discard block
 block discarded – undo
4381 4381
 			}
4382 4382
 		}
4383 4383
 
4384
-		switch($_htmlMode)
4384
+		switch ($_htmlMode)
4385 4385
 		{
4386 4386
 			case 'html_only':
4387 4387
 			case 'always_display':
4388 4388
 				if ($partHTML)
4389 4389
 				{
4390
-					switch($partHTML->getSubType())
4390
+					switch ($partHTML->getSubType())
4391 4391
 					{
4392 4392
 						case 'related':
4393 4393
 							return $this->getMultipartRelated($_uid, $partHTML, $_htmlMode, $_preserveSeen);
@@ -4399,7 +4399,7 @@  discard block
 block discarded – undo
4399 4399
 							return $this->getTextPart($_uid, $partHTML, $_htmlMode, $_preserveSeen);
4400 4400
 					}
4401 4401
 				}
4402
-				elseif ($partText && $_htmlMode=='always_display')
4402
+				elseif ($partText && $_htmlMode == 'always_display')
4403 4403
 				{
4404 4404
 					return $this->getTextPart($_uid, $partText, $_htmlMode, $_preserveSeen);
4405 4405
 				}
@@ -4445,7 +4445,7 @@  discard block
 block discarded – undo
4445 4445
 	 * @param array	&$skipParts - passed by reference to have control/knowledge which parts are already fetched
4446 4446
 	 * @return array containing the desired part
4447 4447
 	 */
4448
-	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts=array())
4448
+	function getMultipartMixed($_uid, Horde_Mime_Part $_structure, $_htmlMode, $_preserveSeen = false, &$skipParts = array())
4449 4449
 	{
4450 4450
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlMode<br>";
4451 4451
 		$bodyPart = array();
@@ -4454,7 +4454,7 @@  discard block
 block discarded – undo
4454 4454
 		$ignore_first_part = true;
4455 4455
 		//$skipParts = array();
4456 4456
 		//error_log(__METHOD__.__LINE__.array2string($_structure->contentTypeMap()));
4457
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
4457
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
4458 4458
 		{
4459 4459
 			//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") $mime_id: $mime_type");
4460 4460
 			if (self::$debug) echo __METHOD__."($_uid, partID=".$_structure->getMimeId().") $mime_id: $mime_type<br>";
@@ -4462,9 +4462,9 @@  discard block
 block discarded – undo
4462 4462
 			{
4463 4463
 				$ignore_first_part = false;
4464 4464
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED FirstPart $mime_id: $mime_type");
4465
-				continue;	// ignore multipart/mixed itself
4465
+				continue; // ignore multipart/mixed itself
4466 4466
 			}
4467
-			if (array_key_exists($mime_id,$skipParts))
4467
+			if (array_key_exists($mime_id, $skipParts))
4468 4468
 			{
4469 4469
 				//error_log(__METHOD__."($_uid, ".$_structure->getMimeId().") SKIPPED $mime_id: $mime_type");
4470 4470
 				continue;
@@ -4472,11 +4472,11 @@  discard block
 block discarded – undo
4472 4472
 
4473 4473
 			$part = $_structure->getPart($mime_id);
4474 4474
 
4475
-			switch($part->getPrimaryType())
4475
+			switch ($part->getPrimaryType())
4476 4476
 			{
4477 4477
 				case 'multipart':
4478 4478
 					if ($part->getDisposition() == 'attachment') continue;
4479
-					switch($part->getSubType())
4479
+					switch ($part->getSubType())
4480 4480
 					{
4481 4481
 						case 'alternative':
4482 4482
 							return array($this->getMultipartAlternative($_uid, $part, $_htmlMode, $_preserveSeen));
@@ -4492,15 +4492,15 @@  discard block
 block discarded – undo
4492 4492
 					}
4493 4493
 					break;
4494 4494
 				case 'application':
4495
-					switch($part->getSubType())
4495
+					switch ($part->getSubType())
4496 4496
 					{
4497 4497
 						case 'pgp-encrypted':
4498
-							if (($part = $_structure->getPart($mime_id+1)) &&
4498
+							if (($part = $_structure->getPart($mime_id + 1)) &&
4499 4499
 								$part->getType() == 'application/octet-stream')
4500 4500
 							{
4501 4501
 								$this->fetchPartContents($_uid, $part);
4502
-								$skipParts[$mime_id]=$mime_type;
4503
-								$skipParts[$mime_id+1]=$part->getType();
4502
+								$skipParts[$mime_id] = $mime_type;
4503
+								$skipParts[$mime_id + 1] = $part->getType();
4504 4504
 								$bodyPart[] = array(
4505 4505
 									'body'		=> $part->getContents(array(
4506 4506
 										'stream' => false,
@@ -4514,15 +4514,15 @@  discard block
 block discarded – undo
4514 4514
 					break;
4515 4515
 
4516 4516
 				case 'text':
4517
-					switch($part->getSubType())
4517
+					switch ($part->getSubType())
4518 4518
 					{
4519 4519
 						case 'plain':
4520 4520
 						case 'html':
4521 4521
 						case 'calendar': // inline ics/ical files
4522
-							if($part->getDisposition() != 'attachment')
4522
+							if ($part->getDisposition() != 'attachment')
4523 4523
 							{
4524 4524
 								$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4525
-								$skipParts[$mime_id]=$mime_type;
4525
+								$skipParts[$mime_id] = $mime_type;
4526 4526
 							}
4527 4527
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$part->type."/".$part->subType.' -> BodyPart:'.array2string($bodyPart[count($bodyPart)-1]));
4528 4528
 							break;
@@ -4531,16 +4531,16 @@  discard block
 block discarded – undo
4531 4531
 
4532 4532
 				case 'message':
4533 4533
 					//skip attachments
4534
-					if($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4534
+					if ($part->getSubType() == 'delivery-status' && $part->getDisposition() != 'attachment')
4535 4535
 					{
4536 4536
 						$bodyPart[] = $this->getTextPart($_uid, $part, $_htmlMode, $_preserveSeen);
4537
-						$skipParts[$mime_id]=$mime_type;
4537
+						$skipParts[$mime_id] = $mime_type;
4538 4538
 					}
4539 4539
 					// do not descend into attached Messages
4540
-					if($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4540
+					if ($part->getSubType() == 'rfc822' || $part->getDisposition() == 'attachment')
4541 4541
 					{
4542 4542
 						$skipParts[$mime_id.'.0'] = $mime_type;
4543
-						foreach($part->contentTypeMap() as $sub_id => $sub_type){ $skipParts[$sub_id] = $sub_type;}
4543
+						foreach ($part->contentTypeMap() as $sub_id => $sub_type) { $skipParts[$sub_id] = $sub_type; }
4544 4544
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$_uid.' Part:'.$mime_id.':'.array2string($skipParts));
4545 4545
 						//break 2;
4546 4546
 					}
@@ -4581,13 +4581,13 @@  discard block
 block discarded – undo
4581 4581
 	 * @param boolean $_tryDecodingServerside = true; wether to try to fetch Data with BINARY instead of BODY
4582 4582
 	 * @return string|resource
4583 4583
 	 */
4584
-	function getBodyPart($_uid, $_partID=null, $_folder=null, $_preserveSeen=false, $_stream=false, &$_encoding=null, $_tryDecodingServerside=true)
4584
+	function getBodyPart($_uid, $_partID = null, $_folder = null, $_preserveSeen = false, $_stream = false, &$_encoding = null, $_tryDecodingServerside = true)
4585 4585
 	{
4586
-		if (self::$debug) error_log( __METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4586
+		if (self::$debug) error_log(__METHOD__.__LINE__."(".array2string($_uid).", $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, $_tryDecodingServerside)");
4587 4587
 
4588 4588
 		if (empty($_folder))
4589 4589
 		{
4590
-			$_folder = (isset($this->sessionData['mailbox'])&&$this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4590
+			$_folder = (isset($this->sessionData['mailbox']) && $this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
4591 4591
 		}
4592 4592
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($_folder).'/'.$this->icServer->getCurrentMailbox().'/'. $this->sessionData['mailbox']);
4593 4593
 		// querying contents of body part
@@ -4598,11 +4598,11 @@  discard block
 block discarded – undo
4598 4598
 		$fquery = new Horde_Imap_Client_Fetch_Query();
4599 4599
 		$fetchParams = array(
4600 4600
 			'peek' => $_preserveSeen,
4601
-			'decode' => true,	// try decode on server, does NOT neccessary work
4601
+			'decode' => true, // try decode on server, does NOT neccessary work
4602 4602
 		);
4603
-		if ($_tryDecodingServerside===false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4603
+		if ($_tryDecodingServerside === false)// || ($_tryDecodingServerside&&$this->isDraftFolder($_folder)))
4604 4604
 		{
4605
-			$_tryDecodingServerside=false;
4605
+			$_tryDecodingServerside = false;
4606 4606
 			$fetchParams = array(
4607 4607
 				'peek' => $_preserveSeen,
4608 4608
 			);
@@ -4622,12 +4622,12 @@  discard block
 block discarded – undo
4622 4622
 		}
4623 4623
 		// if we get an empty result, server may have trouble fetching data with UID FETCH $_uid (BINARY.PEEK[$_partID])
4624 4624
 		// thus we trigger a second go with UID FETCH $_uid (BODY.PEEK[$_partID])
4625
-		if (empty($partToReturn)&&$_tryDecodingServerside===true)
4625
+		if (empty($partToReturn) && $_tryDecodingServerside === true)
4626 4626
 		{
4627 4627
 			error_log(__METHOD__.__LINE__.' failed to fetch bodyPart in  BINARY. Try BODY');
4628 4628
 			$partToReturn = $this->getBodyPart($_uid, $_partID, $_folder, $_preserveSeen, $_stream, $_encoding, false);
4629 4629
 		}
4630
-		return ($partToReturn?$partToReturn:null);
4630
+		return ($partToReturn ? $partToReturn : null);
4631 4631
 	}
4632 4632
 
4633 4633
 	/**
@@ -4640,13 +4640,13 @@  discard block
 block discarded – undo
4640 4640
 	 * @param boolean $_stream = false true return a stream, false return string
4641 4641
 	 * @return array containing the desired text part, mimeType and charset
4642 4642
 	 */
4643
-	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode='', $_preserveSeen=false, $_stream=false)
4643
+	function getTextPart($_uid, Horde_Mime_Part $_structure, $_htmlMode = '', $_preserveSeen = false, $_stream = false)
4644 4644
 	{
4645 4645
 		//error_log(__METHOD__.' ('.__LINE__.') '.'->'.$_uid.':'.array2string($_structure).' '.function_backtrace());
4646 4646
 		$bodyPart = array();
4647
-		if (self::$debug) _debug_array(array($_structure,function_backtrace()));
4647
+		if (self::$debug) _debug_array(array($_structure, function_backtrace()));
4648 4648
 
4649
-		if($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4649
+		if ($_structure->getSubType() == 'html' && !in_array($_htmlMode, array('html_only', 'always_display', 'only_if_no_text')))
4650 4650
 		{
4651 4651
 			$bodyPart = array(
4652 4652
 				'error'		=> 1,
@@ -4692,10 +4692,10 @@  discard block
 block discarded – undo
4692 4692
 	 * @param string $_folder folder to work on
4693 4693
 	 * @return array containing the message body, mimeType and charset
4694 4694
 	 */
4695
-	function getMessageBody($_uid, $_htmlOptions='', $_partID=null, Horde_Mime_Part $_structure=null, $_preserveSeen = false, $_folder = '')
4695
+	function getMessageBody($_uid, $_htmlOptions = '', $_partID = null, Horde_Mime_Part $_structure = null, $_preserveSeen = false, $_folder = '')
4696 4696
 	{
4697 4697
 		if (self::$debug) echo __METHOD__."$_uid, $_htmlOptions, $_partID<br>";
4698
-		if($_htmlOptions != '') {
4698
+		if ($_htmlOptions != '') {
4699 4699
 			$this->htmlOptions = $_htmlOptions;
4700 4700
 		}
4701 4701
 		if (empty($_folder))
@@ -4716,7 +4716,7 @@  discard block
 block discarded – undo
4716 4716
 			return array(
4717 4717
 				array(
4718 4718
 					'error'		=> 1,
4719
-					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions". 'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4719
+					'body'		=> 'Error: Could not fetch structure on mail:'.$_uid." as $_htmlOptions".'for Mailprofile'.$this->icServer->ImapServerId.' User:'.$GLOBALS['egw_info']['user']['account_lid'],
4720 4720
 					'mimeType'	=> 'text/plain',
4721 4721
 					'charSet'	=> self::$displayCharset,
4722 4722
 				)
@@ -4729,7 +4729,7 @@  discard block
 block discarded – undo
4729 4729
 			//_debug_array($_structure->getMimeId()); exit;
4730 4730
 		}
4731 4731
 
4732
-		switch($_structure->getPrimaryType())
4732
+		switch ($_structure->getPrimaryType())
4733 4733
 		{
4734 4734
 			case 'application':
4735 4735
 				return array(
@@ -4741,7 +4741,7 @@  discard block
 block discarded – undo
4741 4741
 				);
4742 4742
 
4743 4743
 			case 'multipart':
4744
-				switch($_structure->getSubType())
4744
+				switch ($_structure->getSubType())
4745 4745
 				{
4746 4746
 					case 'alternative':
4747 4747
 						$bodyParts = array($this->getMultipartAlternative($_uid, $_structure, $this->htmlOptions, $_preserveSeen));
@@ -4775,7 +4775,7 @@  discard block
 block discarded – undo
4775 4775
 				$bodyPart = array();
4776 4776
 				if ($_structure->getDisposition() != 'attachment')
4777 4777
 				{
4778
-					switch($_structure->getSubType())
4778
+					switch ($_structure->getSubType())
4779 4779
 					{
4780 4780
 						case 'calendar':
4781 4781
 							// this is handeled in getTextPart
@@ -4791,11 +4791,11 @@  discard block
 block discarded – undo
4791 4791
 
4792 4792
 			case 'attachment':
4793 4793
 			case 'message':
4794
-				switch($_structure->getSubType())
4794
+				switch ($_structure->getSubType())
4795 4795
 				{
4796 4796
 					case 'rfc822':
4797 4797
 						$newStructure = $_structure->getParts();
4798
-						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]);}
4798
+						if (self::$debug) {echo __METHOD__." Message -> RFC -> NewStructure:"; _debug_array($newStructure[0]); }
4799 4799
 						return self::normalizeBodyParts($this->getMessageBody($_uid, $_htmlOptions, $newStructure[0]->getMimeId(), $newStructure[0], $_preserveSeen, $_folder));
4800 4800
 				}
4801 4801
 				break;
@@ -4823,11 +4823,11 @@  discard block
 block discarded – undo
4823 4823
 	{
4824 4824
 		if (is_array($_bodyParts))
4825 4825
 		{
4826
-			foreach($_bodyParts as $singleBodyPart)
4826
+			foreach ($_bodyParts as $singleBodyPart)
4827 4827
 			{
4828 4828
 				if (!isset($singleBodyPart['body'])) {
4829 4829
 					$buff = self::normalizeBodyParts($singleBodyPart);
4830
-					foreach ((array)$buff as $val) { $body2return[] = $val;}
4830
+					foreach ((array)$buff as $val) { $body2return[] = $val; }
4831 4831
 					continue;
4832 4832
 				}
4833 4833
 				$body2return[] = $singleBodyPart;
@@ -4848,14 +4848,14 @@  discard block
 block discarded – undo
4848 4848
 	 * @param boolean $useTidy  switch to use tidy
4849 4849
 	 * @return string a preformatted string with the mails converted to text
4850 4850
 	 */
4851
-	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false,  $useTidy = true)
4851
+	static function &getdisplayableBody(&$mailClass, $bodyParts, $preserveHTML = false, $useTidy = true)
4852 4852
 	{
4853
-		$message='';
4854
-		for($i=0; $i<count($bodyParts); $i++)
4853
+		$message = '';
4854
+		for ($i = 0; $i < count($bodyParts); $i++)
4855 4855
 		{
4856 4856
 			if (!isset($bodyParts[$i]['body'])) {
4857 4857
 				$bodyParts[$i]['body'] = self::getdisplayableBody($mailClass, $bodyParts[$i], $preserveHTML, $useTidy);
4858
-				$message .= empty($bodyParts[$i]['body'])?'':$bodyParts[$i]['body'];
4858
+				$message .= empty($bodyParts[$i]['body']) ? '' : $bodyParts[$i]['body'];
4859 4859
 				continue;
4860 4860
 			}
4861 4861
 			if (isset($bodyParts[$i]['error'])) continue;
@@ -4880,32 +4880,32 @@  discard block
 block discarded – undo
4880 4880
 				'(R)',
4881 4881
 			);
4882 4882
 
4883
-			if(($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
4883
+			if (($bodyParts[$i]['mimeType'] == 'text/html' || $bodyParts[$i]['mimeType'] == 'text/plain') &&
4884 4884
 				strtoupper($bodyParts[$i]['charSet']) != 'UTF-8')
4885 4885
 			{
4886
-				$bodyParts[$i]['body'] = preg_replace($sar,$rar,$bodyParts[$i]['body']);
4886
+				$bodyParts[$i]['body'] = preg_replace($sar, $rar, $bodyParts[$i]['body']);
4887 4887
 			}
4888 4888
 
4889
-			if ($bodyParts[$i]['charSet']===false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
4889
+			if ($bodyParts[$i]['charSet'] === false) $bodyParts[$i]['charSet'] = Translation::detect_encoding($bodyParts[$i]['body']);
4890 4890
 			// add line breaks to $bodyParts
4891 4891
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Charset:'.$bodyParts[$i]['charSet'].'->'.$bodyParts[$i]['body']);
4892
-			$newBody  = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
4892
+			$newBody = Translation::convert_jsonsafe($bodyParts[$i]['body'], $bodyParts[$i]['charSet']);
4893 4893
 			//error_log(__METHOD__.' ('.__LINE__.') '.' MimeType:'.$bodyParts[$i]['mimeType'].'->'.$newBody);
4894 4894
 			$mailClass->activeMimeType = 'text/plain';
4895 4895
 			if ($bodyParts[$i]['mimeType'] == 'text/html') {
4896 4896
 				$mailClass->activeMimeType = $bodyParts[$i]['mimeType'];
4897 4897
 				if (!$preserveHTML)
4898 4898
 				{
4899
-					$alreadyHtmlLawed=false;
4899
+					$alreadyHtmlLawed = false;
4900 4900
 					// as Translation::convert reduces \r\n to \n and purifier eats \n -> peplace it with a single space
4901
-					$newBody = str_replace("\n"," ",$newBody);
4901
+					$newBody = str_replace("\n", " ", $newBody);
4902 4902
 					// convert HTML to text, as we dont want HTML in infologs
4903 4903
 					if ($useTidy && extension_loaded('tidy'))
4904 4904
 					{
4905 4905
 						$tidy = new tidy();
4906
-						$cleaned = $tidy->repairString($newBody, self::$tidy_config,'utf8');
4906
+						$cleaned = $tidy->repairString($newBody, self::$tidy_config, 'utf8');
4907 4907
 						// Found errors. Strip it all so there's some output
4908
-						if($tidy->getStatus() == 2)
4908
+						if ($tidy->getStatus() == 2)
4909 4909
 						{
4910 4910
 							error_log(__METHOD__.' ('.__LINE__.') '.' ->'.$tidy->errorBuffer);
4911 4911
 						}
@@ -4916,7 +4916,7 @@  discard block
 block discarded – undo
4916 4916
 						if (!$preserveHTML)
4917 4917
 						{
4918 4918
 							// filter only the 'body', as we only want that part, if we throw away the html
4919
-							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
4919
+							preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
4920 4920
 							if ($matches[2])
4921 4921
 							{
4922 4922
 								$hasOther = true;
@@ -4927,7 +4927,7 @@  discard block
 block discarded – undo
4927 4927
 					else
4928 4928
 					{
4929 4929
 						// htmLawed filter only the 'body'
4930
-						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches=array());
4930
+						preg_match('`(<htm.+?<body[^>]*>)(.+?)(</body>.*?</html>)`ims', $newBody, $matches = array());
4931 4931
 						if ($matches[2])
4932 4932
 						{
4933 4933
 							$hasOther = true;
@@ -4936,17 +4936,17 @@  discard block
 block discarded – undo
4936 4936
 						$htmLawed = new Html\HtmLawed();
4937 4937
 						// the next line should not be needed, but produces better results on HTML 2 Text conversion,
4938 4938
 						// as we switched off HTMLaweds tidy functionality
4939
-						$newBody = str_replace(array('&amp;amp;','<DIV><BR></DIV>',"<DIV>&nbsp;</DIV>",'<div>&nbsp;</div>'),array('&amp;','<BR>','<BR>','<BR>'),$newBody);
4940
-						$newBody = $htmLawed->run($newBody,self::$htmLawed_config);
4941
-						if ($hasOther && $preserveHTML) $newBody = $matches[1]. $newBody. $matches[3];
4942
-						$alreadyHtmlLawed=true;
4939
+						$newBody = str_replace(array('&amp;amp;', '<DIV><BR></DIV>', "<DIV>&nbsp;</DIV>", '<div>&nbsp;</div>'), array('&amp;', '<BR>', '<BR>', '<BR>'), $newBody);
4940
+						$newBody = $htmLawed->run($newBody, self::$htmLawed_config);
4941
+						if ($hasOther && $preserveHTML) $newBody = $matches[1].$newBody.$matches[3];
4942
+						$alreadyHtmlLawed = true;
4943 4943
 					}
4944 4944
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after purify:'.$newBody);
4945
-					if ($preserveHTML==false) $newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,true,true);
4945
+					if ($preserveHTML == false) $newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, true, true);
4946 4946
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after convertHTMLToText:'.$newBody);
4947
-					if ($preserveHTML==false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
4947
+					if ($preserveHTML == false) $newBody = nl2br($newBody); // we need this, as htmLawed removes \r\n
4948 4948
 					/*if (!$alreadyHtmlLawed) */ $mailClass->getCleanHTML($newBody); // remove stuff we regard as unwanted
4949
-					if ($preserveHTML==false) $newBody = str_replace("<br />","\r\n",$newBody);
4949
+					if ($preserveHTML == false) $newBody = str_replace("<br />", "\r\n", $newBody);
4950 4950
 					//error_log(__METHOD__.' ('.__LINE__.') '.' after getClean:'.$newBody);
4951 4951
 				}
4952 4952
 				$message .= $newBody;
@@ -4955,9 +4955,9 @@  discard block
 block discarded – undo
4955 4955
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after specialchars):'.$newBody);
4956 4956
 			//use Mail\Html::convertHTMLToText instead of strip_tags, (even message is plain text) as strip_tags eats away too much
4957 4957
 			//$newBody = strip_tags($newBody); //we need to fix broken tags (or just stuff like "<800 USD/p" )
4958
-			$newBody = Mail\Html::convertHTMLToText($newBody,self::$displayCharset,false,false);
4958
+			$newBody = Mail\Html::convertHTMLToText($newBody, self::$displayCharset, false, false);
4959 4959
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body(after strip tags):'.$newBody);
4960
-			$newBody = htmlspecialchars_decode($newBody,ENT_QUOTES);
4960
+			$newBody = htmlspecialchars_decode($newBody, ENT_QUOTES);
4961 4961
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Body (after hmlspc_decode):'.$newBody);
4962 4962
 			$message .= $newBody;
4963 4963
 			//continue;
@@ -4965,27 +4965,27 @@  discard block
 block discarded – undo
4965 4965
 		return $message;
4966 4966
 	}
4967 4967
 
4968
-	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith=false)
4968
+	static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith = false)
4969 4969
 	{
4970 4970
 		$lines = explode("\n", $str);
4971 4971
 		$newStr = '';
4972
-		foreach($lines as $line)
4972
+		foreach ($lines as $line)
4973 4973
 		{
4974 4974
 			// replace tabs by 8 space chars, or any tab only counts one char
4975 4975
 			//$line = str_replace("\t","        ",$line);
4976 4976
 			//$newStr .= wordwrap($line, $cols, $cut);
4977
-			$allowedLength = $cols-strlen($cut);
4977
+			$allowedLength = $cols - strlen($cut);
4978 4978
 			//dont try to break lines with links, chance is we mess up the text is way too big
4979
-			if (strlen($line) > $allowedLength && stripos($line,'href=')===false &&
4980
-				($dontbreaklinesstartingwith==false ||
4979
+			if (strlen($line) > $allowedLength && stripos($line, 'href=') === false &&
4980
+				($dontbreaklinesstartingwith == false ||
4981 4981
 				 ($dontbreaklinesstartingwith &&
4982
-				  strlen($dontbreaklinesstartingwith)>=1 &&
4983
-				  substr($line,0,strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
4982
+				  strlen($dontbreaklinesstartingwith) >= 1 &&
4983
+				  substr($line, 0, strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith
4984 4984
 				 )
4985 4985
 				)
4986 4986
 			   )
4987 4987
 			{
4988
-				$s=explode(" ", $line);
4988
+				$s = explode(" ", $line);
4989 4989
 				$line = "";
4990 4990
 				$linecnt = 0;
4991 4991
 				foreach ($s as &$v) {
@@ -4993,22 +4993,22 @@  discard block
 block discarded – undo
4993 4993
 					// only break long words within the wordboundaries,
4994 4994
 					// but it may destroy links, so we check for href and dont do it if we find one
4995 4995
 					// we check for any html within the word, because we do not want to break html by accident
4996
-					if($cnt > $allowedLength && stripos($v,'href=')===false && stripos($v,'onclick=')===false && $cnt == strlen(html_entity_decode($v)))
4996
+					if ($cnt > $allowedLength && stripos($v, 'href=') === false && stripos($v, 'onclick=') === false && $cnt == strlen(html_entity_decode($v)))
4997 4997
 					{
4998
-						$v=wordwrap($v, $allowedLength, $cut, true);
4998
+						$v = wordwrap($v, $allowedLength, $cut, true);
4999 4999
 					}
5000 5000
 					// the rest should be broken at the start of the new word that exceeds the limit
5001
-					if ($linecnt+$cnt > $allowedLength) {
5002
-						$v=$cut.$v;
5001
+					if ($linecnt + $cnt > $allowedLength) {
5002
+						$v = $cut.$v;
5003 5003
 						#$linecnt = 0;
5004
-						$linecnt =strlen($v)-strlen($cut);
5004
+						$linecnt = strlen($v) - strlen($cut);
5005 5005
 					} else {
5006 5006
 						$linecnt += $cnt;
5007 5007
 					}
5008 5008
 					if (strlen($v)) $line .= (strlen($line) ? " " : "").$v;
5009 5009
 				}
5010 5010
 			}
5011
-			$newStr .= $line . "\n";
5011
+			$newStr .= $line."\n";
5012 5012
 		}
5013 5013
 		return $newStr;
5014 5014
 	}
@@ -5023,12 +5023,12 @@  discard block
 block discarded – undo
5023 5023
 	 * @param boolean $_useHeaderInsteadOfEnvelope - force getMessageHeader method to be used for fetching Envelope Information
5024 5024
 	 * @return array the message header
5025 5025
 	 */
5026
-	function getMessageEnvelope($_uid, $_partID = '',$decode=false, $_folder='', $_useHeaderInsteadOfEnvelope=false)
5026
+	function getMessageEnvelope($_uid, $_partID = '', $decode = false, $_folder = '', $_useHeaderInsteadOfEnvelope = false)
5027 5027
 	{
5028 5028
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder".function_backtrace());
5029
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5029
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5030 5030
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid,$_partID,$decode,$_folder");
5031
-		if((empty($_partID)||$_partID=='null')&&$_useHeaderInsteadOfEnvelope===false) {
5031
+		if ((empty($_partID) || $_partID == 'null') && $_useHeaderInsteadOfEnvelope === false) {
5032 5032
 			$uidsToFetch = new Horde_Imap_Client_Ids();
5033 5033
 			if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5034 5034
 			$uidsToFetch->add($_uid);
@@ -5041,7 +5041,7 @@  discard block
 block discarded – undo
5041 5041
 				'ids' => $uidsToFetch,
5042 5042
 			));
5043 5043
 			if (is_object($headersNew)) {
5044
-				foreach($headersNew as &$_headerObject) {
5044
+				foreach ($headersNew as &$_headerObject) {
5045 5045
 					$env = $_headerObject->getEnvelope();
5046 5046
 					//_debug_array($envFields->singleFields());
5047 5047
 					$singleFields = $envFields->singleFields();
@@ -5056,34 +5056,34 @@  discard block
 block discarded – undo
5056 5056
 							case 'bcc':
5057 5057
 							case 'sender':
5058 5058
 								//error_log(__METHOD__.' ('.__LINE__.') '.$v.'->'.array2string($env->$v->addresses));
5059
-								$envelope[$v]=$env->$v->addresses;
5059
+								$envelope[$v] = $env->$v->addresses;
5060 5060
 								$address = array();
5061 5061
 								if (!is_array($envelope[$v])) break;
5062 5062
 								foreach ($envelope[$v] as $k => $ad)
5063 5063
 								{
5064
-									if (stripos($ad,'@')===false)
5064
+									if (stripos($ad, '@') === false)
5065 5065
 									{
5066
-										$remember=$k;
5066
+										$remember = $k;
5067 5067
 									}
5068 5068
 									else
5069 5069
 									{
5070
-										$address[] = (!is_null($remember)?$envelope[$v][$remember].' ':'').$ad;
5071
-										$remember=null;
5070
+										$address[] = (!is_null($remember) ? $envelope[$v][$remember].' ' : '').$ad;
5071
+										$remember = null;
5072 5072
 									}
5073 5073
 								}
5074 5074
 								$envelope[$v] = $address;
5075 5075
 								break;
5076 5076
 							case 'date':
5077
-								$envelope[$v]=DateTime::to($env->$v);
5077
+								$envelope[$v] = DateTime::to($env->$v);
5078 5078
 								break;
5079 5079
 							default:
5080
-								$envelope[$v]=$env->$v;
5080
+								$envelope[$v] = $env->$v;
5081 5081
 						}
5082 5082
 					}
5083
-					$envelope['size']=$_headerObject->getSize();
5083
+					$envelope['size'] = $_headerObject->getSize();
5084 5084
 				}
5085 5085
 			}
5086
-			$envelope = array_change_key_case($envelope,CASE_UPPER);
5086
+			$envelope = array_change_key_case($envelope, CASE_UPPER);
5087 5087
 			//if ($decode) _debug_array($envelope);
5088 5088
 			//error_log(__METHOD__.' ('.__LINE__.') '.array2string($envelope));
5089 5089
 			if ($decode)
@@ -5091,19 +5091,19 @@  discard block
 block discarded – undo
5091 5091
 				foreach ($envelope as $key => $rvV)
5092 5092
 				{
5093 5093
 					//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5094
-					$envelope[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5094
+					$envelope[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5095 5095
 				}
5096 5096
 			}
5097 5097
 			return $envelope;
5098 5098
 		} else {
5099 5099
 
5100
-			$headers = $this->getMessageHeader($_uid, $_partID, true,true,$_folder);
5100
+			$headers = $this->getMessageHeader($_uid, $_partID, true, true, $_folder);
5101 5101
 
5102 5102
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($headers));
5103 5103
 			//_debug_array($headers);
5104 5104
 			$newData = array(
5105 5105
 				'DATE'		=> $headers['DATE'],
5106
-				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']):$headers['SUBJECT']),
5106
+				'SUBJECT'	=> ($decode ? self::decode_header($headers['SUBJECT']) : $headers['SUBJECT']),
5107 5107
 				'MESSAGE_ID'	=> $headers['MESSAGE-ID']
5108 5108
 			);
5109 5109
 			if (isset($headers['IN-REPLY-TO'])) $newData['IN-REPLY-TO'] = $headers['IN-REPLY-TO'];
@@ -5114,11 +5114,11 @@  discard block
 block discarded – undo
5114 5114
 			if (isset($headers['SIZE'])) $newData['SIZE'] = $headers['SIZE'];
5115 5115
 			//_debug_array($newData);
5116 5116
 			$recepientList = array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO');
5117
-			foreach($recepientList as $recepientType) {
5118
-				if(isset($headers[$recepientType])) {
5119
-					if ($decode) $headers[$recepientType] =  self::decode_header($headers[$recepientType],true);
5117
+			foreach ($recepientList as $recepientType) {
5118
+				if (isset($headers[$recepientType])) {
5119
+					if ($decode) $headers[$recepientType] = self::decode_header($headers[$recepientType], true);
5120 5120
 					//error_log(__METHOD__.__LINE__." ".$recepientType."->".array2string($headers[$recepientType]));
5121
-					foreach(self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5121
+					foreach (self::parseAddressList($headers[$recepientType]) as $singleAddress) {
5122 5122
 						$addressData = array(
5123 5123
 							'PERSONAL_NAME'		=> $singleAddress->personal ? $singleAddress->personal : 'NIL',
5124 5124
 							'AT_DOMAIN_LIST'	=> $singleAddress->adl ? $singleAddress->adl : 'NIL',
@@ -5126,15 +5126,15 @@  discard block
 block discarded – undo
5126 5126
 							'HOST_NAME'		=> $singleAddress->host ? $singleAddress->host : 'NIL',
5127 5127
 							'EMAIL'			=> $singleAddress->host ? $singleAddress->mailbox.'@'.$singleAddress->host : $singleAddress->mailbox,
5128 5128
 						);
5129
-						if($addressData['PERSONAL_NAME'] != 'NIL') {
5129
+						if ($addressData['PERSONAL_NAME'] != 'NIL') {
5130 5130
 							$addressData['RFC822_EMAIL'] = imap_rfc822_write_address($singleAddress->mailbox, $singleAddress->host, $singleAddress->personal);
5131 5131
 						} else {
5132 5132
 							$addressData['RFC822_EMAIL'] = 'NIL';
5133 5133
 						}
5134
-						$newData[$recepientType][] = ($addressData['RFC822_EMAIL']!='NIL'?$addressData['RFC822_EMAIL']:$addressData['EMAIL']);//$addressData;
5134
+						$newData[$recepientType][] = ($addressData['RFC822_EMAIL'] != 'NIL' ? $addressData['RFC822_EMAIL'] : $addressData['EMAIL']); //$addressData;
5135 5135
 					}
5136 5136
 				} else {
5137
-					if($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5137
+					if ($recepientType == 'SENDER' || $recepientType == 'REPLY-TO') {
5138 5138
 						$newData[$recepientType] = $newData['FROM'];
5139 5139
 					} else {
5140 5140
 						$newData[$recepientType] = array();
@@ -5156,10 +5156,10 @@  discard block
 block discarded – undo
5156 5156
 	 * @param string $_folder folder to work on
5157 5157
 	 * @return array|Horde_Mime_Headers message header as array or object
5158 5158
 	 */
5159
-	function getMessageHeader($_uid, $_partID = '',$decode=false, $preserveUnSeen=false, $_folder='')
5159
+	function getMessageHeader($_uid, $_partID = '', $decode = false, $preserveUnSeen = false, $_folder = '')
5160 5160
 	{
5161 5161
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.$_uid.', '.$_partID.', '.$decode.', '.$preserveUnSeen.', '.$_folder);
5162
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5162
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5163 5163
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5164 5164
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
5165 5165
 		$uidsToFetch->add($_uid);
@@ -5167,7 +5167,7 @@  discard block
 block discarded – undo
5167 5167
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5168 5168
 		if ($_partID != '')
5169 5169
 		{
5170
-			$fquery->headerText(array('id'=>$_partID,'peek'=>$preserveUnSeen));
5170
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>$preserveUnSeen));
5171 5171
 			$fquery->structure();
5172 5172
 		}
5173 5173
 		else
@@ -5180,18 +5180,18 @@  discard block
 block discarded – undo
5180 5180
 			'ids' => $uidsToFetch,
5181 5181
 		));
5182 5182
 		if (is_object($headersNew)) {
5183
-			foreach($headersNew as $_fetchObject)
5183
+			foreach ($headersNew as $_fetchObject)
5184 5184
 			{
5185
-				$headers = $_fetchObject->getHeaderText(0,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5185
+				$headers = $_fetchObject->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5186 5186
 				if ($_partID != '')
5187 5187
 				{
5188 5188
 					$mailStructureObject = $_fetchObject->getStructure();
5189 5189
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5190 5190
 					{
5191
-						if ($mime_id==$_partID)
5191
+						if ($mime_id == $_partID)
5192 5192
 						{
5193 5193
 							//error_log(__METHOD__.' ('.__LINE__.') '."$mime_id == $_partID".array2string($_headerObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->toArray()));
5194
-							$headers = $_fetchObject->getHeaderText($mime_id,Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5194
+							$headers = $_fetchObject->getHeaderText($mime_id, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
5195 5195
 							break;
5196 5196
 						}
5197 5197
 					}
@@ -5204,15 +5204,15 @@  discard block
 block discarded – undo
5204 5204
 				if (is_object($headers)) $headers->setUserAgent('EGroupware API '.$GLOBALS['egw_info']['server']['versions']['phpgwapi']);
5205 5205
 				return $headers;
5206 5206
 			}
5207
-			$retValue = is_object($headers) ? $headers->toArray():array();
5207
+			$retValue = is_object($headers) ? $headers->toArray() : array();
5208 5208
 			if ($size) $retValue['size'] = $size;
5209 5209
 		}
5210
-		$retValue = array_change_key_case($retValue,CASE_UPPER);
5210
+		$retValue = array_change_key_case($retValue, CASE_UPPER);
5211 5211
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($retValue));
5212 5212
 		// if SUBJECT is an array, use thelast one, as we assume something with the unfolding for the subject did not work
5213 5213
 		if (is_array($retValue['SUBJECT']))
5214 5214
 		{
5215
-			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT'])-1];
5215
+			$retValue['SUBJECT'] = $retValue['SUBJECT'][count($retValue['SUBJECT']) - 1];
5216 5216
 		}
5217 5217
 		//error_log(__METHOD__.' ('.__LINE__.') '.':'.array2string($decode ? self::decode_header($retValue,true):$retValue));
5218 5218
 		if ($decode)
@@ -5220,7 +5220,7 @@  discard block
 block discarded – undo
5220 5220
 			foreach ($retValue as $key => $rvV)
5221 5221
 			{
5222 5222
 				//try idn conversion only on 'FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO'
5223
-				$retValue[$key]=self::decode_header($rvV,in_array($key,array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5223
+				$retValue[$key] = self::decode_header($rvV, in_array($key, array('FROM', 'TO', 'CC', 'BCC', 'SENDER', 'REPLY-TO')));
5224 5224
 			}
5225 5225
 		}
5226 5226
 		return $retValue;
@@ -5237,14 +5237,14 @@  discard block
 block discarded – undo
5237 5237
 	function getMessageRawHeader($_uid, $_partID = '', $_folder = '')
5238 5238
 	{
5239 5239
 		static $rawHeaders;
5240
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5240
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5241 5241
 		//error_log(__METHOD__.' ('.__LINE__.') '." Try Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5242 5242
 
5243
-		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);
5244
-		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5243
+		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);
5244
+		if (isset($rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5245 5245
 		{
5246 5246
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Header $_uid, $_partID in Folder $_folder");
5247
-			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5247
+			return $rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5248 5248
 		}
5249 5249
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5250 5250
 		$uid = $_uid;
@@ -5254,7 +5254,7 @@  discard block
 block discarded – undo
5254 5254
 		$fquery = new Horde_Imap_Client_Fetch_Query();
5255 5255
 		if ($_partID != '')
5256 5256
 		{
5257
-			$fquery->headerText(array('id'=>$_partID,'peek'=>true));
5257
+			$fquery->headerText(array('id'=>$_partID, 'peek'=>true));
5258 5258
 			$fquery->structure();
5259 5259
 		}
5260 5260
 		else
@@ -5265,14 +5265,14 @@  discard block
 block discarded – undo
5265 5265
 			'ids' => $uidsToFetch,
5266 5266
 		));
5267 5267
 		if (is_object($headersNew)) {
5268
-			foreach($headersNew as &$_headerObject) {
5268
+			foreach ($headersNew as &$_headerObject) {
5269 5269
 				$retValue = $_headerObject->getHeaderText();
5270 5270
 				if ($_partID != '')
5271 5271
 				{
5272 5272
 					$mailStructureObject = $_headerObject->getStructure();
5273 5273
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5274 5274
 					{
5275
-						if ($mime_id==$_partID)
5275
+						if ($mime_id == $_partID)
5276 5276
 						{
5277 5277
 							$retValue = $_headerObject->getHeaderText($mime_id);
5278 5278
 						}
@@ -5280,8 +5280,8 @@  discard block
 block discarded – undo
5280 5280
 				}
5281 5281
 			}
5282 5282
 		}
5283
-		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]=$retValue;
5284
-		Cache::setCache(Cache::INSTANCE,'email','rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']),$rawHeaders,60*60*1);
5283
+		$rawHeaders[$this->icServer->ImapServerId][(string)$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $retValue;
5284
+		Cache::setCache(Cache::INSTANCE, 'email', 'rawHeadersCache'.trim($GLOBALS['egw_info']['user']['account_id']), $rawHeaders, 60 * 60 * 1);
5285 5285
 		return $retValue;
5286 5286
 	}
5287 5287
 
@@ -5294,25 +5294,25 @@  discard block
 block discarded – undo
5294 5294
 	{
5295 5295
 		$style = '';
5296 5296
 		if (empty($_bodyParts)) return "";
5297
-		foreach((array)$_bodyParts as $singleBodyPart) {
5297
+		foreach ((array)$_bodyParts as $singleBodyPart) {
5298 5298
 			if (!isset($singleBodyPart['body'])) {
5299 5299
 				$singleBodyPart['body'] = self::getStyles($singleBodyPart);
5300 5300
 				$style .= $singleBodyPart['body'];
5301 5301
 				continue;
5302 5302
 			}
5303 5303
 
5304
-			if ($singleBodyPart['charSet']===false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5304
+			if ($singleBodyPart['charSet'] === false) $singleBodyPart['charSet'] = Translation::detect_encoding($singleBodyPart['body']);
5305 5305
 			$singleBodyPart['body'] = Translation::convert(
5306 5306
 				$singleBodyPart['body'],
5307 5307
 				strtolower($singleBodyPart['charSet'])
5308 5308
 			);
5309 5309
 			$ct = 0;
5310
-			$newStyle=array();
5311
-			if (stripos($singleBodyPart['body'],'<style')!==false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5312
-			if ($ct>0)
5310
+			$newStyle = array();
5311
+			if (stripos($singleBodyPart['body'], '<style') !== false)  $ct = preg_match_all('#<style(?:\s.*)?>(.+)</style>#isU', $singleBodyPart['body'], $newStyle);
5312
+			if ($ct > 0)
5313 5313
 			{
5314 5314
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$ct.'#'.array2string($newStyle));
5315
-				$style2buffer = implode('',$newStyle[0]);
5315
+				$style2buffer = implode('', $newStyle[0]);
5316 5316
 			}
5317 5317
 			if ($style2buffer && strtoupper(self::$displayCharset) == 'UTF-8')
5318 5318
 			{
@@ -5320,7 +5320,7 @@  discard block
 block discarded – undo
5320 5320
 				$test = json_encode($style2buffer);
5321 5321
 				//error_log(__METHOD__.' ('.__LINE__.') '.'#'.$test.'# ->'.strlen($style2buffer).' Error:'.json_last_error());
5322 5322
 				//if (json_last_error() != JSON_ERROR_NONE && strlen($style2buffer)>0)
5323
-				if ($test=="null" && strlen($style2buffer)>0)
5323
+				if ($test == "null" && strlen($style2buffer) > 0)
5324 5324
 				{
5325 5325
 					// this should not be needed, unless something fails with charset detection/ wrong charset passed
5326 5326
 					error_log(__METHOD__.' ('.__LINE__.') '.' Found Invalid sequence for utf-8 in CSS:'.$style2buffer.' Charset Reported:'.$singleBodyPart['charSet'].' Carset Detected:'.Translation::detect_encoding($style2buffer));
@@ -5331,19 +5331,19 @@  discard block
 block discarded – undo
5331 5331
 		}
5332 5332
 		// clean out comments and stuff
5333 5333
 		$search = array(
5334
-			'@url\(http:\/\/[^\)].*?\)@si',  // url calls e.g. in style definitions
5334
+			'@url\(http:\/\/[^\)].*?\)@si', // url calls e.g. in style definitions
5335 5335
 //			'@<!--[\s\S]*?[ \t\n\r]*-->@',   // Strip multi-line comments including CDATA
5336 5336
 //			'@<!--[\s\S]*?[ \t\n\r]*--@',    // Strip broken multi-line comments including CDATA
5337 5337
 		);
5338
-		$style = preg_replace($search,"",$style);
5338
+		$style = preg_replace($search, "", $style);
5339 5339
 
5340 5340
 		// CSS Security
5341 5341
 		// http://code.google.com/p/browsersec/wiki/Part1#Cascading_stylesheets
5342
-		$css = preg_replace('/(javascript|expression|-moz-binding)/i','',$style);
5343
-		if (stripos($css,'script')!==false) Mail\Html::replaceTagsCompletley($css,'script'); // Strip out script that may be included
5342
+		$css = preg_replace('/(javascript|expression|-moz-binding)/i', '', $style);
5343
+		if (stripos($css, 'script') !== false) Mail\Html::replaceTagsCompletley($css, 'script'); // Strip out script that may be included
5344 5344
 		// 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
5345 5345
 		// as the comments as <!-- styledefinition --> in stylesheet are outdated, and ck-editor does not understand it, we remove it
5346
-		$css = str_replace(array(':','<!--','-->'),array(': ','',''),$css);
5346
+		$css = str_replace(array(':', '<!--', '-->'), array(': ', '', ''), $css);
5347 5347
 		//error_log(__METHOD__.' ('.__LINE__.') '.$css);
5348 5348
 		// TODO: we may have to strip urls and maybe comments and ifs
5349 5349
 		return $css;
@@ -5357,16 +5357,16 @@  discard block
 block discarded – undo
5357 5357
 	 * @param string $_folder folder to work on
5358 5358
 	 * @return string the message body
5359 5359
 	 */
5360
-	function getMessageRawBody($_uid, $_partID = '', $_folder='')
5360
+	function getMessageRawBody($_uid, $_partID = '', $_folder = '')
5361 5361
 	{
5362 5362
 		//TODO: caching einbauen static!
5363 5363
 		static $rawBody;
5364 5364
 		if (is_null($rawBody)) $rawBody = array();
5365
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5366
-		if (isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)]))
5365
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5366
+		if (isset($rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)]))
5367 5367
 		{
5368 5368
 			//error_log(__METHOD__.' ('.__LINE__.') '." Using Cache for raw Body $_uid, $_partID in Folder $_folder");
5369
-			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)];
5369
+			return $rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)];
5370 5370
 		}
5371 5371
 
5372 5372
 		$uidsToFetch = new Horde_Imap_Client_Ids();
@@ -5379,13 +5379,13 @@  discard block
 block discarded – undo
5379 5379
 		if ($_partID != '')
5380 5380
 		{
5381 5381
 			$fquery->structure();
5382
-			$fquery->bodyPart($_partID,array('peek'=>true));
5382
+			$fquery->bodyPart($_partID, array('peek'=>true));
5383 5383
 		}
5384 5384
 		$headersNew = $this->icServer->fetch($_folder, $fquery, array(
5385 5385
 			'ids' => $uidsToFetch,
5386 5386
 		));
5387 5387
 		if (is_object($headersNew)) {
5388
-			foreach($headersNew as &$_headerObject) {
5388
+			foreach ($headersNew as &$_headerObject) {
5389 5389
 				$body = $_headerObject->getFullMsg();
5390 5390
 				if ($_partID != '')
5391 5391
 				{
@@ -5393,7 +5393,7 @@  discard block
 block discarded – undo
5393 5393
 					//_debug_array($mailStructureObject->contentTypeMap());
5394 5394
 					foreach ($mailStructureObject->contentTypeMap() as $mime_id => $mime_type)
5395 5395
 					{
5396
-						if ($mime_id==$_partID)
5396
+						if ($mime_id == $_partID)
5397 5397
 						{
5398 5398
 							$body = $_headerObject->getBodyPart($mime_id);
5399 5399
 						}
@@ -5402,7 +5402,7 @@  discard block
 block discarded – undo
5402 5402
 			}
5403 5403
 		}
5404 5404
 		//error_log(__METHOD__.' ('.__LINE__.') '."[$this->icServer->ImapServerId][$_folder][$_uid][".(empty($_partID)?'NIL':$_partID)."]");
5405
-		$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID)?'NIL':$_partID)] = $body;
5405
+		$rawBody[$this->icServer->ImapServerId][$_folder][$_uid][(empty($_partID) ? 'NIL' : $_partID)] = $body;
5406 5406
 		return $body;
5407 5407
 	}
5408 5408
 
@@ -5416,13 +5416,13 @@  discard block
 block discarded – undo
5416 5416
 	 * @param Horde_Imap_Client_Fetch_Query $fquery=null default query just structure
5417 5417
 	 * @return Horde_Mime_Part
5418 5418
 	 */
5419
-	function getStructure($_uid, $_partID=null, $_folder=null, $_preserveSeen=false)
5419
+	function getStructure($_uid, $_partID = null, $_folder = null, $_preserveSeen = false)
5420 5420
 	{
5421
-		if (self::$debug) error_log( __METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5421
+		if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_partID");
5422 5422
 
5423 5423
 		if (empty($_folder))
5424 5424
 		{
5425
-			$_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5425
+			$_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5426 5426
 		}
5427 5427
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5428 5428
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
@@ -5440,7 +5440,7 @@  discard block
 block discarded – undo
5440 5440
 				'ids' => $uidsToFetch,
5441 5441
 			))->first();
5442 5442
 
5443
-			return is_object($mail)?$mail->getStructure():null;
5443
+			return is_object($mail) ? $mail->getStructure() : null;
5444 5444
 		}
5445 5445
 		catch (\Exception $e)
5446 5446
 		{
@@ -5463,14 +5463,14 @@  discard block
 block discarded – undo
5463 5463
 	 * @param string $_folder folder to work on
5464 5464
 	 * @return array  an array of information about the attachment: array of array(name, size, mimeType, partID, encoding)
5465 5465
 	 */
5466
-	function getMessageAttachments($_uid, $_partID=null, Horde_Mime_Part $_structure=null, $fetchEmbeddedImages=true, $fetchTextCalendar=false, $resolveTNEF=true, $_folder='')
5466
+	function getMessageAttachments($_uid, $_partID = null, Horde_Mime_Part $_structure = null, $fetchEmbeddedImages = true, $fetchTextCalendar = false, $resolveTNEF = true, $_folder = '')
5467 5467
 	{
5468
-		if (self::$debug) error_log( __METHOD__.":$_uid, $_partID");
5469
-		if (empty($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5468
+		if (self::$debug) error_log(__METHOD__.":$_uid, $_partID");
5469
+		if (empty($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5470 5470
 		$attachments = array();
5471 5471
 		if (!isset($_structure))
5472 5472
 		{
5473
-			$_structure = $this->getStructure($_uid, $_partID,$_folder,true);
5473
+			$_structure = $this->getStructure($_uid, $_partID, $_folder, true);
5474 5474
 			//error_log(__METHOD__.' ('.__LINE__.') '.':'.print_r($_structure->contentTypeMap(),true));
5475 5475
 		}
5476 5476
 		if (!$_structure || !$_structure->contentTypeMap()) return array();
@@ -5478,7 +5478,7 @@  discard block
 block discarded – undo
5478 5478
 		$skipParts = array();
5479 5479
 		$tnefParts = array();
5480 5480
 		$skip = 0;
5481
-		foreach($_structure->contentTypeMap() as $mime_id => $mime_type)
5481
+		foreach ($_structure->contentTypeMap() as $mime_id => $mime_type)
5482 5482
 		{
5483 5483
 			// skip multipart/encrypted incl. its two sub-parts, as we show 2. sub-part as body to be decrypted client-side
5484 5484
 			if ($mime_type == 'multipart/encrypted')
@@ -5486,7 +5486,7 @@  discard block
 block discarded – undo
5486 5486
 				$skip = 2;
5487 5487
 				continue;
5488 5488
 			}
5489
-			elseif($skip)
5489
+			elseif ($skip)
5490 5490
 			{
5491 5491
 				$skip--;
5492 5492
 				continue;
@@ -5500,10 +5500,10 @@  discard block
 block discarded – undo
5500 5500
 			$partPrimaryType = $part->getPrimaryType();
5501 5501
 			// we only want to retrieve the attachments of the current mail, not those of possible
5502 5502
 			// attached mails
5503
-			if ($mime_type=='message/rfc822' && $_partID!=$mime_id)
5503
+			if ($mime_type == 'message/rfc822' && $_partID != $mime_id)
5504 5504
 			{
5505 5505
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.'->'.$mime_id.':'.array2string($part->contentTypeMap()));
5506
-				foreach($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type;}
5506
+				foreach ($part->contentTypeMap() as $sub_id => $sub_type) {if ($sub_id != $mime_id) $skipParts[$sub_id] = $sub_type; }
5507 5507
 			}
5508 5508
 			if (empty($partDisposition) && $partPrimaryType != 'multipart' && $partPrimaryType != 'text')
5509 5509
 			{
@@ -5511,27 +5511,27 @@  discard block
 block discarded – undo
5511 5511
 				// attachment with no link to show the attachment inline.
5512 5512
 				// Considering this: we "list" everything that matches the above criteria
5513 5513
 				// as attachment in order to not loose/miss information on our data
5514
-				$partDisposition='attachment';
5514
+				$partDisposition = 'attachment';
5515 5515
 			}
5516 5516
 			//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($skipParts));
5517
-			if (array_key_exists($mime_id,$skipParts)) continue;
5517
+			if (array_key_exists($mime_id, $skipParts)) continue;
5518 5518
 
5519 5519
 			if ($partDisposition == 'attachment' ||
5520
-				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId()=='') ||
5520
+				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image' && $part->getContentId() == '') ||
5521 5521
 				(($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType != 'image' && $partPrimaryType != 'text' && $partPrimaryType != 'multipart') ||
5522
-				($mime_type=='image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5522
+				($mime_type == 'image/tiff') || //always fetch. even if $fetchEmbeddedImages is false. as we cannot display tiffs
5523 5523
 				($fetchEmbeddedImages && ($partDisposition == 'inline' || empty($partDisposition)) && $partPrimaryType == 'image') ||
5524 5524
 				($fetchTextCalendar && $partPrimaryType == 'text' && $part->getSubType() == 'calendar'))
5525 5525
 			{
5526 5526
 				// if type is message/rfc822 and _partID is given, and MimeID equals partID
5527 5527
 				// we attempt to fetch "ourselves"
5528
-				if ($_partID==$part->getMimeId() && $part->getPrimaryType()=='message') continue;
5528
+				if ($_partID == $part->getMimeId() && $part->getPrimaryType() == 'message') continue;
5529 5529
 				$attachment = $part->getAllDispositionParameters();
5530 5530
 				$attachment['disposition'] = $part->getDisposition();
5531 5531
 				$attachment['mimeType'] = $mime_type;
5532 5532
 				$attachment['uid'] = $_uid;
5533 5533
 				$attachment['partID'] = $mime_id;
5534
-				if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5534
+				if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5535 5535
 				if ($fetchTextCalendar)
5536 5536
 				{
5537 5537
 					//error_log(__METHOD__.' ('.__LINE__.') '.array2string($part->getAllContentTypeParameters()));
@@ -5541,11 +5541,11 @@  discard block
 block discarded – undo
5541 5541
 				}
5542 5542
 				$attachment['size'] = $part->getBytes();
5543 5543
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5544
-				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);
5544
+				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);
5545 5545
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Uid:'.$uid.' Part:'.$_partID.'->'.$mime_id.':'.array2string($attachment));
5546 5546
 				//typical winmail.dat attachment is
5547 5547
 				//Array([size] => 1462762[filename] => winmail.dat[mimeType] => application/ms-tnef[uid] => 100[partID] => 2[name] => winmail.dat)
5548
-				if ($resolveTNEF && ($attachment['mimeType']=='application/ms-tnef' || !strcasecmp($attachment['name'],'winmail.dat')))
5548
+				if ($resolveTNEF && ($attachment['mimeType'] == 'application/ms-tnef' || !strcasecmp($attachment['name'], 'winmail.dat')))
5549 5549
 				{
5550 5550
 					$tnefParts[] = $attachment;
5551 5551
 				}
@@ -5560,31 +5560,31 @@  discard block
 block discarded – undo
5560 5560
 			//error_log(__METHOD__.__LINE__.array2string($tnefParts));
5561 5561
 			foreach ($tnefParts as $k => $tnp)
5562 5562
 			{
5563
-				$tnefResolved=false;
5564
-				$tnef_data = $this->getAttachment($tnp['uid'],$tnp['partID'],$k,false);
5563
+				$tnefResolved = false;
5564
+				$tnef_data = $this->getAttachment($tnp['uid'], $tnp['partID'], $k, false);
5565 5565
 				$myTnef = $this->tnef_decoder($tnef_data['attachment']);
5566 5566
 				//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
5567 5567
 				// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
5568 5568
 				// we need to build Something that meets the needs
5569 5569
 				if ($myTnef)
5570 5570
 				{
5571
-					foreach($myTnef->getParts() as $mime_id => $part)
5571
+					foreach ($myTnef->getParts() as $mime_id => $part)
5572 5572
 					{
5573
-						$tnefResolved=true;
5573
+						$tnefResolved = true;
5574 5574
 						$attachment = $part->getAllDispositionParameters();
5575 5575
 						$attachment['disposition'] = $part->getDisposition();
5576 5576
 						$attachment['mimeType'] = $part->getType();
5577 5577
 						$attachment['uid'] = $tnp['uid'];
5578 5578
 						$attachment['partID'] = $tnp['partID'];
5579 5579
 						$attachment['is_winmail'] = $tnp['uid'].'@'.$tnp['partID'].'@'.$mime_id;
5580
-						if (!isset($attachment['name'])||empty($attachment['name'])) $attachment['name'] = $part->getName();
5580
+						if (!isset($attachment['name']) || empty($attachment['name'])) $attachment['name'] = $part->getName();
5581 5581
 						$attachment['size'] = $part->getBytes();
5582 5582
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5583
-						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']);
5583
+						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']);
5584 5584
 						$attachments[] = $attachment;
5585 5585
 					}
5586 5586
 				}
5587
-				if ($tnefResolved===false) $attachments[]=$tnp;
5587
+				if ($tnefResolved === false) $attachments[] = $tnp;
5588 5588
 			}
5589 5589
 		}
5590 5590
 		//error_log(__METHOD__.__LINE__.array2string($attachments));
@@ -5599,9 +5599,9 @@  discard block
 block discarded – undo
5599 5599
 	 * @return boolean|Horde_Mime_part Multipart/Mixed part decoded attachments |
5600 5600
 	 *	return false if there's no attachments or failure
5601 5601
 	 */
5602
-	public function tnef_decoder( $data )
5602
+	public function tnef_decoder($data)
5603 5603
 	{
5604
-		foreach(array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5604
+		foreach (array('Horde_Compress', 'Horde_Icalendar', 'Horde_Mapi') as $class)
5605 5605
 		{
5606 5606
 			if (!class_exists($class))
5607 5607
 			{
@@ -5633,7 +5633,7 @@  discard block
 block discarded – undo
5633 5633
 				$tmp_part->setContents($data['stream']);
5634 5634
 				$tmp_part->setDescription($data['name']);
5635 5635
 
5636
-				$type = $data['type'] . '/' . $data['subtype'];
5636
+				$type = $data['type'].'/'.$data['subtype'];
5637 5637
 				if (in_array($type, array('application/octet-stream', 'application/base64')))
5638 5638
 				{
5639 5639
 					$type = Horde_Mime_Magic::filenameToMIME($data['name']);
@@ -5676,24 +5676,24 @@  discard block
 block discarded – undo
5676 5676
 	 *
5677 5677
 	 * @return array returns an array of all resolved embeded attachments from winmail.dat
5678 5678
 	 */
5679
-	function getTnefAttachments ($_uid, $_partID, $_stream=false)
5679
+	function getTnefAttachments($_uid, $_partID, $_stream = false)
5680 5680
 	{
5681
-		$tnef_data = $this->getAttachment($_uid, $_partID,0,false);
5681
+		$tnef_data = $this->getAttachment($_uid, $_partID, 0, false);
5682 5682
 		$tnef_parts = $this->tnef_decoder($tnef_data['attachment']);
5683 5683
 		$attachments = array();
5684 5684
 		if ($tnef_parts)
5685 5685
 		{
5686
-			foreach($tnef_parts->getParts() as $mime_id => $part)
5686
+			foreach ($tnef_parts->getParts() as $mime_id => $part)
5687 5687
 			{
5688 5688
 
5689 5689
 				$attachment = $part->getAllDispositionParameters();
5690 5690
 				$attachment['mimeType'] = $part->getType();
5691
-				if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5691
+				if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5692 5692
 				if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5693 5693
 				if (empty($attachment['filename']))
5694 5694
 				{
5695
-					$attachment['filename'] = (isset($attachment['cid'])&&!empty($attachment['cid'])?
5696
-						$attachment['cid']:lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5695
+					$attachment['filename'] = (isset($attachment['cid']) && !empty($attachment['cid']) ?
5696
+						$attachment['cid'] : lang("unknown").'_Uid'.$_uid.'_Part'.$mime_id).'.'.MimeMagic::mime2ext($attachment['mimeType']);
5697 5697
 				}
5698 5698
 
5699 5699
 				$attachment['attachment'] = $part->getContents(array('stream'=>$_stream));
@@ -5717,10 +5717,10 @@  discard block
 block discarded – undo
5717 5717
 	 *
5718 5718
 	 * @return array
5719 5719
 	 */
5720
-	function getAttachment($_uid, $_partID, $_winmail_nr=0, $_returnPart=true, $_stream=false, $_folder=null)
5720
+	function getAttachment($_uid, $_partID, $_winmail_nr = 0, $_returnPart = true, $_stream = false, $_folder = null)
5721 5721
 	{
5722 5722
 		//error_log(__METHOD__.__LINE__."Uid:$_uid, PartId:$_partID, WinMailNr:$_winmail_nr, ReturnPart:$_returnPart, Stream:$_stream, Folder:$_folder".function_backtrace());
5723
-		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox']? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5723
+		if (!isset($_folder)) $_folder = ($this->sessionData['mailbox'] ? $this->sessionData['mailbox'] : $this->icServer->getCurrentMailbox());
5724 5724
 
5725 5725
 		$uidsToFetch = new Horde_Imap_Client_Ids();
5726 5726
 		if (!(is_object($_uid) || is_array($_uid))) $_uid = (array)$_uid;
@@ -5733,36 +5733,36 @@  discard block
 block discarded – undo
5733 5733
 			'ids' => $uidsToFetch,
5734 5734
 		));
5735 5735
 		if (is_object($headersNew)) {
5736
-			foreach($headersNew as $id=>$_headerObject) {
5736
+			foreach ($headersNew as $id=>$_headerObject) {
5737 5737
 				$body = $_headerObject->getFullMsg();
5738 5738
 				if ($_partID != '')
5739 5739
 				{
5740 5740
 					$mailStructureObject = $_headerObject->getStructure();
5741 5741
 					$mailStructureObject->contentTypeMap();
5742 5742
 					$part = $mailStructureObject->getPart($_partID);
5743
-					$partDisposition = ($part?$part->getDisposition():'failed');
5744
-					if ($partDisposition=='failed')
5743
+					$partDisposition = ($part ? $part->getDisposition() : 'failed');
5744
+					if ($partDisposition == 'failed')
5745 5745
 					{
5746 5746
 						error_log(__METHOD__.'('.__LINE__.'):'.array2string($_uid).','.$_partID.' ID:'.$id.' HObject:'.array2string($_headerObject).' StructureObject:'.array2string($mailStructureObject->contentTypeMap()).'->'.function_backtrace());
5747 5747
 					}
5748 5748
 					// if $partDisposition is empty, we assume attachment, and hope that the function
5749 5749
 					// itself is only triggered to fetch attachments
5750
-					if (empty($partDisposition)) $partDisposition='attachment';
5751
-					if ($part && ($partDisposition=='attachment' || $partDisposition=='inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
5750
+					if (empty($partDisposition)) $partDisposition = 'attachment';
5751
+					if ($part && ($partDisposition == 'attachment' || $partDisposition == 'inline' || ($part->getPrimaryType() == 'text' && $part->getSubType() == 'calendar')))
5752 5752
 					{
5753 5753
 						//$headerObject=$part->getAllDispositionParameters();//not used anywhere around here
5754 5754
 						$structure_mime = $part->getType();
5755 5755
 						$filename = $part->getName();
5756 5756
 						$charset = $part->getContentTypeParameter('charset');
5757 5757
 						//$structure_bytes = $part->getBytes(); $structure_partID=$part->getMimeId(); error_log(__METHOD__.__LINE__." fetchPartContents(".array2string($_uid).", $structure_partID, $_stream, $_preserveSeen,$structure_mime)" );
5758
-						$this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen=true,$structure_mime);
5758
+						$this->fetchPartContents($_uid, $part, $_stream, $_preserveSeen = true, $structure_mime);
5759 5759
 						if ($_returnPart) return $part;
5760 5760
 					}
5761 5761
 				}
5762 5762
 			}
5763 5763
 		}
5764 5764
 		$ext = MimeMagic::mime2ext($structure_mime);
5765
-		if ($ext && stripos($filename,'.')===false && stripos($filename,$ext)===false) $filename = trim($filename).'.'.$ext;
5765
+		if ($ext && stripos($filename, '.') === false && stripos($filename, $ext) === false) $filename = trim($filename).'.'.$ext;
5766 5766
 		if (!$part)
5767 5767
 		{
5768 5768
 			throw new Exception\WrongParameter("Error: Could not fetch attachment for Uid=".array2string($_uid).", PartId=$_partID, WinMailNr=$_winmail_nr, folder=$_folder");
@@ -5780,20 +5780,20 @@  discard block
 block discarded – undo
5780 5780
 		// try guessing the mimetype, if we get the application/octet-stream
5781 5781
 		if (strtolower($attachmentData['type']) == 'application/octet-stream') $attachmentData['type'] = MimeMagic::filename2mime($attachmentData['filename']);
5782 5782
 		# if the attachment holds a winmail number and is a winmail.dat then we have to handle that.
5783
-		if ( $filename == 'winmail.dat' && $_winmail_nr)
5783
+		if ($filename == 'winmail.dat' && $_winmail_nr)
5784 5784
 		{
5785 5785
 			//by now _uid is of type array
5786
-			$tnefResolved=false;
5787
-			$wantedPart=$_uid[0].'@'.$_partID;
5786
+			$tnefResolved = false;
5787
+			$wantedPart = $_uid[0].'@'.$_partID;
5788 5788
 			$myTnef = $this->tnef_decoder($attachmentData['attachment']);
5789 5789
 			//error_log(__METHOD__.__LINE__.array2string($myTnef->getParts()));
5790 5790
 			// Note: MimeId starts with 0, almost always, we cannot use that as winmail_id
5791 5791
 			// we need to build Something that meets the needs
5792 5792
 			if ($myTnef)
5793 5793
 			{
5794
-				foreach($myTnef->getParts() as $mime_id => $part)
5794
+				foreach ($myTnef->getParts() as $mime_id => $part)
5795 5795
 				{
5796
-					$tnefResolved=true;
5796
+					$tnefResolved = true;
5797 5797
 					$attachment = $part->getAllDispositionParameters();
5798 5798
 					$attachment['mimeType'] = $part->getType();
5799 5799
 					//error_log(__METHOD__.__LINE__.'#'.$mime_id.'#'.$filename.'#'.array2string($attachment));
@@ -5801,9 +5801,9 @@  discard block
 block discarded – undo
5801 5801
 					if ($_winmail_nr == $wantedPart.'@'.$mime_id)
5802 5802
 					{
5803 5803
 						//error_log(__METHOD__.__LINE__.'#'.$structure_mime.'#'.$filename.'#'.array2string($attachment));
5804
-						if (!isset($attachment['filename'])||empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5804
+						if (!isset($attachment['filename']) || empty($attachment['filename'])) $attachment['filename'] = $part->getName();
5805 5805
 						if (($cid = $part->getContentId())) $attachment['cid'] = $cid;
5806
-						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']);
5806
+						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']);
5807 5807
 						$wmattach = $attachment;
5808 5808
 						$wmattach['attachment'] = $part->getContents(array('stream'=>$_stream));
5809 5809
 
@@ -5813,7 +5813,7 @@  discard block
 block discarded – undo
5813 5813
 			if ($tnefResolved)
5814 5814
 			{
5815 5815
 				$ext = MimeMagic::mime2ext($wmattach['mimeType']);
5816
-				if ($ext && stripos($wmattach['filename'],'.')===false && stripos($wmattach['filename'],$ext)===false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
5816
+				if ($ext && stripos($wmattach['filename'], '.') === false && stripos($wmattach['filename'], $ext) === false) $wmattach['filename'] = trim($wmattach['filename']).'.'.$ext;
5817 5817
 				$attachmentData = array(
5818 5818
 					'type'       => $wmattach['mimeType'],
5819 5819
 					'filename'   => $wmattach['filename'],
@@ -5837,21 +5837,21 @@  discard block
 block discarded – undo
5837 5837
 	 *	true:
5838 5838
 	 * @return Horde_Mime_Part
5839 5839
 	 */
5840
-	function getAttachmentByCID($_uid, $_cid, $_part, $_stream=null)
5840
+	function getAttachmentByCID($_uid, $_cid, $_part, $_stream = null)
5841 5841
 	{
5842 5842
 		// some static variables to avoid fetching the same mail multiple times
5843
-		static $uid=null, $part=null, $structure=null;
5843
+		static $uid = null, $part = null, $structure = null;
5844 5844
 		//error_log(__METHOD__.' ('.__LINE__.') '.":$_uid, $_cid, $_part");
5845 5845
 
5846
-		if(empty($_cid)) return false;
5846
+		if (empty($_cid)) return false;
5847 5847
 
5848 5848
 		if ($_uid != $uid || $_part != $part)
5849 5849
 		{
5850
-			$structure = $this->getStructure($uid=$_uid, $part=$_part);
5850
+			$structure = $this->getStructure($uid = $_uid, $part = $_part);
5851 5851
 		}
5852 5852
 		/** @var Horde_Mime_Part */
5853 5853
 		$attachment = null;
5854
-		foreach($structure->contentTypeMap() as $mime_id => $mime_type)
5854
+		foreach ($structure->contentTypeMap() as $mime_id => $mime_type)
5855 5855
 		{
5856 5856
 			$part = $structure->getPart($mime_id);
5857 5857
 
@@ -5903,16 +5903,16 @@  discard block
 block discarded – undo
5903 5903
 	 * @param string  $_mimetype to decide wether to try to fetch part as binary or not
5904 5904
 	 * @return Horde_Mime_Part
5905 5905
 	 */
5906
-	public function fetchPartContents($_uid, Horde_Mime_Part $part=null, $_stream=false, $_preserveSeen=false, $_mimetype=null)
5906
+	public function fetchPartContents($_uid, Horde_Mime_Part $part = null, $_stream = false, $_preserveSeen = false, $_mimetype = null)
5907 5907
 	{
5908
-		if (is_null($part)) return null;//new Horde_Mime_Part;
5908
+		if (is_null($part)) return null; //new Horde_Mime_Part;
5909 5909
 		$encoding = null;
5910 5910
 		$fetchAsBinary = true;
5911
-		if ($_mimetype && strtolower($_mimetype)=='message/rfc822') $fetchAsBinary = false;
5911
+		if ($_mimetype && strtolower($_mimetype) == 'message/rfc822') $fetchAsBinary = false;
5912 5912
 		// we need to set content on structure to decode transfer encoding
5913 5913
 		$part->setContents(
5914 5914
 			$this->getBodyPart($_uid, $part->getMimeId(), null, $_preserveSeen, $_stream, $encoding, $fetchAsBinary),
5915
-			array('encoding' => (!$fetchAsBinary&&!$encoding?'8bit':$encoding)));
5915
+			array('encoding' => (!$fetchAsBinary && !$encoding ? '8bit' : $encoding)));
5916 5916
 
5917 5917
 		return $part;
5918 5918
 	}
@@ -5930,17 +5930,17 @@  discard block
 block discarded – undo
5930 5930
 	 * @return the id of the message appended or exception
5931 5931
 	 * @throws Exception\WrongUserinput
5932 5932
 	 */
5933
-	function appendMessage($_folderName, $_header, $_body, $_flags='\\Recent')
5933
+	function appendMessage($_folderName, $_header, $_body, $_flags = '\\Recent')
5934 5934
 	{
5935 5935
 		if (!is_resource($_header))
5936 5936
 		{
5937
-			if (stripos($_header,'message-id:')===false)
5937
+			if (stripos($_header, 'message-id:') === false)
5938 5938
 			{
5939 5939
 				$_header = 'Message-ID: <'.self::getRandomString().'@localhost>'."\n".$_header;
5940 5940
 			}
5941 5941
 			//error_log(__METHOD__.' ('.__LINE__.') '."$_folderName, $_header, $_body, $_flags");
5942
-			$_header = ltrim(str_replace("\n","\r\n",$_header));
5943
-			$_header .= str_replace("\n","\r\n",$_body);
5942
+			$_header = ltrim(str_replace("\n", "\r\n", $_header));
5943
+			$_header .= str_replace("\n", "\r\n", $_body);
5944 5944
 		}
5945 5945
 		// the recent flag is the default enforced here ; as we assume the _flags is always set,
5946 5946
 		// we default it to hordes default (Recent) (, other wise we should not pass the parameter
@@ -5958,7 +5958,7 @@  discard block
 block discarded – undo
5958 5958
 			// searched for the message-id then returning the uid found
5959 5959
 			//$dataNflags[] = array('data'=>array(array('t'=>'text','v'=>"$header"."$body")), 'flags'=>array($_flags));
5960 5960
 			$dataNflags[] = array('data' => $_header, 'flags'=>array($_flags));
5961
-			$messageid = $this->icServer->append($_folderName,$dataNflags);
5961
+			$messageid = $this->icServer->append($_folderName, $dataNflags);
5962 5962
 		}
5963 5963
 		catch (\Exception $e)
5964 5964
 		{
@@ -5970,7 +5970,7 @@  discard block
 block discarded – undo
5970 5970
 		//$messageid = true; // for debug reasons only
5971 5971
 		if ($messageid === true || empty($messageid)) // try to figure out the message uid
5972 5972
 		{
5973
-			$list = $this->getHeaders($_folderName, $_startMessage=1, 1, 'INTERNALDATE', true, array(),null, false);
5973
+			$list = $this->getHeaders($_folderName, $_startMessage = 1, 1, 'INTERNALDATE', true, array(), null, false);
5974 5974
 			if ($list)
5975 5975
 			{
5976 5976
 				if (self::$debug) error_log(__METHOD__.' ('.__LINE__.') '.' MessageUid:'.$messageid.' but found:'.array2string($list));
@@ -6010,27 +6010,27 @@  discard block
 block discarded – undo
6010 6010
 	 *				'attachments'=>$attachments,
6011 6011
 	 *				'headers'=>$headers,; boolean false on failure
6012 6012
 	 */
6013
-	static function get_mailcontent(&$mailClass,$uid,$partid='',$mailbox='', $preserveHTML = false, $addHeaderSection=true, $includeAttachments=true)
6013
+	static function get_mailcontent(&$mailClass, $uid, $partid = '', $mailbox = '', $preserveHTML = false, $addHeaderSection = true, $includeAttachments = true)
6014 6014
 	{
6015 6015
 			//echo __METHOD__." called for $uid,$partid <br>";
6016
-			$headers = $mailClass->getMessageHeader($uid,$partid,true,false,$mailbox);
6016
+			$headers = $mailClass->getMessageHeader($uid, $partid, true, false, $mailbox);
6017 6017
 			if (empty($headers)) return false;
6018 6018
 			// dont force retrieval of the textpart, let mailClass preferences decide
6019
-			$bodyParts = $mailClass->getMessageBody($uid,($preserveHTML?'always_display':'only_if_no_text'),$partid,null,false,$mailbox);
6019
+			$bodyParts = $mailClass->getMessageBody($uid, ($preserveHTML ? 'always_display' : 'only_if_no_text'), $partid, null, false, $mailbox);
6020 6020
 			// if we do not want HTML but there is no TextRepresentation with the message itself, try converting
6021
-			if ( !$preserveHTML && $bodyParts[0]['mimeType']=='text/html')
6021
+			if (!$preserveHTML && $bodyParts[0]['mimeType'] == 'text/html')
6022 6022
 			{
6023
-				foreach($bodyParts as $i => $part)
6023
+				foreach ($bodyParts as $i => $part)
6024 6024
 				{
6025
-					if ($bodyParts[$i]['mimeType']=='text/html')
6025
+					if ($bodyParts[$i]['mimeType'] == 'text/html')
6026 6026
 					{
6027
-						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'],$bodyParts[$i]['charSet'],true,$stripalltags=true);
6028
-						$bodyParts[$i]['mimeType']='text/plain';
6027
+						$bodyParts[$i]['body'] = Mail\Html::convertHTMLToText($bodyParts[$i]['body'], $bodyParts[$i]['charSet'], true, $stripalltags = true);
6028
+						$bodyParts[$i]['mimeType'] = 'text/plain';
6029 6029
 					}
6030 6030
 				}
6031 6031
 			}
6032 6032
 			//error_log(array2string($bodyParts));
6033
-			$attachments = $includeAttachments?$mailClass->getMessageAttachments($uid,$partid,null,true,false,true,$mailbox):array();
6033
+			$attachments = $includeAttachments ? $mailClass->getMessageAttachments($uid, $partid, null, true, false, true, $mailbox) : array();
6034 6034
 
6035 6035
 			if ($mailClass->isSentFolder($mailbox)) $mailaddress = $headers['TO'];
6036 6036
 			elseif (isset($headers['FROM'])) $mailaddress = $headers['FROM'];
@@ -6041,7 +6041,7 @@  discard block
 block discarded – undo
6041 6041
 
6042 6042
 			$message = self::getdisplayableBody($mailClass, $bodyParts, $preserveHTML);
6043 6043
 			if ($preserveHTML && $mailClass->activeMimeType == 'text/plain') $message = '<pre>'.$message.'</pre>';
6044
-			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '',$preserveHTML) : '');
6044
+			$headdata = ($addHeaderSection ? self::createHeaderInfoSection($headers, '', $preserveHTML) : '');
6045 6045
 			$message = $headdata.$message;
6046 6046
 			//echo __METHOD__.'<br>';
6047 6047
 			//_debug_array($attachments);
@@ -6057,25 +6057,25 @@  discard block
 block discarded – undo
6057 6057
 						//_debug_array($mailClass->getMessageHeader($uid, $attachment['partID']));
6058 6058
 						//_debug_array($mailClass->getMessageBody($uid,'', $attachment['partID']));
6059 6059
 						//_debug_array($mailClass->getMessageAttachments($uid, $attachment['partID']));
6060
-						$mailcontent = self::get_mailcontent($mailClass,$uid,$attachment['partID'],$mailbox);
6061
-						$headdata ='';
6060
+						$mailcontent = self::get_mailcontent($mailClass, $uid, $attachment['partID'], $mailbox);
6061
+						$headdata = '';
6062 6062
 						if ($mailcontent['headers'])
6063 6063
 						{
6064
-							$headdata = self::createHeaderInfoSection($mailcontent['headers'],'',$preserveHTML);
6064
+							$headdata = self::createHeaderInfoSection($mailcontent['headers'], '', $preserveHTML);
6065 6065
 						}
6066 6066
 						if ($mailcontent['message'])
6067 6067
 						{
6068
-							$tempname =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6068
+							$tempname = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6069 6069
 							$attachedMessages[] = array(
6070 6070
 								'type' => 'TEXT/PLAIN',
6071 6071
 								'name' => $mailcontent['subject'].'.txt',
6072 6072
 								'tmp_name' => $tempname,
6073 6073
 							);
6074
-							$tmpfile = fopen($tempname,'w');
6075
-							fwrite($tmpfile,$headdata.$mailcontent['message']);
6074
+							$tmpfile = fopen($tempname, 'w');
6075
+							fwrite($tmpfile, $headdata.$mailcontent['message']);
6076 6076
 							fclose($tmpfile);
6077 6077
 						}
6078
-						foreach($mailcontent['attachments'] as &$tmpval)
6078
+						foreach ($mailcontent['attachments'] as &$tmpval)
6079 6079
 						{
6080 6080
 							$attachedMessages[] = $tmpval;
6081 6081
 						}
@@ -6083,36 +6083,36 @@  discard block
 block discarded – undo
6083 6083
 					}
6084 6084
 					else
6085 6085
 					{
6086
-						$attachments[$num] = array_merge($attachments[$num],$mailClass->getAttachment($uid, $attachment['partID'],0,false,false));
6086
+						$attachments[$num] = array_merge($attachments[$num], $mailClass->getAttachment($uid, $attachment['partID'], 0, false, false));
6087 6087
 
6088
-						if (empty($attachments[$num]['attachment'])&&$attachments[$num]['cid'])
6088
+						if (empty($attachments[$num]['attachment']) && $attachments[$num]['cid'])
6089 6089
 						{
6090
-							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'],true);
6090
+							$c = $mailClass->getAttachmentByCID($uid, $attachment['cid'], $attachment['partID'], true);
6091 6091
 							$attachments[$num]['attachment'] = $c->getContents();
6092 6092
 						}
6093 6093
 						// no attempt to convert, if we dont know about the charset
6094
-						if (isset($attachments[$num]['charset'])&&!empty($attachments[$num]['charset'])) {
6094
+						if (isset($attachments[$num]['charset']) && !empty($attachments[$num]['charset'])) {
6095 6095
 							// we do not try guessing the charset, if it is not set
6096 6096
 							//if ($attachments[$num]['charset']===false) $attachments[$num]['charset'] = Translation::detect_encoding($attachments[$num]['attachment']);
6097
-							Translation::convert($attachments[$num]['attachment'],$attachments[$num]['charset']);
6097
+							Translation::convert($attachments[$num]['attachment'], $attachments[$num]['charset']);
6098 6098
 						}
6099
-						if(in_array($attachments[$num]['name'], $file_list))
6099
+						if (in_array($attachments[$num]['name'], $file_list))
6100 6100
 						{
6101 6101
 							$dupe_count[$attachments[$num]['name']]++;
6102
-							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME) .
6103
-								' ('.($dupe_count[$attachments[$num]['name']] + 1).')' . '.' .
6102
+							$attachments[$num]['name'] = pathinfo($attachments[$num]['name'], PATHINFO_FILENAME).
6103
+								' ('.($dupe_count[$attachments[$num]['name']] + 1).')'.'.'.
6104 6104
 								pathinfo($attachments[$num]['name'], PATHINFO_EXTENSION);
6105 6105
 						}
6106 6106
 						$attachments[$num]['type'] = $attachments[$num]['mimeType'];
6107
-						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6108
-						$tmpfile = fopen($attachments[$num]['tmp_name'],'w');
6109
-						fwrite($tmpfile,$attachments[$num]['attachment']);
6107
+						$attachments[$num]['tmp_name'] = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6108
+						$tmpfile = fopen($attachments[$num]['tmp_name'], 'w');
6109
+						fwrite($tmpfile, $attachments[$num]['attachment']);
6110 6110
 						fclose($tmpfile);
6111 6111
 						$file_list[] = $attachments[$num]['name'];
6112 6112
 						unset($attachments[$num]['attachment']);
6113 6113
 					}
6114 6114
 				}
6115
-				if (is_array($attachedMessages)) $attachments = array_merge($attachments,$attachedMessages);
6115
+				if (is_array($attachedMessages)) $attachments = array_merge($attachments, $attachedMessages);
6116 6116
 			}
6117 6117
 			return array(
6118 6118
 					'mailaddress'=>$mailaddress,
@@ -6134,10 +6134,10 @@  discard block
 block discarded – undo
6134 6134
 	{
6135 6135
 		$c = 0;
6136 6136
 		// use the standardIdentity
6137
-		foreach($_identities as $key => $acc) {
6138
-			if ($c==0) $identity = $acc;
6137
+		foreach ($_identities as $key => $acc) {
6138
+			if ($c == 0) $identity = $acc;
6139 6139
 			//error_log(__METHOD__.__LINE__." $key == $_profile_id ");
6140
-			if ($key==$_profile_id) $identity = $acc;
6140
+			if ($key == $_profile_id) $identity = $acc;
6141 6141
 			$c++;
6142 6142
 		}
6143 6143
 		return $identity;
@@ -6149,29 +6149,29 @@  discard block
 block discarded – undo
6149 6149
 	 * @param bool createHTML do it with HTML breaks
6150 6150
 	 * @return string a preformatted string with the information of the header worked into it
6151 6151
 	 */
6152
-	static function createHeaderInfoSection($header,$headline='', $createHTML = false)
6152
+	static function createHeaderInfoSection($header, $headline = '', $createHTML = false)
6153 6153
 	{
6154 6154
 		$headdata = null;
6155 6155
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($header).function_backtrace());
6156
-		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML?"<br />":"\n");
6157
-		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML?"<br />":"\n");
6158
-		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML?"<br />":"\n");
6159
-		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML?"<br />":"\n");
6160
-		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML?"<br />":"\n");
6161
-		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML?"<br />":"\n");
6162
-		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML?"<br />":"\n");
6163
-		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML?"<br />":"\n");
6164
-		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] !='normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML?"<br />":"\n");
6156
+		if ($header['SUBJECT']) $headdata = lang('subject').': '.$header['SUBJECT'].($createHTML ? "<br />" : "\n");
6157
+		if ($header['FROM']) $headdata .= lang('from').': '.self::convertAddressArrayToString($header['FROM'], $createHTML).($createHTML ? "<br />" : "\n");
6158
+		if ($header['SENDER']) $headdata .= lang('sender').': '.self::convertAddressArrayToString($header['SENDER'], $createHTML).($createHTML ? "<br />" : "\n");
6159
+		if ($header['TO']) $headdata .= lang('to').': '.self::convertAddressArrayToString($header['TO'], $createHTML).($createHTML ? "<br />" : "\n");
6160
+		if ($header['CC']) $headdata .= lang('cc').': '.self::convertAddressArrayToString($header['CC'], $createHTML).($createHTML ? "<br />" : "\n");
6161
+		if ($header['BCC']) $headdata .= lang('bcc').': '.self::convertAddressArrayToString($header['BCC'], $createHTML).($createHTML ? "<br />" : "\n");
6162
+		if ($header['DATE']) $headdata .= lang('date').': '.$header['DATE'].($createHTML ? "<br />" : "\n");
6163
+		if ($header['PRIORITY'] && $header['PRIORITY'] != 'normal') $headdata .= lang('priority').': '.$header['PRIORITY'].($createHTML ? "<br />" : "\n");
6164
+		if ($header['IMPORTANCE'] && $header['IMPORTANCE'] != 'normal') $headdata .= lang('importance').': '.$header['IMPORTANCE'].($createHTML ? "<br />" : "\n");
6165 6165
 		//if ($mailcontent['headers']['ORGANIZATION']) $headdata .= lang('organization').': '.$mailcontent['headers']['ORGANIZATION']."\
6166 6166
 		if (!empty($headdata))
6167 6167
 		{
6168
-			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML?"<br />":"\n").$headdata;
6169
-			if (empty($headline)) $headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'').$headdata;
6170
-			$headdata .= ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6168
+			if (!empty($headline) && $headline != 'SUPPRESS') $headdata = "---------------------------- $headline ----------------------------".($createHTML ? "<br />" : "\n").$headdata;
6169
+			if (empty($headline)) $headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '').$headdata;
6170
+			$headdata .= ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6171 6171
 		}
6172 6172
 		else
6173 6173
 		{
6174
-			$headdata = ($headline != 'SUPPRESS'?"--------------------------------------------------------".($createHTML?"<br />":"\n"):'');
6174
+			$headdata = ($headline != 'SUPPRESS' ? "--------------------------------------------------------".($createHTML ? "<br />" : "\n") : '');
6175 6175
 		}
6176 6176
 		return $headdata;
6177 6177
 	}
@@ -6184,8 +6184,8 @@  discard block
 block discarded – undo
6184 6184
 	 */
6185 6185
 	static function adaptSubjectForImport($subject)
6186 6186
 	{
6187
-		$subject = str_replace('$$','__',($subject?$subject:lang('(no subject)')));
6188
-		$subject = str_ireplace(array('[FWD]','[',']','{','}','<','>'),array('Fwd:',' ',' ',' ',' ',' ',' '),trim($subject));
6187
+		$subject = str_replace('$$', '__', ($subject ? $subject : lang('(no subject)')));
6188
+		$subject = str_ireplace(array('[FWD]', '[', ']', '{', '}', '<', '>'), array('Fwd:', ' ', ' ', ' ', ' ', ' ', ' '), trim($subject));
6189 6189
 		return $subject;
6190 6190
 	}
6191 6191
 
@@ -6197,15 +6197,15 @@  discard block
 block discarded – undo
6197 6197
 	static function convertAddressArrayToString($rfcAddressArray)
6198 6198
 	{
6199 6199
 		//error_log(__METHOD__.' ('.__LINE__.') '.array2string($rfcAddressArray));
6200
-		$returnAddr ='';
6200
+		$returnAddr = '';
6201 6201
 		if (is_array($rfcAddressArray))
6202 6202
 		{
6203
-			foreach((array)$rfcAddressArray as $addressData) {
6203
+			foreach ((array)$rfcAddressArray as $addressData) {
6204 6204
 				//error_log(__METHOD__.' ('.__LINE__.') '.array2string($addressData));
6205
-				if($addressData['MAILBOX_NAME'] == 'NIL') {
6205
+				if ($addressData['MAILBOX_NAME'] == 'NIL') {
6206 6206
 					continue;
6207 6207
 				}
6208
-				if(strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6208
+				if (strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') {
6209 6209
 					continue;
6210 6210
 				}
6211 6211
 				if ($addressData['RFC822_EMAIL'])
@@ -6214,7 +6214,7 @@  discard block
 block discarded – undo
6214 6214
 				}
6215 6215
 				else
6216 6216
 				{
6217
-					$emailaddress = ($addressData['PERSONAL_NAME']?$addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>':$addressData['EMAIL']);
6217
+					$emailaddress = ($addressData['PERSONAL_NAME'] ? $addressData['PERSONAL_NAME'].' <'.$addressData['EMAIL'].'>' : $addressData['EMAIL']);
6218 6218
 					$addressObjectA = self::parseAddressList($emailaddress);
6219 6219
 				}
6220 6220
 				$addressObject = $addressObjectA[0];
@@ -6223,10 +6223,10 @@  discard block
 block discarded – undo
6223 6223
 				//$mb =(string)$addressObject->mailbox;
6224 6224
 				//$h = (string)$addressObject->host;
6225 6225
 				//$p = (string)$addressObject->personal;
6226
-				$returnAddr .= (strlen($returnAddr)>0?',':'');
6226
+				$returnAddr .= (strlen($returnAddr) > 0 ? ',' : '');
6227 6227
 				//error_log(__METHOD__.' ('.__LINE__.') '.$p.' <'.$mb.'@'.$h.'>');
6228 6228
 				$buff = imap_rfc822_write_address($addressObject->mailbox, Horde_Idna::decode($addressObject->host), $addressObject->personal);
6229
-				$buff = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$buff);
6229
+				$buff = str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $buff);
6230 6230
 				//error_log(__METHOD__.' ('.__LINE__.') '.' Address: '.$returnAddr);
6231 6231
 				$returnAddr .= $buff;
6232 6232
 			}
@@ -6234,8 +6234,8 @@  discard block
 block discarded – undo
6234 6234
 		else
6235 6235
 		{
6236 6236
 			// do not mess with strings, return them untouched /* ToDo: validate string as Address */
6237
-			$rfcAddressArray = self::decode_header($rfcAddressArray,true);
6238
-			$rfcAddressArray = str_replace(array('<','>','"\'','\'"'),array('[',']','"','"'),$rfcAddressArray);
6237
+			$rfcAddressArray = self::decode_header($rfcAddressArray, true);
6238
+			$rfcAddressArray = str_replace(array('<', '>', '"\'', '\'"'), array('[', ']', '"', '"'), $rfcAddressArray);
6239 6239
 			if (is_string($rfcAddressArray)) return $rfcAddressArray;
6240 6240
 		}
6241 6241
 		return $returnAddr;
@@ -6249,12 +6249,12 @@  discard block
 block discarded – undo
6249 6249
 	 * @param string &$err error-message on error
6250 6250
 	 * @return string/boolean merged content or false on error
6251 6251
 	 */
6252
-	static function merge($content,$ids,$mimetype='')
6252
+	static function merge($content, $ids, $mimetype = '')
6253 6253
 	{
6254 6254
 		$mergeobj = new Contacts\Merge();
6255 6255
 
6256
-		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ?'text/plain':'text/html');
6257
-		$rv = $mergeobj->merge_string($content,$ids,$err='',$mimetype, array(), self::$displayCharset);
6256
+		if (empty($mimetype)) $mimetype = (strlen(strip_tags($content)) == strlen($content) ? 'text/plain' : 'text/html');
6257
+		$rv = $mergeobj->merge_string($content, $ids, $err = '', $mimetype, array(), self::$displayCharset);
6258 6258
 		if (empty($rv) && !empty($content) && !empty($err)) $rv = $content;
6259 6259
 		if (!empty($err) && !empty($content) && !empty($ids)) error_log(__METHOD__.' ('.__LINE__.') '.' Merge failed for Ids:'.array2string($ids).' ContentType:'.$mimetype.' Content:'.$content.' Reason:'.array2string($err));
6260 6260
 		return $rv;
@@ -6296,12 +6296,12 @@  discard block
 block discarded – undo
6296 6296
 		else
6297 6297
 			settype($bytes, 'integer');
6298 6298
 
6299
-		return $bytes . ' ' . $type ;
6299
+		return $bytes.' '.$type;
6300 6300
 	}
6301 6301
 
6302 6302
 	static function detect_qp(&$sting) {
6303 6303
 		$needle = '/(=[0-9][A-F])|(=[A-F][0-9])|(=[A-F][A-F])|(=[0-9][0-9])/';
6304
-		return preg_match("$needle",$string);
6304
+		return preg_match("$needle", $string);
6305 6305
 	}
6306 6306
 
6307 6307
 	/**
@@ -6314,11 +6314,11 @@  discard block
 block discarded – undo
6314 6314
 	 * @param string $_methodNline - Information where the log was taken
6315 6315
 	 * @return void
6316 6316
 	 */
6317
-	static function logRunTimes($_starttime,$_endtime=null,$_message='',$_methodNline='')
6317
+	static function logRunTimes($_starttime, $_endtime = null, $_message = '', $_methodNline = '')
6318 6318
 	{
6319 6319
 		if (is_null($_endtime)) $_endtime = microtime(true);
6320 6320
 		$usagetime = microtime(true) - $_starttime;
6321
-		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime,5).'(s) '.($_message?'Details:'.$_message:''));
6321
+		if (self::$debugTimes) error_log($_methodNline.' took:'.number_format($usagetime, 5).'(s) '.($_message ? 'Details:'.$_message : ''));
6322 6322
 	}
6323 6323
 
6324 6324
 	/**
@@ -6331,9 +6331,9 @@  discard block
 block discarded – undo
6331 6331
 	 *
6332 6332
 	 * @throws Exception\WrongUserinput
6333 6333
 	 */
6334
-	static function checkFileBasics(&$_formData, $IDtoAddToFileName='', $reqMimeType='message/rfc822')
6334
+	static function checkFileBasics(&$_formData, $IDtoAddToFileName = '', $reqMimeType = 'message/rfc822')
6335 6335
 	{
6336
-		if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6336
+		if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'egw-data') return $_formData['file'];
6337 6337
 
6338 6338
 		//error_log(__METHOD__.__FILE__.array2string($_formData).' Id:'.$IDtoAddToFileName.' ReqMimeType:'.$reqMimeType);
6339 6339
 		$importfailed = $tmpFileName = false;
@@ -6343,7 +6343,7 @@  discard block
 block discarded – undo
6343 6343
 			$importfailed = true;
6344 6344
 			$alert_msg .= lang("Empty file %1 ignored.", $_formData['name']);
6345 6345
 		}
6346
-		elseif (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6346
+		elseif (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs' || is_uploaded_file($_formData['file']) ||
6347 6347
 			realpath(dirname($_formData['file'])) == realpath($GLOBALS['egw_info']['server']['temp_dir']))
6348 6348
 		{
6349 6349
 			// ensure existance of eGW temp dir
@@ -6351,7 +6351,7 @@  discard block
 block discarded – undo
6351 6351
 			// and different from any other temp file location set in php.ini
6352 6352
 			if (!file_exists($GLOBALS['egw_info']['server']['temp_dir']))
6353 6353
 			{
6354
-				@mkdir($GLOBALS['egw_info']['server']['temp_dir'],0700);
6354
+				@mkdir($GLOBALS['egw_info']['server']['temp_dir'], 0700);
6355 6355
 			}
6356 6356
 
6357 6357
 			// if we were NOT able to create this temp directory, then make an ERROR report
@@ -6378,14 +6378,14 @@  discard block
 block discarded – undo
6378 6378
 			// maybe its application/octet-stream -> this may mean that we could not determine the type
6379 6379
 			// so we check for the suffix too
6380 6380
 			// trust vfs mime-types, trust the mimetype if it contains a method
6381
-			if ((substr($_formData['file'],0,6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'],'method=')===false)
6381
+			if ((substr($_formData['file'], 0, 6) !== 'vfs://' || $_formData['type'] == 'application/octet-stream') && stripos($_formData['type'], 'method=') === false)
6382 6382
 			{
6383
-				$buff = explode('.',$_formData['name']);
6383
+				$buff = explode('.', $_formData['name']);
6384 6384
 				$suffix = '';
6385 6385
 				if (is_array($buff)) $suffix = array_pop($buff); // take the last extension to check with ext2mime
6386 6386
 				if (!empty($suffix)) $sfxMimeType = MimeMagic::ext2mime($suffix);
6387 6387
 				if (!empty($suffix) && !empty($sfxMimeType) &&
6388
-					(strlen(trim($_formData['type']))==0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6388
+					(strlen(trim($_formData['type'])) == 0 || (strtolower(trim($_formData['type'])) != $sfxMimeType)))
6389 6389
 				{
6390 6390
 					error_log(__METHOD__.' ('.__LINE__.') '.' Data:'.array2string($_formData));
6391 6391
 					error_log(__METHOD__.' ('.__LINE__.') '.' Form reported Mimetype:'.$_formData['type'].' but seems to be:'.$sfxMimeType);
@@ -6400,13 +6400,13 @@  discard block
 block discarded – undo
6400 6400
 			if ($reqMimeType)
6401 6401
 			{
6402 6402
 				// so if PHP did not pass any file_type info, then substitute the rfc default value
6403
-				if (substr(strtolower(trim($_formData['type'])),0,strlen($mime_type_default)) != $mime_type_default)
6403
+				if (substr(strtolower(trim($_formData['type'])), 0, strlen($mime_type_default)) != $mime_type_default)
6404 6404
 				{
6405 6405
 					if (!(strtolower(trim($_formData['type'])) == "application/octet-stream" && $sfxMimeType == $reqMimeType))
6406 6406
 					{
6407 6407
 						//error_log("Message rejected, no message/rfc. Is:".$_formData['type']);
6408 6408
 						$importfailed = true;
6409
-						$alert_msg .= lang("File rejected, no %2. Is:%1",$_formData['type'],$reqMimeType);
6409
+						$alert_msg .= lang("File rejected, no %2. Is:%1", $_formData['type'], $reqMimeType);
6410 6410
 					}
6411 6411
 					if ((strtolower(trim($_formData['type'])) != $reqMimeType && $sfxMimeType == $reqMimeType))
6412 6412
 					{
@@ -6415,17 +6415,17 @@  discard block
 block discarded – undo
6415 6415
 				}
6416 6416
 			}
6417 6417
 			// as FreeBSD seems to have problems with the generated temp names we append some more random stuff
6418
-			$randomString = chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90)).chr(rand(48,57)).chr(rand(65,90));
6418
+			$randomString = chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90)).chr(rand(48, 57)).chr(rand(65, 90));
6419 6419
 			$tmpFileName = $GLOBALS['egw_info']['user']['account_id'].
6420 6420
 				trim($IDtoAddToFileName).basename($_formData['file']).'_'.$randomString;
6421 6421
 
6422
-			if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs')
6422
+			if (parse_url($_formData['file'], PHP_URL_SCHEME) == 'vfs')
6423 6423
 			{
6424
-				$tmpFileName = $_formData['file'];	// no need to store it somewhere
6424
+				$tmpFileName = $_formData['file']; // no need to store it somewhere
6425 6425
 			}
6426 6426
 			elseif (is_uploaded_file($_formData['file']))
6427 6427
 			{
6428
-				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName);	// requirement for safe_mode!
6428
+				move_uploaded_file($_formData['file'], $GLOBALS['egw_info']['server']['temp_dir'].'/'.$tmpFileName); // requirement for safe_mode!
6429 6429
 			}
6430 6430
 			else
6431 6431
 			{
@@ -6434,7 +6434,7 @@  discard block
 block discarded – undo
6434 6434
 		} else {
6435 6435
 			//error_log("Import of message ".$_formData['file']." failes to meet basic restrictions");
6436 6436
 			$importfailed = true;
6437
-			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.",$_formData['name']);
6437
+			$alert_msg .= lang("Processing of file %1 failed. Failed to meet basic restrictions.", $_formData['name']);
6438 6438
 		}
6439 6439
 		if ($importfailed == true)
6440 6440
 		{
@@ -6442,7 +6442,7 @@  discard block
 block discarded – undo
6442 6442
 		}
6443 6443
 		else
6444 6444
 		{
6445
-			if (parse_url($tmpFileName,PHP_URL_SCHEME) == 'vfs')
6445
+			if (parse_url($tmpFileName, PHP_URL_SCHEME) == 'vfs')
6446 6446
 			{
6447 6447
 				Vfs::load_wrapper('vfs');
6448 6448
 			}
@@ -6467,7 +6467,7 @@  discard block
 block discarded – undo
6467 6467
 		$images = null;
6468 6468
 		if (preg_match_all("/(src|background)=\"(.*)\"/Ui", $_html2parse, $images) && isset($images[2]))
6469 6469
 		{
6470
-			foreach($images[2] as $i => $url)
6470
+			foreach ($images[2] as $i => $url)
6471 6471
 			{
6472 6472
 				//$isData = false;
6473 6473
 				$basedir = $data = '';
@@ -6479,20 +6479,20 @@  discard block
 block discarded – undo
6479 6479
 					$filename = basename($url);
6480 6480
 					if (($directory = dirname($url)) == '.') $directory = '';
6481 6481
 					$ext = pathinfo($filename, PATHINFO_EXTENSION);
6482
-					$mimeType  = MimeMagic::ext2mime($ext);
6483
-					if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
6482
+					$mimeType = MimeMagic::ext2mime($ext);
6483
+					if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
6484 6484
 					$myUrl = $directory.$filename;
6485
-					if ($myUrl[0]=='/') // local path -> we only allow path's that are available via http/https (or vfs)
6485
+					if ($myUrl[0] == '/') // local path -> we only allow path's that are available via http/https (or vfs)
6486 6486
 					{
6487
-						$basedir = ($_SERVER['HTTPS']?'https://':'http://'.$_SERVER['HTTP_HOST']);
6487
+						$basedir = ($_SERVER['HTTPS'] ? 'https://' : 'http://'.$_SERVER['HTTP_HOST']);
6488 6488
 					}
6489 6489
 					// use vfs instead of url containing webdav.php
6490 6490
 					// ToDo: we should test if the webdav url is of our own scope, as we cannot handle foreign
6491 6491
 					// webdav.php urls as vfs
6492
-					if (strpos($myUrl,'/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6492
+					if (strpos($myUrl, '/webdav.php') !== false) // we have a webdav link, so we build a vfs/sqlfs link of it.
6493 6493
 					{
6494 6494
 						Vfs::load_wrapper('vfs');
6495
-						list(,$myUrl) = explode('/webdav.php',$myUrl,2);
6495
+						list(,$myUrl) = explode('/webdav.php', $myUrl, 2);
6496 6496
 						$basedir = 'vfs://default';
6497 6497
 						$needTempFile = false;
6498 6498
 					}
@@ -6505,11 +6505,11 @@  discard block
 block discarded – undo
6505 6505
 						// Strips the url and store it into a temp for further procss
6506 6506
 						$tmp_url = html_entity_decode($myUrl);
6507 6507
 
6508
-						parse_str(parse_url($tmp_url, PHP_URL_QUERY),$URI_params);
6508
+						parse_str(parse_url($tmp_url, PHP_URL_QUERY), $URI_params);
6509 6509
 						if ($URI_params['mailbox'] && $URI_params['uid'] && $URI_params['cid'])
6510 6510
 						{
6511 6511
 							$mail_bo->reopen(base64_decode($URI_params['mailbox']));
6512
-							$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']),base64_decode($URI_params['partID']),true);
6512
+							$attachment = $mail_bo->getAttachmentByCID($URI_params['uid'], base64_decode($URI_params['cid']), base64_decode($URI_params['partID']), true);
6513 6513
 							$mail_bo->closeConnection();
6514 6514
 							if ($attachment)
6515 6515
 							{
@@ -6520,32 +6520,32 @@  discard block
 block discarded – undo
6520 6520
 						}
6521 6521
 					}
6522 6522
 
6523
-					if ( strlen($basedir) > 1 && substr($basedir,-1) != '/' && $myUrl[0]!='/') { $basedir .= '/'; }
6524
-					if ($needTempFile && !$attachment && substr($myUrl,0,4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6523
+					if (strlen($basedir) > 1 && substr($basedir, -1) != '/' && $myUrl[0] != '/') { $basedir .= '/'; }
6524
+					if ($needTempFile && !$attachment && substr($myUrl, 0, 4) !== "http") $data = file_get_contents($basedir.urldecode($myUrl));
6525 6525
 				}
6526
-				if (substr($url,0,strlen('data:'))=='data:')
6526
+				if (substr($url, 0, strlen('data:')) == 'data:')
6527 6527
 				{
6528 6528
 					//error_log(__METHOD__.' ('.__LINE__.') '.' -> '.$i.': '.array2string($images[$i]));
6529 6529
 					// we only support base64 encoded data
6530
-					$tmp = substr($url,strlen('data:'));
6531
-					list($mimeType,$data_base64) = explode(';base64,',$tmp);
6530
+					$tmp = substr($url, strlen('data:'));
6531
+					list($mimeType, $data_base64) = explode(';base64,', $tmp);
6532 6532
 					$data = base64_decode($data_base64);
6533 6533
 					// FF currently does NOT add any mime-type
6534 6534
 					if (strtolower(substr($mimeType, 0, 6)) != 'image/')
6535 6535
 					{
6536 6536
 						$mimeType = MimeMagic::analyze_data($data);
6537 6537
 					}
6538
-					list($what,$exactly) = explode('/',$mimeType);
6538
+					list($what, $exactly) = explode('/', $mimeType);
6539 6539
 					$needTempFile = true;
6540
-					$filename = ($what?$what:'data').$imageC++.'.'.$exactly;
6540
+					$filename = ($what ? $what : 'data').$imageC++.'.'.$exactly;
6541 6541
 				}
6542 6542
 				if ($data || $needTempFile === false)
6543 6543
 				{
6544 6544
 					if ($needTempFile)
6545 6545
 					{
6546
-						$attachment_file =tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
6547
-						$tmpfile = fopen($attachment_file,'w');
6548
-						fwrite($tmpfile,$data);
6546
+						$attachment_file = tempnam($GLOBALS['egw_info']['server']['temp_dir'], $GLOBALS['egw_info']['flags']['currentapp']."_");
6547
+						$tmpfile = fopen($attachment_file, 'w');
6548
+						fwrite($tmpfile, $data);
6549 6549
 						fclose($tmpfile);
6550 6550
 					}
6551 6551
 					else
@@ -6556,7 +6556,7 @@  discard block
 block discarded – undo
6556 6556
 					// (or similar) in all cases (when cut&paste). This may lead to more attached files, in case
6557 6557
 					// we use the same image multiple times, but, if we do this, we should try to detect that
6558 6558
 					// on upload. filename itself is not sufficient to determine the sameness of images
6559
-					$cid = 'cid:' . md5($attachment_file);
6559
+					$cid = 'cid:'.md5($attachment_file);
6560 6560
 					if ($_mailObject->AddEmbeddedImage($attachment_file, substr($cid, 4), urldecode($filename), $mimeType) !== null)
6561 6561
 					{
6562 6562
 						//$_html2parse = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $_html2parse);
@@ -6578,10 +6578,10 @@  discard block
 block discarded – undo
6578 6578
 	 * @param string& $importID ID for the imported message, used by attachments to identify them unambiguously
6579 6579
 	 * @return mixed array of messages with success and failed messages or exception
6580 6580
 	 */
6581
-	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID='')
6581
+	function importMessageToMergeAndSend(Storage\Merge $bo_merge, $document, $SendAndMergeTocontacts, &$_folder, &$importID = '')
6582 6582
 	{
6583 6583
 		$importfailed = false;
6584
-		$processStats = array('success'=>array(),'failed'=>array());
6584
+		$processStats = array('success'=>array(), 'failed'=>array());
6585 6585
 		if (empty($SendAndMergeTocontacts))
6586 6586
 		{
6587 6587
 			$importfailed = true;
@@ -6622,7 +6622,7 @@  discard block
 block discarded – undo
6622 6622
 				$_folder = $this->getSentFolder();
6623 6623
 			}
6624 6624
 			$delimiter = $this->getHierarchyDelimiter();
6625
-			if($_folder=='INBOX'.$delimiter) $_folder='INBOX';
6625
+			if ($_folder == 'INBOX'.$delimiter) $_folder = 'INBOX';
6626 6626
 			if ($importfailed === false)
6627 6627
 			{
6628 6628
 				$Subject = $mailObject->getHeader('Subject');
@@ -6640,9 +6640,9 @@  discard block
 block discarded – undo
6640 6640
 				{
6641 6641
 					$mailObject->clearReplyTos();
6642 6642
 					$activeMailProfiles = $this->mail->getAccountIdentities($this->profileID);
6643
-					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
6643
+					$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
6644 6644
 
6645
-					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']),Mail::generateIdentityString($activeMailProfile,false));
6645
+					$mailObject->addReplyTo(Horde_Idna::encode($activeMailProfile['ident_email']), Mail::generateIdentityString($activeMailProfile, false));
6646 6646
 				}
6647 6647
 				foreach ($SendAndMergeTocontacts as $k => $val)
6648 6648
 				{
@@ -6656,12 +6656,12 @@  discard block
 block discarded – undo
6656 6656
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6657 6657
 
6658 6658
 						// Parse destinations for placeholders
6659
-						foreach(Mailer::$type2header as $type => $h)
6659
+						foreach (Mailer::$type2header as $type => $h)
6660 6660
 						{
6661 6661
 							//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));
6662
-							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset);
6663
-							$mailObject->addAddress($merged,'',$type);
6664
-							if($type == 'to')
6662
+							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]), $val, $e, 'text/plain', array(), self::$displayCharset);
6663
+							$mailObject->addAddress($merged, '', $type);
6664
+							if ($type == 'to')
6665 6665
 							{
6666 6666
 								$email = $merged;
6667 6667
 							}
@@ -6674,26 +6674,26 @@  discard block
 block discarded – undo
6674 6674
 							//error_log(__METHOD__.' ('.__LINE__.') '.' ID:'.$val.' Data:'.array2string($contact));
6675 6675
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
6676 6676
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
6677
-							if($email)
6677
+							if ($email)
6678 6678
 							{
6679 6679
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
6680 6680
 							}
6681 6681
 						}
6682 6682
 
6683 6683
 						$activeMailProfiles = $this->getAccountIdentities($this->profileID);
6684
-						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles,$this->profileID);
6684
+						$activeMailProfile = self::getStandardIdentityForProfile($activeMailProfiles, $this->profileID);
6685 6685
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($activeMailProfile));
6686 6686
 						$mailObject->setFrom($activeMailProfile['ident_email'],
6687
-							self::generateIdentityString($activeMailProfile,false));
6687
+							self::generateIdentityString($activeMailProfile, false));
6688 6688
 
6689 6689
 						$mailObject->removeHeader('Message-ID');
6690 6690
 						$mailObject->removeHeader('Date');
6691 6691
 						$mailObject->clearCustomHeaders();
6692 6692
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6693 6693
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6694
-						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));
6694
+						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));
6695 6695
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6696
-						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));
6696
+						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));
6697 6697
 
6698 6698
 						//error_log(__METHOD__.' ('.__LINE__.') '.array2string($mailObject));
6699 6699
 						// set a higher timeout for big messages
@@ -6702,7 +6702,7 @@  discard block
 block discarded – undo
6702 6702
 						try {
6703 6703
 							$mailObject->send();
6704 6704
 						}
6705
-						catch(Exception $e) {
6705
+						catch (Exception $e) {
6706 6706
 							$sendOK = false;
6707 6707
 							$errorInfo = $e->getMessage();
6708 6708
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($errorInfo));
@@ -6716,41 +6716,41 @@  discard block
 block discarded – undo
6716 6716
 						$mailObject->clearCustomHeaders();
6717 6717
 
6718 6718
 						// Parse destinations for placeholders
6719
-						foreach(Mailer::$type2header as $type => $h)
6719
+						foreach (Mailer::$type2header as $type => $h)
6720 6720
 						{
6721
-							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]),$val,$e,'text/plain',array(),self::$displayCharset);
6721
+							$merged = $bo_merge->merge_string($mailObject->getHeader(Mailer::$type2header[$type]), $val, $e, 'text/plain', array(), self::$displayCharset);
6722 6722
 							//error_log($type . ': ' . $mailObject->getHeader(Mailer::$type2header[$type]) . ' -> ' .$merged);
6723
-							$mailObject->addAddress(trim($merged,'"'),'',$type);
6723
+							$mailObject->addAddress(trim($merged, '"'), '', $type);
6724 6724
 						}
6725 6725
 
6726 6726
 						// No addresses from placeholders?  Treat it as just a contact ID
6727
-						if (count($mailObject->getAddresses('to',true)) == 0 &&
6727
+						if (count($mailObject->getAddresses('to', true)) == 0 &&
6728 6728
 							is_numeric($val) || $GLOBALS['egw']->accounts->name2id($val)) // do the merge
6729 6729
 						{
6730 6730
 							$contact = $bo_merge->contacts->read($val);
6731 6731
 							//error_log(__METHOD__.' ('.__LINE__.') '.array2string($contact));
6732 6732
 							$email = ($contact['email'] ? $contact['email'] : $contact['email_home']);
6733 6733
 							$nfn = ($contact['n_fn'] ? $contact['n_fn'] : $contact['n_given'].' '.$contact['n_family']);
6734
-							if($email)
6734
+							if ($email)
6735 6735
 							{
6736 6736
 								$mailObject->addAddress(Horde_Idna::encode($email), $nfn);
6737 6737
 							}
6738 6738
 						}
6739 6739
 						$mailObject->addHeader('Subject', $bo_merge->merge_string($Subject, $val, $e, 'text/plain', array(), self::$displayCharset));
6740 6740
 						//error_log(__METHOD__.' ('.__LINE__.') '.' ContentType:'.$mailObject->BodyContentType);
6741
-						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));
6741
+						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));
6742 6742
 						//error_log(__METHOD__.' ('.__LINE__.') '.' Result:'.$mailObject->Body.' error:'.array2string($e));
6743
-						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));
6743
+						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));
6744 6744
 						$_folder = $this->getDraftFolder();
6745 6745
 					}
6746 6746
 					if ($sendOK || $openAsDraft)
6747 6747
 					{
6748
-						if ($this->folderExists($_folder,true))
6748
+						if ($this->folderExists($_folder, true))
6749 6749
 						{
6750
-						    if($this->isSentFolder($_folder))
6750
+						    if ($this->isSentFolder($_folder))
6751 6751
 							{
6752 6752
 						        $flags = '\\Seen';
6753
-						    } elseif($this->isDraftFolder($_folder)) {
6753
+						    } elseif ($this->isDraftFolder($_folder)) {
6754 6754
 						        $flags = '\\Draft';
6755 6755
 						    } else {
6756 6756
 						        $flags = '';
@@ -6758,7 +6758,7 @@  discard block
 block discarded – undo
6758 6758
 							$savefailed = false;
6759 6759
 							try
6760 6760
 							{
6761
-								$messageUid =$this->appendMessage($_folder,
6761
+								$messageUid = $this->appendMessage($_folder,
6762 6762
 									$mailObject->getRaw(),
6763 6763
 									null,
6764 6764
 									$flags);
@@ -6766,10 +6766,10 @@  discard block
 block discarded – undo
6766 6766
 							catch (\Exception\WrongUserinput $e)
6767 6767
 							{
6768 6768
 								$savefailed = true;
6769
-								$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3",$Subject,$_folder,$e->getMessage());
6769
+								$alert_msg .= lang("Save of message %1 failed. Could not save message to folder %2 due to: %3", $Subject, $_folder, $e->getMessage());
6770 6770
 							}
6771 6771
 							// no send, save successful, and message_uid present
6772
-							if ($savefailed===false && $messageUid && is_null($sendOK))
6772
+							if ($savefailed === false && $messageUid && is_null($sendOK))
6773 6773
 							{
6774 6774
 								$importID = $messageUid;
6775 6775
 								$openComposeWindow = true;
@@ -6778,20 +6778,20 @@  discard block
 block discarded – undo
6778 6778
 						else
6779 6779
 						{
6780 6780
 							$savefailed = true;
6781
-							$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.",$Subject,$_folder);
6781
+							$alert_msg .= lang("Saving of message %1 failed. Destination Folder %2 does not exist.", $Subject, $_folder);
6782 6782
 						}
6783 6783
 						if ($sendOK)
6784 6784
 						{
6785
-							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed?' but failed to store to Folder:'.$_folder:'');
6785
+							$processStats['success'][$val] = 'Send succeeded to '.$nfn.'<'.$email.'>'.($savefailed ? ' but failed to store to Folder:'.$_folder : '');
6786 6786
 						}
6787 6787
 						else
6788 6788
 						{
6789
-							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6789
+							if (!$openComposeWindow) $processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6790 6790
 						}
6791 6791
 					}
6792
-					if (!is_null($sendOK) && $sendOK===false && is_null($openComposeWindow))
6792
+					if (!is_null($sendOK) && $sendOK === false && is_null($openComposeWindow))
6793 6793
 					{
6794
-						$processStats['failed'][$val] = $errorInfo?$errorInfo:'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6794
+						$processStats['failed'][$val] = $errorInfo ? $errorInfo : 'Send failed to '.$nfn.'<'.$email.'> See error_log for details';
6795 6795
 					}
6796 6796
 				}
6797 6797
 			}
@@ -6861,19 +6861,18 @@  discard block
 block discarded – undo
6861 6861
 			//error_log(__METHOD__.__LINE__.':'.array2string($structure));
6862 6862
 
6863 6863
 			// unfortunately parseMessage does NOT return parsed headers (we assume header is shorter then 8k)
6864
-			$start = is_string($message) ? substr($message, 0, 8192) :
6865
-				(fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 8192));
6864
+			$start = is_string($message) ? substr($message, 0, 8192) : (fseek($message, 0, SEEK_SET) == -1 ? '' : fread($message, 8192));
6866 6865
 
6867 6866
 			$length = strpos($start, Horde_Mime_Part::RFC_EOL.Horde_Mime_Part::RFC_EOL);
6868
-			if ($length===false) $length = strlen($start);
6869
-			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0,$length));
6867
+			if ($length === false) $length = strlen($start);
6868
+			$headers = Horde_Mime_Headers::parseHeaders(substr($start, 0, $length));
6870 6869
 
6871
-			foreach($headers->toArray(array('nowrap' => true)) as $header => $value)
6870
+			foreach ($headers->toArray(array('nowrap' => true)) as $header => $value)
6872 6871
 			{
6873
-				foreach((array)$value as $n => $val)
6872
+				foreach ((array)$value as $n => $val)
6874 6873
 				{
6875 6874
 					$overwrite = !$n;
6876
-					switch($header)
6875
+					switch ($header)
6877 6876
 					{
6878 6877
 						case 'Content-Transfer-Encoding':
6879 6878
 							//as we parse the message and this sets the part with a Content-Transfer-Encoding, we
@@ -6894,7 +6893,7 @@  discard block
 block discarded – undo
6894 6893
 		}
6895 6894
 		else
6896 6895
 		{
6897
-			if (($type = gettype($message)) == 'object') $type = get_class ($message);
6896
+			if (($type = gettype($message)) == 'object') $type = get_class($message);
6898 6897
 			throw new Exception\WrongParameter('Wrong parameter type for message: '.$type);
6899 6898
 		}
6900 6899
 	}
@@ -6908,50 +6907,50 @@  discard block
 block discarded – undo
6908 6907
 	 * @param string $default_domain
6909 6908
 	 * @return Horde_Mail_Rfc822_List iteratable Horde_Mail_Rfc822_Address objects with attributes mailbox, host, personal and valid
6910 6909
 	 */
6911
-	public static function parseAddressList($addresses, $default_domain=null)
6910
+	public static function parseAddressList($addresses, $default_domain = null)
6912 6911
 	{
6913 6912
 		$rfc822 = new Horde_Mail_Rfc822();
6914 6913
 		$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
6915 6914
 		//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count.function_backtrace());
6916
-		if ((empty($ret) || $ret->count()==0)&& is_string($addresses) && strlen($addresses)>0)
6915
+		if ((empty($ret) || $ret->count() == 0) && is_string($addresses) && strlen($addresses) > 0)
6917 6916
 		{
6918 6917
 			$matches = array();
6919
-			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/",$addresses,$matches);
6918
+			preg_match_all("/[\w\.,-.,_.,0-9.]+@[\w\.,-.,_.,0-9.]+/", $addresses, $matches);
6920 6919
 			//error_log(__METHOD__.__LINE__.array2string($matches));
6921
-			foreach ($matches[0] as &$match) {$match = trim($match,', ');}
6922
-			$addresses = implode(',',$matches[0]);
6920
+			foreach ($matches[0] as &$match) {$match = trim($match, ', '); }
6921
+			$addresses = implode(',', $matches[0]);
6923 6922
 			//error_log(__METHOD__.__LINE__.array2string($addresses));
6924 6923
 			$ret = $rfc822->parseAddressList($addresses, $default_domain ? array('default_domain' => $default_domain) : array());
6925 6924
 			//error_log(__METHOD__.__LINE__.'#'.array2string($addresses).'#'.array2string($ret).'#'.$ret->count().'#'.$ret->count);
6926 6925
 		}
6927
-		$previousFailed=false;
6926
+		$previousFailed = false;
6928 6927
 		$ret2 = new Horde_Mail_Rfc822_List();
6929 6928
 		// handle known problems on emailaddresses
6930
-		foreach($ret as $i => $adr)
6929
+		foreach ($ret as $i => $adr)
6931 6930
 		{
6932 6931
 			//mailaddresses enclosed in single quotes like '[email protected]' show up as 'me as mailbox and you.com' as host
6933
-			if ($adr->mailbox && stripos($adr->mailbox,"'")== 0 &&
6934
-					$adr->host && stripos($adr->host,"'")== (strlen($adr->host) -1))
6932
+			if ($adr->mailbox && stripos($adr->mailbox, "'") == 0 &&
6933
+					$adr->host && stripos($adr->host, "'") == (strlen($adr->host) - 1))
6935 6934
 			{
6936
-				$adr->mailbox = str_replace("'","",$adr->mailbox);
6937
-				$adr->host = str_replace("'","",$adr->host);
6935
+				$adr->mailbox = str_replace("'", "", $adr->mailbox);
6936
+				$adr->host = str_replace("'", "", $adr->host);
6938 6937
 			}
6939 6938
 			// no mailbox or host part as 'Xr\xc3\xa4hlyz, User <[email protected]>' is parsed as 2 addresses separated by ','
6940 6939
 			//#'Xr\xc3\xa4hlyz, User <[email protected]>'
6941 6940
 			//#Horde_Mail_Rfc822_List Object([_data:protected] => Array(
6942 6941
 			//[0] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => Xr\xc3\xa4hlyz[_host:protected] => [_personal:protected] => )
6943 6942
 			//[1] => Horde_Mail_Rfc822_Address Object([comment] => Array()[mailbox] => mailboxpart1.mailboxpart2[_host:protected] => youthost.com[_personal:protected] => User))[_filter:protected] => Array()[_ptr:protected] => )#2#,
6944
-			if (strlen($adr->mailbox)==0||strlen($adr->host)==0)
6943
+			if (strlen($adr->mailbox) == 0 || strlen($adr->host) == 0)
6945 6944
 			{
6946
-				$remember = ($adr->mailbox?$adr->mailbox:($adr->host?$adr->host:''));
6947
-				$previousFailed=true;
6945
+				$remember = ($adr->mailbox ? $adr->mailbox : ($adr->host ? $adr->host : ''));
6946
+				$previousFailed = true;
6948 6947
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
6949 6948
 			}
6950 6949
 			else
6951 6950
 			{
6952
-				if ($previousFailed && $remember) $adr->personal = $remember. ' ' . $adr->personal;
6951
+				if ($previousFailed && $remember) $adr->personal = $remember.' '.$adr->personal;
6953 6952
 				$remember = '';
6954
-				$previousFailed=false;
6953
+				$previousFailed = false;
6955 6954
 				//error_log(__METHOD__.__LINE__."('$addresses', $default_domain) parsed $i: mailbox=$adr->mailbox, host=$adr->host, personal=$adr->personal");
6956 6955
 				$ret2->add($adr);
6957 6956
 			}
@@ -6967,7 +6966,7 @@  discard block
 block discarded – undo
6967 6966
 	 * @param string $_folder
6968 6967
 	 * @return boolean
6969 6968
 	 */
6970
-	function sendMDN($uid,$_folder)
6969
+	function sendMDN($uid, $_folder)
6971 6970
 	{
6972 6971
 		$acc = Mail\Account::read($this->profileID);
6973 6972
 		$identity = Mail\Account::read_identity($acc['ident_id'], true, null, $acc);
@@ -6997,7 +6996,7 @@  discard block
 block discarded – undo
6997 6996
 	 */
6998 6997
 	function addAccount($_hookValues)
6999 6998
 	{
7000
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
6999
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7001 7000
 
7002 7001
 	}
7003 7002
 
@@ -7011,7 +7010,7 @@  discard block
 block discarded – undo
7011 7010
 	 */
7012 7011
 	function deleteAccount($_hookValues)
7013 7012
 	{
7014
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7013
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7015 7014
 
7016 7015
 	}
7017 7016
 
@@ -7025,7 +7024,7 @@  discard block
 block discarded – undo
7025 7024
 	 */
7026 7025
 	function updateAccount($_hookValues)
7027 7026
 	{
7028
-		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!' . ' hookValue = '. $_hookValues);
7027
+		error_log(__METHOD__.' ('.__LINE__.') '.' NOT DONE YET!'.' hookValue = '.$_hookValues);
7029 7028
 
7030 7029
 	}
7031 7030
 }
Please login to merge, or discard this patch.