Completed
Pull Request — master (#1170)
by Christoph
10:11
created

MessagesController::loadMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 23
ccs 0
cts 16
cp 0
rs 9.0857
cc 2
eloc 15
nc 2
nop 3
crap 6
1
<?php
2
/**
3
 * ownCloud - Mail app
4
 *
5
 * @author Thomas Müller
6
 * @copyright 2013-2014 Thomas Müller [email protected]
7
 *
8
 * You should have received a copy of the GNU Lesser General Public
9
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
10
 *
11
 */
12
13
namespace OCA\Mail\Controller;
14
15
use OCA\Mail\Http\AttachmentDownloadResponse;
16
use OCA\Mail\Http\HtmlResponse;
17
use OCA\Mail\Service\AccountService;
18
use OCA\Mail\Service\ContactsIntegration;
19
use OCA\Mail\Service\IMailBox;
20
use OCA\Mail\Service\UnifiedAccount;
21
use OCP\AppFramework\Controller;
22
use OCP\AppFramework\Db\DoesNotExistException;
23
use OCP\AppFramework\Http;
24
use OCP\AppFramework\Http\ContentSecurityPolicy;
25
use OCP\AppFramework\Http\JSONResponse;
26
use OCP\AppFramework\Http\TemplateResponse;
27
use OCP\IL10N;
28
use OCP\Util;
29
30
class MessagesController extends Controller {
31
32
	/** @var AccountService */
33
	private $accountService;
34
35
	/**
36
	 * @var string
37
	 */
38
	private $currentUserId;
39
40
	/**
41
	 * @var ContactsIntegration
42
	 */
43
	private $contactsIntegration;
44
45
	/**
46
	 * @var \OCA\Mail\Service\Logger
47
	 */
48
	private $logger;
49
50
	/**
51
	 * @var \OCP\Files\Folder
52
	 */
53
	private $userFolder;
54
55
	/**
56
	 * @var IL10N
57
	 */
58
	private $l10n;
59
60
	/**
61
	 * @var IAccount[]
62
	 */
63
	private $accounts = [];
64
65
	/**
66
	 * @param string $appName
67
	 * @param \OCP\IRequest $request
68
	 * @param AccountService $accountService
69
	 * @param $currentUserId
70
	 * @param $userFolder
71
	 * @param $contactsIntegration
72
	 * @param $logger
73
	 * @param $l10n
74
	 */
75 12
	public function __construct($appName,
76
								$request,
77
								AccountService $accountService,
78
								$currentUserId,
79
								$userFolder,
80
								$contactsIntegration,
81
								$logger,
82
								$l10n) {
83 12
		parent::__construct($appName, $request);
84 12
		$this->accountService = $accountService;
85 12
		$this->currentUserId = $currentUserId;
86 12
		$this->userFolder = $userFolder;
87 12
		$this->contactsIntegration = $contactsIntegration;
88 12
		$this->logger = $logger;
89 12
		$this->l10n = $l10n;
90 12
	}
91
92
	/**
93
	 * @NoAdminRequired
94
	 * @NoCSRFRequired
95
	 *
96
	 * @param int $accountId
97
	 * @param string $folderId
98
	 * @param int $from
99
	 * @param int $to
100
	 * @param string $filter
101
	 * @param array $ids
102
	 * @return JSONResponse
103
	 */
104
	public function index($accountId, $folderId, $from=0, $to=20, $filter=null, $ids=null) {
105
		if (!is_null($ids)) {
106
			$ids = explode(',', $ids);
107
108
			return $this->loadMultiple($accountId, $folderId, $ids);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->loadMultip...ntId, $folderId, $ids); (array) is incompatible with the return type documented by OCA\Mail\Controller\MessagesController::index of type OCP\AppFramework\Http\JSONResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
109
		}
110
		$mailBox = $this->getFolder($accountId, $folderId);
111
112
		$this->logger->debug("loading messages $from to $to of folder <$folderId>");
113
114
		$json = $mailBox->getMessages($from, $to-$from+1, $filter);
115
116
		$ci = $this->contactsIntegration;
117
		$json = array_map(function($j) use ($ci, $mailBox) {
118
			if ($mailBox->getSpecialRole() === 'trash') {
119
				$j['delete'] = (string)$this->l10n->t('Delete permanently');
120
			}
121
122
			if ($mailBox->getSpecialRole() === 'sent') {
123
				$j['fromEmail'] = $j['toEmail'];
124
				$j['from'] = $j['to'];
125
				if((count($j['toList']) > 1) || (count($j['ccList']) > 0)) {
126
					$j['from'] .= ' ' . $this->l10n->t('& others');
127
				}
128
			}
129
130
			$j['senderImage'] = $ci->getPhoto($j['fromEmail']);
131
			return $j;
132
		}, $json);
133
134
		return new JSONResponse($json);
135
	}
136
137
	private function loadMessage($accountId, $folderId, $id) {
138
		$account = $this->getAccount($accountId);
139
		$mailBox = $account->getMailbox(base64_decode($folderId));
140
		$m = $mailBox->getMessage($id);
141
142
		$json = $this->enhanceMessage($accountId, $folderId, $id, $m, $account, $mailBox);
143
144
		// Unified inbox hack
145
		$messageId = $id;
146
		if ($accountId === UnifiedAccount::ID) {
147
			// Add accountId, folderId for unified inbox replies
148
			list($accountId, $messageId) = json_decode(base64_decode($id));
149
			$account = $this->getAccount($accountId);
150
			$inbox = $account->getInbox();
151
			$folderId = base64_encode($inbox->getFolderId());
152
		}
153
		$json['messageId'] = $messageId;
154
		$json['accountId'] = $accountId;
155
		$json['folderId'] = $folderId;
156
		// End unified inbox hack
157
158
		return $json;
159
	}
160
161
	/**
162
	 * @NoAdminRequired
163
	 * @NoCSRFRequired
164
	 *
165
	 * @param int $accountId
166
	 * @param string $folderId
167
	 * @param mixed $id
168
	 * @return JSONResponse
169
	 */
170
	public function show($accountId, $folderId, $id) {
171
		try {
172
			$json = $this->loadMessage($accountId, $folderId, $id);
173
		} catch (DoesNotExistException $ex) {
0 ignored issues
show
Bug introduced by
The class OCP\AppFramework\Db\DoesNotExistException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
174
			return new JSONResponse([], 404);
175
		}
176
		return new JSONResponse($json);
177
	}
178
179
	/**
180
	 * @NoAdminRequired
181
	 * @NoCSRFRequired
182
	 *
183
	 * @param int $accountId
184
	 * @param string $folderId
185
	 * @param string $messageId
186
	 * @return \OCA\Mail\Http\HtmlResponse
187
	 */
188 1
	public function getHtmlBody($accountId, $folderId, $messageId) {
189
		try {
190 1
			$mailBox = $this->getFolder($accountId, $folderId);
191
192 1
			$m = $mailBox->getMessage($messageId, true);
0 ignored issues
show
Unused Code introduced by
The call to IMailBox::getMessage() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
193
			$html = $m->getHtmlBody($accountId, $folderId, $messageId, function($cid) use ($m){
194
				$match = array_filter($m->attachments, function($a) use($cid){
195
					return $a['cid'] === $cid;
196
				});
197
				$match = array_shift($match);
198
				if (is_null($match)) {
199
					return null;
200
				}
201
				return $match['id'];
202 1
			});
203
204 1
			$htmlResponse = new HtmlResponse($html);
205
206
			// Harden the default security policy
207
			// FIXME: Remove once ownCloud 8.1 is a requirement for the mail app
208 1 View Code Duplication
			if(class_exists('\OCP\AppFramework\Http\ContentSecurityPolicy')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209 1
				$policy = new ContentSecurityPolicy();
210 1
				$policy->allowEvalScript(false);
211 1
				$policy->disallowScriptDomain('\'self\'');
212 1
				$policy->disallowConnectDomain('\'self\'');
213 1
				$policy->disallowFontDomain('\'self\'');
214 1
				$policy->disallowMediaDomain('\'self\'');
215 1
				$htmlResponse->setContentSecurityPolicy($policy);
216 1
			}
217
218
			// Enable caching
219 1
			$htmlResponse->cacheFor(60 * 60);
220 1
			$htmlResponse->addHeader('Pragma', 'cache');
221
222 1
			return $htmlResponse;
223
		} catch(\Exception $ex) {
224
			return new TemplateResponse($this->appName, 'error', ['message' => $ex->getMessage()], 'none');
225
		}
226
	}
227
228
	/**
229
	 * @NoAdminRequired
230
	 * @NoCSRFRequired
231
	 *
232
	 * @param int $accountId
233
	 * @param string $folderId
234
	 * @param string $messageId
235
	 * @param string $attachmentId
236
	 * @return AttachmentDownloadResponse
237
	 */
238 1
	public function downloadAttachment($accountId, $folderId, $messageId, $attachmentId) {
239 1
		$mailBox = $this->getFolder($accountId, $folderId);
240
241 1
		$attachment = $mailBox->getAttachment($messageId, $attachmentId);
242
243 1
		return new AttachmentDownloadResponse(
244 1
			$attachment->getContents(),
245 1
			$attachment->getName(),
246 1
			$attachment->getType());
247
	}
248
249
	/**
250
	 * @NoAdminRequired
251
	 * @NoCSRFRequired
252
	 *
253
	 * @param int $accountId
254
	 * @param string $folderId
255
	 * @param string $messageId
256
	 * @param string $attachmentId
257
	 * @param string $targetPath
258
	 * @return JSONResponse
259
	 */
260 2
	public function saveAttachment($accountId, $folderId, $messageId, $attachmentId, $targetPath) {
261 2
		$mailBox = $this->getFolder($accountId, $folderId);
262
263 2
		$attachmentIds = [];
0 ignored issues
show
Unused Code introduced by
$attachmentIds is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
264 2
		if($attachmentId === 0) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $attachmentId (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
265
			// Save all attachments
266 1
			$m = $mailBox->getMessage($messageId);
267
			$attachmentIds = array_map(function($a){
268 1
				return $a['id'];
269 1
			}, $m->attachments);
270 1
		} else {
271 1
			$attachmentIds = [$attachmentId];
272
		}
273
274 2
		foreach($attachmentIds as $attachmentId) {
275 2
			$attachment = $mailBox->getAttachment($messageId, $attachmentId);
276
277 2
			$fileName = $attachment->getName();
278 2
			$fileParts = pathinfo($fileName);
279 2
			$fileName = $fileParts['filename'];
280 2
			$fileExtension = $fileParts['extension'];
281 2
			$fullPath = "$targetPath/$fileName.$fileExtension";
282 2
			$counter = 2;
283 2
			while($this->userFolder->nodeExists($fullPath)) {
284
				$fullPath = "$targetPath/$fileName ($counter).$fileExtension";
285
				$counter++;
286
			}
287
288 2
			$newFile = $this->userFolder->newFile($fullPath);
289 2
			$newFile->putContent($attachment->getContents());
290 2
		}
291
292 2
		return new JSONResponse();
293
	}
294
295
	/**
296
	 * @NoAdminRequired
297
	 *
298
	 * @param int $accountId
299
	 * @param string $folderId
300
	 * @param string $messageId
301
	 * @param array $flags
302
	 * @return JSONResponse
303
	 */
304 2
	public function setFlags($accountId, $folderId, $messageId, $flags) {
305 2
		$mailBox = $this->getFolder($accountId, $folderId);
306
307 2
		foreach($flags as $flag => $value) {
308 2
			$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
309 2
			if ($flag === 'unseen') {
310 1
				$flag = 'seen';
311 1
				$value = !$value;
312 1
			}
313 2
			$mailBox->setMessageFlag($messageId, '\\'.$flag, $value);
314 2
		}
315
316 2
		return new JSONResponse();
317
	}
318
319
	/**
320
	 * @NoAdminRequired
321
	 *
322
	 * @param int $accountId
323
	 * @param string $folderId
324
	 * @param string $id
325
	 * @return JSONResponse
326
	 */
327 3
	public function destroy($accountId, $folderId, $id) {
328 3
		$this->logger->debug("deleting message <$id> of folder <$folderId>, account <$accountId>");
329
		try {
330 3
			$account = $this->getAccount($accountId);
331 2
			$account->deleteMessage(base64_decode($folderId), $id);
332 1
			return new JSONResponse();
333
334 2
		} catch (DoesNotExistException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\AppFramework\Db\DoesNotExistException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
335 2
			$this->logger->error("could not delete message <$id> of folder <$folderId>, "
336 2
				. "account <$accountId> because it does not exist");
337 2
			return new JSONResponse([], Http::STATUS_NOT_FOUND);
338
		}
339
	}
340
341
	/**
342
	 * @param int $accountId
343
	 * @return \OCA\Mail\Service\IAccount
344
	 */
345 9
	private function getAccount($accountId) {
346 9
		if (!array_key_exists($accountId, $this->accounts)) {
347 9
			$this->accounts[$accountId] = $this->accountService->find($this->currentUserId, $accountId);
348 8
		}
349 8
		return $this->accounts[$accountId];
350
	}
351
352
	/**
353
	 * @param int $accountId
354
	 * @param string $folderId
355
	 * @return IMailBox
356
	 */
357 6
	private function getFolder($accountId, $folderId) {
358 6
		$account = $this->getAccount($accountId);
359 6
		return $account->getMailbox(base64_decode($folderId));
360
	}
361
362
	/**
363
	 * @param string $messageId
364
	 * @param $accountId
365
	 * @param $folderId
366
	 * @return callable
367
	 */
368
	private function enrichDownloadUrl($accountId, $folderId, $messageId, $attachment) {
369
		$downloadUrl = \OCP\Util::linkToRoute('mail.messages.downloadAttachment', [
370
			'accountId' => $accountId,
371
			'folderId' => $folderId,
372
			'messageId' => $messageId,
373
			'attachmentId' => $attachment['id'],
374
		]);
375
		$downloadUrl = \OC::$server->getURLGenerator()->getAbsoluteURL($downloadUrl);
376
		$attachment['downloadUrl'] = $downloadUrl;
377
		$attachment['mimeUrl'] = \OC_Helper::mimetypeIcon($attachment['mime']);
378
379
		if ($this->attachmentIsImage($attachment)) {
380
			$attachment['isImage'] = true;
381
		}
382
		return $attachment;
383
	}
384
385
	/**
386
	 * @param $attachment
387
	 *
388
	 * Determines if the content of this attachment is an image
389
	 */
390
	private function attachmentIsImage($attachment) {
391
		return in_array($attachment['mime'], array('image/jpeg',
392
			'image/png',
393
			'image/gif'));
394
	}
395
396
	/**
397
	 * @param string $accountId
398
	 * @param string $folderId
399
	 * @param string $messageId
400
	 * @return string
401
	 */
402
	private function buildHtmlBodyUrl($accountId, $folderId, $messageId) {
403
		$htmlBodyUrl = \OC::$server->getURLGenerator()->linkToRoute('mail.messages.getHtmlBody', [
404
			'accountId' => $accountId,
405
			'folderId' => $folderId,
406
			'messageId' => $messageId,
407
		]);
408
		return \OC::$server->getURLGenerator()->getAbsoluteURL($htmlBodyUrl);
409
	}
410
411
	private function loadMultiple($accountId, $folderId, $ids) {
412
		$messages = array_map(function($id) use ($accountId, $folderId){
413
			try {
414
				return $this->loadMessage($accountId, $folderId, $id);
415
			} catch (DoesNotExistException $ex) {
0 ignored issues
show
Bug introduced by
The class OCP\AppFramework\Db\DoesNotExistException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
416
				return null;
417
			}
418
		}, $ids);
419
420
		return $messages;
421
	}
422
423
	/**
424
	 * @param $accountId
425
	 * @param $folderId
426
	 * @param $id
427
	 * @param $m
428
	 * @param $account
429
	 * @param $mailBox
430
	 * @return mixed
431
	 */
432
	private function enhanceMessage($accountId, $folderId, $id, $m, $account, $mailBox) {
433
		$json = $m->getFullMessage($account->getEmail(), $mailBox->getSpecialRole());
434
		$json['senderImage'] = $this->contactsIntegration->getPhoto($m->getFromEmail());
435
		if (isset($json['hasHtmlBody'])) {
436
			$json['htmlBodyUrl'] = $this->buildHtmlBodyUrl($accountId, $folderId, $id);
437
		}
438
439
		if (isset($json['attachment'])) {
440
			$json['attachment'] = $this->enrichDownloadUrl($accountId, $folderId, $id, $json['attachment']);
441
		}
442
		if (isset($json['attachments'])) {
443
			$json['attachments'] = array_map(function ($a) use ($accountId, $folderId, $id) {
444
				return $this->enrichDownloadUrl($accountId, $folderId, $id, $a);
445
			}, $json['attachments']);
446
447
			// show images first
448
			usort($json['attachments'], function($a, $b) {
449
				if (isset($a['isImage']) && !isset($b['isImage'])) {
450
					return -1;
451
				} elseif (!isset($a['isImage']) && isset($b['isImage'])) {
452
					return 1;
453
				} else {
454
					Util::naturalSortCompare($a['fileName'], $b['fileName']);
455
				}
456
			});
457
			return $json;
458
		}
459
		return $json;
460
	}
461
462
}
463