Merge pull request #16469 from civicrm/5.22
[civicrm-core.git] / tests / phpunit / api / v3 / AttachmentTest.php
1 <?php
2 /**
3 * api_v3_AttachmentTest
4 *
5 * @copyright Copyright CiviCRM LLC (C) 2014
6 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
7 * GNU Affero General Public License version 3
8 * @version $Id: ContactTest.php 31254 2010-12-15 10:09:29Z eileen $
9 * @package CiviCRM
10 *
11 * This file is part of CiviCRM
12 *
13 * CiviCRM is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Affero General Public License
15 * as published by the Free Software Foundation; either version 3 of
16 * the License, or (at your option) any later version.
17 *
18 * CiviCRM is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Affero General Public License for more details.
22 *
23 * You should have received a copy of the GNU Affero General Public
24 * License along with this program. If not, see
25 * <http://www.gnu.org/licenses/>.
26 */
27
28 /**
29 * Test for the Attachment API
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contact
33 * @group headless
34 */
35 class api_v3_AttachmentTest extends CiviUnitTestCase {
36 protected static $filePrefix = NULL;
37
38 /**
39 * @return string
40 */
41 public static function getFilePrefix() {
42 if (!self::$filePrefix) {
43 self::$filePrefix = "test_" . CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC) . '_';
44 }
45 return self::$filePrefix;
46 }
47
48 protected function setUp() {
49 parent::setUp();
50 $this->useTransaction(TRUE);
51
52 $this->cleanupFiles();
53 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
54 }
55
56 protected function tearDown() {
57 parent::tearDown();
58 $this->cleanupFiles();
59 \Civi::reset();
60 }
61
62 /**
63 * @return array
64 */
65 public function okCreateProvider() {
66 // array($entityClass, $createParams, $expectedContent)
67 $cases = [];
68
69 $cases[] = [
70 'CRM_Activity_DAO_Activity',
71 [
72 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
73 'mime_type' => 'text/plain',
74 'description' => 'My test description',
75 'content' => 'My test content',
76 ],
77 'My test content',
78 ];
79
80 $cases[] = [
81 'CRM_Activity_DAO_Activity',
82 [
83 'name' => self::getFilePrefix() . 'exampleWithEmptyContent.txt',
84 'mime_type' => 'text/plain',
85 'description' => 'My test description',
86 'content' => '',
87 ],
88 '',
89 ];
90
91 $cases[] = [
92 'CRM_Activity_DAO_Activity',
93 [
94 'name' => self::getFilePrefix() . 'exampleFromMove.txt',
95 'mime_type' => 'text/plain',
96 'description' => 'My test description',
97 'options' => [
98 'move-file' => $this->tmpFile('mytest.txt'),
99 ],
100 ],
101 'This comes from a file',
102 ];
103 $cases[] = [
104 'CRM_Core_DAO_Domain',
105 [
106 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
107 'mime_type' => 'text/plain',
108 'description' => 'My test description',
109 'content' => 'My test content',
110 ],
111 'My test content',
112 ];
113
114 return $cases;
115 }
116
117 /**
118 * @return array
119 */
120 public function badCreateProvider() {
121 // array($entityClass, $createParams, $expectedError)
122 $cases = [];
123
124 $cases[] = [
125 'CRM_Activity_DAO_Activity',
126 [
127 'id' => 12345,
128 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
129 'mime_type' => 'text/plain',
130 'description' => 'My test description',
131 'content' => 'My test content',
132 ],
133 '/Invalid ID/',
134 ];
135 $cases[] = [
136 'CRM_Activity_DAO_Activity',
137 [
138 'name' => self::getFilePrefix() . 'failedExample.txt',
139 'mime_type' => 'text/plain',
140 'description' => 'My test description',
141 ],
142 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
143 ];
144 $cases[] = [
145 'CRM_Activity_DAO_Activity',
146 [
147 'name' => self::getFilePrefix() . 'failedExample.txt',
148 'mime_type' => 'text/plain',
149 'description' => 'My test description',
150 'content' => 'too much content',
151 'options' => [
152 'move-file' => $this->tmpFile('too-much.txt'),
153 ],
154 ],
155 "/'content' and 'options.move-file' are mutually exclusive/",
156 ];
157 $cases[] = [
158 'CRM_Activity_DAO_Activity',
159 [
160 'name' => 'inv/alid.txt',
161 'mime_type' => 'text/plain',
162 'description' => 'My test description',
163 'content' => 'My test content',
164 ],
165 "/Malformed name/",
166 ];
167
168 return $cases;
169 }
170
171 /**
172 * @return array
173 */
174 public function badUpdateProvider() {
175 // array($entityClass, $createParams, $updateParams, $expectedError)
176 $cases = [];
177
178 $readOnlyFields = [
179 'name' => 'newname.txt',
180 'entity_table' => 'civicrm_domain',
181 'entity_id' => 5,
182 'upload_date' => '2010-11-12 13:14:15',
183 ];
184 foreach ($readOnlyFields as $readOnlyField => $newValue) {
185 $cases[] = [
186 'CRM_Activity_DAO_Activity',
187 [
188 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
189 'mime_type' => 'text/plain',
190 'description' => 'My test description',
191 'content' => 'My test content',
192 ],
193 [
194 'check_permissions' => 1,
195 $readOnlyField => $newValue,
196 ],
197 "/Cannot modify $readOnlyField/",
198 ];
199 }
200
201 return $cases;
202 }
203
204 /**
205 * @return array
206 */
207 public function okGetProvider() {
208 // array($getParams, $expectedNames)
209 $cases = [];
210
211 // Each search runs in a DB which contains these attachments:
212 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
213 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
214
215 // NOTE: Searching across multiple records (w/o entity_id) is currently
216 // prohibited by DynamicFKAuthorization. The technique used to authorize requests
217 // does not adapt well to such searches.
218
219 //$cases[] = array(
220 // array('entity_table' => 'civicrm_activity'),
221 // array(
222 // self::getFilePrefix() . 'example_123.csv',
223 // self::getFilePrefix() . 'example_123.txt',
224 // self::getFilePrefix() . 'example_456.csv',
225 // self::getFilePrefix() . 'example_456.txt',
226 // ),
227 //);
228 //$cases[] = array(
229 // array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
230 // array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_456.txt'),
231 //);
232
233 $cases[] = [
234 ['entity_table' => 'civicrm_activity', 'entity_id' => '123'],
235 [self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_123.csv'],
236 ];
237 $cases[] = [
238 ['entity_table' => 'civicrm_activity', 'entity_id' => '456'],
239 [self::getFilePrefix() . 'example_456.txt', self::getFilePrefix() . 'example_456.csv'],
240 ];
241 $cases[] = [
242 ['entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/csv'],
243 [self::getFilePrefix() . 'example_456.csv'],
244 ];
245 $cases[] = [
246 ['entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/html'],
247 [],
248 ];
249 $cases[] = [
250 ['entity_table' => 'civicrm_activity', 'entity_id' => '999'],
251 [],
252 ];
253
254 return $cases;
255 }
256
257 /**
258 * @return array
259 */
260 public function badGetProvider() {
261 // array($getParams, $expectedNames)
262 $cases = [];
263
264 // Each search runs in a DB which contains these attachments:
265 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
266 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
267
268 $cases[] = [
269 ['check_permissions' => 1, 'mime_type' => 'text/plain'],
270 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
271 ];
272 $cases[] = [
273 ['check_permissions' => 1, 'entity_id' => '123'],
274 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
275 ];
276 $cases[] = [
277 ['check_permissions' => 1],
278 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
279 ];
280 $cases[] = [
281 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'name' => 'example_456.csv'],
282 "/Get by name is not currently supported/",
283 ];
284 $cases[] = [
285 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'content' => 'test'],
286 "/Get by content is not currently supported/",
287 ];
288 $cases[] = [
289 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'path' => '/home/foo'],
290 "/Get by path is not currently supported/",
291 ];
292 $cases[] = [
293 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'url' => '/index.php'],
294 "/Get by url is not currently supported/",
295 ];
296
297 return $cases;
298 }
299
300 /**
301 * Create an attachment using "content" and then "get" the attachment.
302 *
303 * @param string $testEntityClass
304 * E.g. "CRM_Core_DAO_Activity".
305 * @param array $createParams
306 * @param string $expectedContent
307 * @dataProvider okCreateProvider
308 */
309 public function testCreate($testEntityClass, $createParams, $expectedContent) {
310 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
311 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
312 $this->assertTrue(is_numeric($entity->id));
313
314 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams + [
315 'entity_table' => $entity_table,
316 'entity_id' => $entity->id,
317 ]);
318 $fileId = $createResult['id'];
319 $this->assertTrue(is_numeric($fileId));
320 $this->assertEquals($entity_table, $createResult['values'][$fileId]['entity_table']);
321 $this->assertEquals($entity->id, $createResult['values'][$fileId]['entity_id']);
322 $this->assertEquals('My test description', $createResult['values'][$fileId]['description']);
323 $this->assertRegExp('/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/', $createResult['values'][$fileId]['upload_date']);
324 $this->assertTrue(!isset($createResult['values'][$fileId]['content']));
325 $this->assertTrue(!empty($createResult['values'][$fileId]['url']));
326 $this->assertAttachmentExistence(TRUE, $createResult);
327
328 $getResult = $this->callAPISuccess('Attachment', 'get', [
329 'entity_table' => $entity_table,
330 'entity_id' => $entity->id,
331 ]);
332 $this->assertEquals(1, $getResult['count']);
333 foreach (['id', 'entity_table', 'entity_id', 'url'] as $field) {
334 if ($field == 'url') {
335 $this->assertEquals(substr($createResult['values'][$fileId][$field], 0, -15), substr($getResult['values'][$fileId][$field], 0, -15));
336 $this->assertEquals(substr($createResult['values'][$fileId][$field], -3), substr($getResult['values'][$fileId][$field], -3));
337 $this->assertApproxEquals(substr($createResult['values'][$fileId][$field], -14, 10), substr($getResult['values'][$fileId][$field], -14, 10), 2);
338 }
339 else {
340 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
341 }
342 }
343 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
344
345 $getResult2 = $this->callAPISuccess('Attachment', 'get', [
346 'entity_table' => $entity_table,
347 'entity_id' => $entity->id,
348 'return' => ['content'],
349 ]);
350 $this->assertEquals($expectedContent, $getResult2['values'][$fileId]['content']);
351 // Do this again even though we just tested above to demonstrate that these fields should be returned even if you only ask to return 'content'.
352 foreach (['id', 'entity_table', 'entity_id', 'url'] as $field) {
353 if ($field == 'url') {
354 $this->assertEquals(substr($createResult['values'][$fileId][$field], 0, -15), substr($getResult2['values'][$fileId][$field], 0, -15));
355 $this->assertEquals(substr($createResult['values'][$fileId][$field], -3), substr($getResult2['values'][$fileId][$field], -3));
356 $this->assertApproxEquals(substr($createResult['values'][$fileId][$field], -14, 10), substr($getResult2['values'][$fileId][$field], -14, 10), 2);
357 }
358 else {
359 $this->assertEquals($createResult['values'][$fileId][$field], $getResult2['values'][$fileId][$field], "Expect field $field to match");
360 }
361 }
362 }
363
364 /**
365 * @param $testEntityClass
366 * @param $createParams
367 * @param $expectedError
368 * @dataProvider badCreateProvider
369 */
370 public function testCreateFailure($testEntityClass, $createParams, $expectedError) {
371 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
372 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
373 $this->assertTrue(is_numeric($entity->id));
374
375 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams + [
376 'entity_table' => $entity_table,
377 'entity_id' => $entity->id,
378 ]);
379 $this->assertRegExp($expectedError, $createResult['error_message']);
380 }
381
382 /**
383 * @param $testEntityClass
384 * @param $createParams
385 * @param $updateParams
386 * @param $expectedError
387 * @dataProvider badUpdateProvider
388 */
389 public function testCreateWithBadUpdate($testEntityClass, $createParams, $updateParams, $expectedError) {
390 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
391 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
392 $this->assertTrue(is_numeric($entity->id));
393
394 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams + [
395 'entity_table' => $entity_table,
396 'entity_id' => $entity->id,
397 ]);
398 $fileId = $createResult['id'];
399 $this->assertTrue(is_numeric($fileId));
400
401 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams + [
402 'id' => $fileId,
403 ]);
404 $this->assertRegExp($expectedError, $updateResult['error_message']);
405 }
406
407 /**
408 * If one submits a weird file name, it should be automatically converted
409 * to something safe.
410 */
411 public function testCreateWithWeirdName() {
412 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
413 $this->assertTrue(is_numeric($entity->id));
414
415 $createResult = $this->callAPISuccess('Attachment', 'create', [
416 'name' => self::getFilePrefix() . 'weird:na"me.txt',
417 'mime_type' => 'text/plain',
418 'description' => 'My test description',
419 'content' => 'My test content',
420 'entity_table' => 'civicrm_activity',
421 'entity_id' => $entity->id,
422 ]);
423 $fileId = $createResult['id'];
424 $this->assertTrue(is_numeric($fileId));
425 $this->assertEquals(self::getFilePrefix() . 'weird_na_me.txt', $createResult['values'][$fileId]['name']);
426 // Check for appropriate icon
427 $this->assertEquals('fa-file-text-o', $createResult['values'][$fileId]['icon']);
428 }
429
430 public function testCreateShouldSetCreatedIdAsTheLoggedInUser() {
431 $loggedInUser = $this->createLoggedInUser();
432
433 $testEntityClass = 'CRM_Activity_DAO_Activity';
434 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
435 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
436 $this->assertTrue(is_numeric($entity->id));
437
438 $createResult = $this->callAPISuccess('Attachment', 'create', [
439 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
440 'mime_type' => 'text/plain',
441 'content' => 'My test content',
442 'entity_table' => $entity_table,
443 'entity_id' => $entity->id,
444 ]);
445
446 $fileId = $createResult['id'];
447 $this->assertEquals($loggedInUser, $createResult['values'][$fileId]['created_id']);
448 }
449
450 public function testCreateShouldKeepCreatedIdEmptyIfTheresNoLoggedInUser() {
451 $testEntityClass = 'CRM_Activity_DAO_Activity';
452 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
453 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
454 $this->assertTrue(is_numeric($entity->id));
455
456 $createResult = $this->callAPISuccess('Attachment', 'create', [
457 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
458 'mime_type' => 'text/plain',
459 'content' => 'My test content',
460 'entity_table' => $entity_table,
461 'entity_id' => $entity->id,
462 ]);
463
464 $fileId = $createResult['id'];
465 $this->assertEmpty($createResult['values'][$fileId]['created_id']);
466 }
467
468 public function testCreateShouldNotUpdateTheCreatedId() {
469 $testEntityClass = 'CRM_Activity_DAO_Activity';
470 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
471 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
472 $this->assertTrue(is_numeric($entity->id));
473
474 $attachmentParams = [
475 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
476 'mime_type' => 'text/plain',
477 'description' => 'My test description',
478 'content' => 'My test content',
479 'entity_table' => $entity_table,
480 'entity_id' => $entity->id,
481 ];
482
483 $createResult = $this->callAPISuccess('Attachment', 'create', $attachmentParams);
484
485 $fileId = $createResult['id'];
486 $this->assertEmpty($createResult['values'][$fileId]['created_id']);
487
488 $attachmentParams['id'] = $fileId;
489 $attachmentParams['description'] = 'My updated description';
490
491 $loggedInUser = $this->createLoggedInUser();
492
493 $this->callAPISuccess('Attachment', 'create', $attachmentParams);
494
495 $updatedAttachment = $this->callAPISuccess('Attachment', 'get', [
496 'id' => $fileId,
497 'entity_id' => $attachmentParams['entity_id'],
498 'entity_table' => $attachmentParams['entity_table'],
499 ]);
500
501 $this->assertNotEmpty($loggedInUser);
502 $this->assertEmpty($updatedAttachment['values'][$fileId]['created_id']);
503 $this->assertEquals($attachmentParams['description'], $updatedAttachment['values'][$fileId]['description']);
504 }
505
506 /**
507 * @param $getParams
508 * @param $expectedNames
509 * @dataProvider okGetProvider
510 */
511 public function testGet($getParams, $expectedNames) {
512 foreach ([123, 456] as $entity_id) {
513 foreach (['text/plain' => '.txt', 'text/csv' => '.csv'] as $mime => $ext) {
514 $this->callAPISuccess('Attachment', 'create', [
515 'name' => self::getFilePrefix() . 'example_' . $entity_id . $ext,
516 'mime_type' => $mime,
517 'description' => 'My test description',
518 'content' => 'My test content',
519 'entity_table' => 'civicrm_activity',
520 'entity_id' => $entity_id,
521 ]);
522 }
523 }
524
525 $getResult = $this->callAPISuccess('Attachment', 'get', $getParams);
526 $actualNames = array_values(CRM_Utils_Array::collect('name', $getResult['values']));
527 // Verify the hash generated by the API is valid if we were to try and load the file.
528 foreach ($getResult['values'] as $result) {
529 $queryResult = [];
530 $parsedURl = parse_url($result['url']);
531 $parsedQuery = parse_str($parsedURl['query'], $queryResult);
532 $this->assertTrue(CRM_Core_BAO_File::validateFileHash($queryResult['fcs'], $queryResult['eid'], $queryResult['id']));
533 }
534
535 sort($actualNames);
536 sort($expectedNames);
537 $this->assertEquals($expectedNames, $actualNames);
538 }
539
540 /**
541 * @param $getParams
542 * @param $expectedError
543 * @dataProvider badGetProvider
544 */
545 public function testGetError($getParams, $expectedError) {
546 foreach ([123, 456] as $entity_id) {
547 foreach (['text/plain' => '.txt', 'text/csv' => '.csv'] as $mime => $ext) {
548 $this->callAPISuccess('Attachment', 'create', [
549 'name' => self::getFilePrefix() . 'example_' . $entity_id . $ext,
550 'mime_type' => $mime,
551 'description' => 'My test description',
552 'content' => 'My test content',
553 'entity_table' => 'civicrm_activity',
554 'entity_id' => $entity_id,
555 ]);
556 }
557 }
558
559 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
560 $this->assertRegExp($expectedError, $getResult['error_message']);
561 }
562
563 /**
564 * Take the values from a "get", make a small change, and then send
565 * the full thing back in as an update ("create"). This ensures some
566 * consistency in the acceptable formats.
567 */
568 public function testGetThenUpdate() {
569 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
570 $this->assertTrue(is_numeric($entity->id));
571
572 $createResult = $this->callAPISuccess('Attachment', 'create', [
573 'name' => self::getFilePrefix() . 'getThenUpdate.txt',
574 'mime_type' => 'text/plain',
575 'description' => 'My test description',
576 'content' => 'My test content',
577 'entity_table' => 'civicrm_activity',
578 'entity_id' => $entity->id,
579 ]);
580 $fileId = $createResult['id'];
581 $this->assertTrue(is_numeric($fileId));
582 $this->assertEquals(self::getFilePrefix() . 'getThenUpdate.txt', $createResult['values'][$fileId]['name']);
583 $this->assertAttachmentExistence(TRUE, $createResult);
584
585 $getResult = $this->callAPISuccess('Attachment', 'get', [
586 'id' => $fileId,
587 ]);
588 $this->assertTrue(is_array($getResult['values'][$fileId]));
589
590 $updateParams = $getResult['values'][$fileId];
591 $updateParams['description'] = 'new description';
592 $this->callAPISuccess('Attachment', 'create', $updateParams);
593 $this->assertAttachmentExistence(TRUE, $createResult);
594 }
595
596 /**
597 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
598 * in the DB and the filesystem.
599 */
600 public function testDeleteByID() {
601 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
602 $this->assertTrue(is_numeric($entity->id));
603
604 foreach (['first', 'second'] as $n) {
605 $createResults[$n] = $this->callAPISuccess('Attachment', 'create', [
606 'name' => self::getFilePrefix() . 'testDeleteByID.txt',
607 'mime_type' => 'text/plain',
608 'content' => 'My test content',
609 'entity_table' => 'civicrm_activity',
610 'entity_id' => $entity->id,
611 ]);
612 $this->assertTrue(is_numeric($createResults[$n]['id']));
613 $this->assertEquals(self::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
614 }
615 $this->assertAttachmentExistence(TRUE, $createResults['first']);
616 $this->assertAttachmentExistence(TRUE, $createResults['second']);
617
618 $this->callAPISuccess('Attachment', 'delete', [
619 'id' => $createResults['first']['id'],
620 ]);
621 $this->assertAttachmentExistence(FALSE, $createResults['first']);
622 $this->assertAttachmentExistence(TRUE, $createResults['second']);
623 }
624
625 /**
626 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
627 * in the DB and the filesystem.
628 */
629 public function testDeleteByEntity() {
630 // create 2 entities (keepme,delme) -- each with 2 attachments (first,second)
631 foreach (['keepme', 'delme'] as $e) {
632 $entities[$e] = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
633 $this->assertTrue(is_numeric($entities[$e]->id));
634 foreach (['first', 'second'] as $n) {
635 $createResults[$e][$n] = $this->callAPISuccess('Attachment', 'create', [
636 'name' => self::getFilePrefix() . 'testDeleteByEntity.txt',
637 'mime_type' => 'text/plain',
638 'content' => 'My test content',
639 'entity_table' => 'civicrm_activity',
640 'entity_id' => $entities[$e]->id,
641 ]);
642 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
643 }
644 }
645 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
646 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
647 $this->assertAttachmentExistence(TRUE, $createResults['delme']['first']);
648 $this->assertAttachmentExistence(TRUE, $createResults['delme']['second']);
649
650 $this->callAPISuccess('Attachment', 'delete', [
651 'entity_table' => 'civicrm_activity',
652 'entity_id' => $entities[$e]->id,
653 ]);
654 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
655 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
656 $this->assertAttachmentExistence(FALSE, $createResults['delme']['first']);
657 $this->assertAttachmentExistence(FALSE, $createResults['delme']['second']);
658 }
659
660 /**
661 * Ensure mime type is converted to appropriate icon.
662 */
663 public function testGetIcon() {
664 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
665 $this->assertTrue(is_numeric($entity->id));
666
667 $createResult = $this->callAPISuccess('Attachment', 'create', [
668 'name' => self::getFilePrefix() . 'hasIcon.docx',
669 'mime_type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
670 'description' => 'My test description',
671 'content' => 'My test content',
672 'entity_table' => 'civicrm_activity',
673 'entity_id' => $entity->id,
674 ]);
675 $fileId = $createResult['id'];
676 $this->assertEquals('fa-file-word-o', $createResult['values'][$fileId]['icon']);
677
678 $createResult = $this->callAPISuccess('Attachment', 'create', [
679 'name' => self::getFilePrefix() . 'hasIcon.jpg',
680 'mime_type' => 'image/jpg',
681 'description' => 'My test description',
682 'content' => 'My test content',
683 'entity_table' => 'civicrm_activity',
684 'entity_id' => $entity->id,
685 ]);
686 $fileId = $createResult['id'];
687 $this->assertEquals('fa-file-image-o', $createResult['values'][$fileId]['icon']);
688 }
689
690 /**
691 * @param $name
692 * @return string
693 */
694 protected function tmpFile($name) {
695 $tmpDir = sys_get_temp_dir();
696 $this->assertTrue($tmpDir && is_dir($tmpDir), 'Tmp dir must exist: ' . $tmpDir);
697 return $tmpDir . '/' . self::getFilePrefix() . $name;
698 }
699
700 protected function cleanupFiles() {
701 $config = CRM_Core_Config::singleton();
702 $dirs = [
703 sys_get_temp_dir(),
704 $config->customFileUploadDir,
705 ];
706 foreach ($dirs as $dir) {
707 $files = (array) glob($dir . "/" . self::getFilePrefix() . "*");
708 foreach ($files as $file) {
709 unlink($file);
710 }
711
712 }
713 }
714
715 }