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