3 * api_v3_AttachmentTest
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 $
11 * This file is part of CiviCRM
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.
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.
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/>.
29 * Test for the Attachment API
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contact
35 class api_v3_AttachmentTest
extends CiviUnitTestCase
{
36 protected static $filePrefix = NULL;
41 public static function getFilePrefix() {
42 if (!self
::$filePrefix) {
43 self
::$filePrefix = "test_" . CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
) . '_';
45 return self
::$filePrefix;
49 protected function setUp() {
51 $this->useTransaction(TRUE);
53 $this->cleanupFiles();
54 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
57 protected function tearDown() {
59 $this->cleanupFiles();
66 public function okCreateProvider() {
67 $cases = array(); // array($entityClass, $createParams, $expectedContent)
70 'CRM_Activity_DAO_Activity',
72 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
73 'mime_type' => 'text/plain',
74 'description' => 'My test description',
75 'content' => 'My test content',
81 'CRM_Activity_DAO_Activity',
83 'name' => self
::getFilePrefix() . 'exampleWithEmptyContent.txt',
84 'mime_type' => 'text/plain',
85 'description' => 'My test description',
92 'CRM_Activity_DAO_Activity',
94 'name' => self
::getFilePrefix() . 'exampleFromMove.txt',
95 'mime_type' => 'text/plain',
96 'description' => 'My test description',
98 'move-file' => $this->tmpFile('mytest.txt'),
101 'This comes from a file',
110 public function badCreateProvider() {
111 $cases = array(); // array($entityClass, $createParams, $expectedError)
114 'CRM_Activity_DAO_Activity',
117 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
118 'mime_type' => 'text/plain',
119 'description' => 'My test description',
120 'content' => 'My test content',
125 'CRM_Activity_DAO_Activity',
127 'name' => self
::getFilePrefix() . 'failedExample.txt',
128 'mime_type' => 'text/plain',
129 'description' => 'My test description',
131 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
134 'CRM_Activity_DAO_Activity',
136 'name' => self
::getFilePrefix() . 'failedExample.txt',
137 'mime_type' => 'text/plain',
138 'description' => 'My test description',
139 'content' => 'too much content',
141 'move-file' => $this->tmpFile('too-much.txt'),
144 "/'content' and 'options.move-file' are mutually exclusive/",
147 'CRM_Activity_DAO_Activity',
149 'name' => 'inv/alid.txt',
150 'mime_type' => 'text/plain',
151 'description' => 'My test description',
152 'content' => 'My test content',
157 'CRM_Core_DAO_Domain',
159 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
160 'mime_type' => 'text/plain',
161 'description' => 'My test description',
162 'content' => 'My test content',
164 "/Unrecognized target entity/",
173 public function badUpdateProvider() {
174 $cases = array(); // array($entityClass, $createParams, $updateParams, $expectedError)
176 $readOnlyFields = array(
177 'name' => 'newname.txt',
178 'entity_table' => 'civicrm_domain',
180 'upload_date' => '2010-11-12 13:14:15',
182 foreach ($readOnlyFields as $readOnlyField => $newValue) {
184 'CRM_Activity_DAO_Activity',
186 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
187 'mime_type' => 'text/plain',
188 'description' => 'My test description',
189 'content' => 'My test content',
192 'check_permissions' => 1,
193 $readOnlyField => $newValue,
195 "/Cannot modify $readOnlyField/",
205 public function okGetProvider() {
206 $cases = array(); // array($getParams, $expectedNames)
208 // Each search runs in a DB which contains these attachments:
209 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
210 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
212 // NOTE: Searching across multiple records (w/o entity_id) is currently
213 // prohibited by DynamicFKAuthorization. The technique used to authorize requests
214 // does not adapt well to such searches.
217 // array('entity_table' => 'civicrm_activity'),
219 // self::getFilePrefix() . 'example_123.csv',
220 // self::getFilePrefix() . 'example_123.txt',
221 // self::getFilePrefix() . 'example_456.csv',
222 // self::getFilePrefix() . 'example_456.txt',
226 // array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
227 // array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_456.txt'),
231 array('entity_table' => 'civicrm_activity', 'entity_id' => '123'),
232 array(self
::getFilePrefix() . 'example_123.txt', self
::getFilePrefix() . 'example_123.csv'),
235 array('entity_table' => 'civicrm_activity', 'entity_id' => '456'),
236 array(self
::getFilePrefix() . 'example_456.txt', self
::getFilePrefix() . 'example_456.csv'),
239 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/csv'),
240 array(self
::getFilePrefix() . 'example_456.csv'),
243 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/html'),
247 array('entity_table' => 'civicrm_activity', 'entity_id' => '999'),
257 public function badGetProvider() {
258 $cases = array(); // array($getParams, $expectedNames)
260 // Each search runs in a DB which contains these attachments:
261 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
262 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
265 array('check_permissions' => 1, 'mime_type' => 'text/plain'),
266 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
269 array('check_permissions' => 1, 'entity_id' => '123'),
270 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
273 array('check_permissions' => 1),
274 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
277 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'name' => 'example_456.csv'),
278 "/Get by name is not currently supported/",
281 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'content' => 'test'),
282 "/Get by content is not currently supported/",
285 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'path' => '/home/foo'),
286 "/Get by path is not currently supported/",
289 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'url' => '/index.php'),
290 "/Get by url is not currently supported/",
297 * Create an attachment using "content" and then "get" the attachment.
299 * @param string $testEntityClass
300 * E.g. "CRM_Core_DAO_Activity".
301 * @param array $createParams
302 * @param string $expectedContent
303 * @dataProvider okCreateProvider
305 public function testCreate($testEntityClass, $createParams, $expectedContent) {
306 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
307 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
308 $this->assertTrue(is_numeric($entity->id
));
310 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
311 'entity_table' => $entity_table,
312 'entity_id' => $entity->id
,
314 $fileId = $createResult['id'];
315 $this->assertTrue(is_numeric($fileId));
316 $this->assertEquals($entity_table, $createResult['values'][$fileId]['entity_table']);
317 $this->assertEquals($entity->id
, $createResult['values'][$fileId]['entity_id']);
318 $this->assertEquals('My test description', $createResult['values'][$fileId]['description']);
319 $this->assertRegExp('/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/', $createResult['values'][$fileId]['upload_date']);
320 $this->assertTrue(!isset($createResult['values'][$fileId]['content']));
321 $this->assertTrue(!empty($createResult['values'][$fileId]['url']));
322 $this->assertAttachmentExistence(TRUE, $createResult);
324 $getResult = $this->callAPISuccess('Attachment', 'get', array(
325 'entity_table' => $entity_table,
326 'entity_id' => $entity->id
,
328 $this->assertEquals(1, $getResult['count']);
329 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
330 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
332 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
334 $getResult2 = $this->callAPISuccess('Attachment', 'get', array(
335 'entity_table' => $entity_table,
336 'entity_id' => $entity->id
,
337 'return' => array('content'),
339 $this->assertEquals($expectedContent, $getResult2['values'][$fileId]['content']);
340 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
341 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
346 * @param $testEntityClass
347 * @param $createParams
348 * @param $expectedError
349 * @dataProvider badCreateProvider
351 public function testCreateFailure($testEntityClass, $createParams, $expectedError) {
352 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
353 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
354 $this->assertTrue(is_numeric($entity->id
));
356 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams +
array(
357 'entity_table' => $entity_table,
358 'entity_id' => $entity->id
,
360 $this->assertRegExp($expectedError, $createResult['error_message']);
364 * @param $testEntityClass
365 * @param $createParams
366 * @param $updateParams
367 * @param $expectedError
368 * @dataProvider badUpdateProvider
370 public function testCreateWithBadUpdate($testEntityClass, $createParams, $updateParams, $expectedError) {
371 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
372 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
373 $this->assertTrue(is_numeric($entity->id
));
375 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
376 'entity_table' => $entity_table,
377 'entity_id' => $entity->id
,
379 $fileId = $createResult['id'];
380 $this->assertTrue(is_numeric($fileId));
382 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams +
array(
385 $this->assertRegExp($expectedError, $updateResult['error_message']);
389 * If one submits a weird file name, it should be automatically converted
392 public function testCreateWithWeirdName() {
393 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
394 $this->assertTrue(is_numeric($entity->id
));
396 $createResult = $this->callAPISuccess('Attachment', 'create', array(
397 'name' => self
::getFilePrefix() . 'weird:na"me.txt',
398 'mime_type' => 'text/plain',
399 'description' => 'My test description',
400 'content' => 'My test content',
401 'entity_table' => 'civicrm_activity',
402 'entity_id' => $entity->id
,
404 $fileId = $createResult['id'];
405 $this->assertTrue(is_numeric($fileId));
406 $this->assertEquals(self
::getFilePrefix() . 'weird_na_me.txt', $createResult['values'][$fileId]['name']);
407 // Check for appropriate icon
408 $this->assertEquals('fa-file-text-o', $createResult['values'][$fileId]['icon']);
411 public function testCreateShouldSetCreatedIdAsTheLoggedInUser() {
412 $loggedInUser = $this->createLoggedInUser();
414 $testEntityClass = 'CRM_Activity_DAO_Activity';
415 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
416 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
417 $this->assertTrue(is_numeric($entity->id
));
419 $createResult = $this->callAPISuccess('Attachment', 'create', array(
420 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
421 'mime_type' => 'text/plain',
422 'content' => 'My test content',
423 'entity_table' => $entity_table,
424 'entity_id' => $entity->id
,
427 $fileId = $createResult['id'];
428 $this->assertEquals($loggedInUser, $createResult['values'][$fileId]['created_id']);
431 public function testCreateShouldKeepCreatedIdEmptyIfTheresNoLoggedInUser() {
432 $testEntityClass = 'CRM_Activity_DAO_Activity';
433 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
434 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
435 $this->assertTrue(is_numeric($entity->id
));
437 $createResult = $this->callAPISuccess('Attachment', 'create', array(
438 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
439 'mime_type' => 'text/plain',
440 'content' => 'My test content',
441 'entity_table' => $entity_table,
442 'entity_id' => $entity->id
,
445 $fileId = $createResult['id'];
446 $this->assertEmpty($createResult['values'][$fileId]['created_id']);
449 public function testCreateShouldNotUpdateTheCreatedId() {
450 $testEntityClass = 'CRM_Activity_DAO_Activity';
451 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
452 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
453 $this->assertTrue(is_numeric($entity->id
));
455 $attachmentParams = array(
456 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
457 'mime_type' => 'text/plain',
458 'description' => 'My test description',
459 'content' => 'My test content',
460 'entity_table' => $entity_table,
461 'entity_id' => $entity->id
,
464 $createResult = $this->callAPISuccess('Attachment', 'create', $attachmentParams);
466 $fileId = $createResult['id'];
467 $this->assertEmpty($createResult['values'][$fileId]['created_id']);
469 $attachmentParams['id'] = $fileId;
470 $attachmentParams['description'] = 'My updated description';
472 $loggedInUser = $this->createLoggedInUser();
474 $this->callAPISuccess('Attachment', 'create', $attachmentParams);
476 $updatedAttachment = $this->callAPISuccess('Attachment', 'get', array(
478 'entity_id' => $attachmentParams['entity_id'],
479 'entity_table' => $attachmentParams['entity_table'],
482 $this->assertNotEmpty($loggedInUser);
483 $this->assertEmpty($updatedAttachment['values'][$fileId]['created_id']);
484 $this->assertEquals($attachmentParams['description'], $updatedAttachment['values'][$fileId]['description']);
489 * @param $expectedNames
490 * @dataProvider okGetProvider
492 public function testGet($getParams, $expectedNames) {
493 foreach (array(123, 456) as $entity_id) {
494 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
495 $this->callAPISuccess('Attachment', 'create', array(
496 'name' => self
::getFilePrefix() . 'example_' . $entity_id . $ext,
497 'mime_type' => $mime,
498 'description' => 'My test description',
499 'content' => 'My test content',
500 'entity_table' => 'civicrm_activity',
501 'entity_id' => $entity_id,
506 $getResult = $this->callAPISuccess('Attachment', 'get', $getParams);
507 $actualNames = array_values(CRM_Utils_Array
::collect('name', $getResult['values']));
509 sort($expectedNames);
510 $this->assertEquals($expectedNames, $actualNames);
515 * @param $expectedError
516 * @dataProvider badGetProvider
518 public function testGetError($getParams, $expectedError) {
519 foreach (array(123, 456) as $entity_id) {
520 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
521 $this->callAPISuccess('Attachment', 'create', array(
522 'name' => self
::getFilePrefix() . 'example_' . $entity_id . $ext,
523 'mime_type' => $mime,
524 'description' => 'My test description',
525 'content' => 'My test content',
526 'entity_table' => 'civicrm_activity',
527 'entity_id' => $entity_id,
532 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
533 $this->assertRegExp($expectedError, $getResult['error_message']);
537 * Take the values from a "get", make a small change, and then send
538 * the full thing back in as an update ("create"). This ensures some
539 * consistency in the acceptable formats.
541 public function testGetThenUpdate() {
542 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
543 $this->assertTrue(is_numeric($entity->id
));
545 $createResult = $this->callAPISuccess('Attachment', 'create', array(
546 'name' => self
::getFilePrefix() . 'getThenUpdate.txt',
547 'mime_type' => 'text/plain',
548 'description' => 'My test description',
549 'content' => 'My test content',
550 'entity_table' => 'civicrm_activity',
551 'entity_id' => $entity->id
,
553 $fileId = $createResult['id'];
554 $this->assertTrue(is_numeric($fileId));
555 $this->assertEquals(self
::getFilePrefix() . 'getThenUpdate.txt', $createResult['values'][$fileId]['name']);
556 $this->assertAttachmentExistence(TRUE, $createResult);
558 $getResult = $this->callAPISuccess('Attachment', 'get', array(
561 $this->assertTrue(is_array($getResult['values'][$fileId]));
563 $updateParams = $getResult['values'][$fileId];
564 $updateParams['description'] = 'new description';
565 $this->callAPISuccess('Attachment', 'create', $updateParams);
566 $this->assertAttachmentExistence(TRUE, $createResult);
570 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
571 * in the DB and the filesystem.
573 public function testDeleteByID() {
574 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
575 $this->assertTrue(is_numeric($entity->id
));
577 foreach (array('first', 'second') as $n) {
578 $createResults[$n] = $this->callAPISuccess('Attachment', 'create', array(
579 'name' => self
::getFilePrefix() . 'testDeleteByID.txt',
580 'mime_type' => 'text/plain',
581 'content' => 'My test content',
582 'entity_table' => 'civicrm_activity',
583 'entity_id' => $entity->id
,
585 $this->assertTrue(is_numeric($createResults[$n]['id']));
586 $this->assertEquals(self
::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
588 $this->assertAttachmentExistence(TRUE, $createResults['first']);
589 $this->assertAttachmentExistence(TRUE, $createResults['second']);
591 $this->callAPISuccess('Attachment', 'delete', array(
592 'id' => $createResults['first']['id'],
594 $this->assertAttachmentExistence(FALSE, $createResults['first']);
595 $this->assertAttachmentExistence(TRUE, $createResults['second']);
599 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
600 * in the DB and the filesystem.
602 public function testDeleteByEntity() {
603 // create 2 entities (keepme,delme) -- each with 2 attachments (first,second)
604 foreach (array('keepme', 'delme') as $e) {
605 $entities[$e] = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
606 $this->assertTrue(is_numeric($entities[$e]->id
));
607 foreach (array('first', 'second') as $n) {
608 $createResults[$e][$n] = $this->callAPISuccess('Attachment', 'create', array(
609 'name' => self
::getFilePrefix() . 'testDeleteByEntity.txt',
610 'mime_type' => 'text/plain',
611 'content' => 'My test content',
612 'entity_table' => 'civicrm_activity',
613 'entity_id' => $entities[$e]->id
,
615 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
618 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
619 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
620 $this->assertAttachmentExistence(TRUE, $createResults['delme']['first']);
621 $this->assertAttachmentExistence(TRUE, $createResults['delme']['second']);
623 $this->callAPISuccess('Attachment', 'delete', array(
624 'entity_table' => 'civicrm_activity',
625 'entity_id' => $entities[$e]->id
,
627 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
628 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
629 $this->assertAttachmentExistence(FALSE, $createResults['delme']['first']);
630 $this->assertAttachmentExistence(FALSE, $createResults['delme']['second']);
634 * Ensure mime type is converted to appropriate icon.
636 public function testGetIcon() {
637 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
638 $this->assertTrue(is_numeric($entity->id
));
640 $createResult = $this->callAPISuccess('Attachment', 'create', array(
641 'name' => self
::getFilePrefix() . 'hasIcon.docx',
642 'mime_type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
643 'description' => 'My test description',
644 'content' => 'My test content',
645 'entity_table' => 'civicrm_activity',
646 'entity_id' => $entity->id
,
648 $fileId = $createResult['id'];
649 $this->assertEquals('fa-file-word-o', $createResult['values'][$fileId]['icon']);
651 $createResult = $this->callAPISuccess('Attachment', 'create', array(
652 'name' => self
::getFilePrefix() . 'hasIcon.jpg',
653 'mime_type' => 'image/jpg',
654 'description' => 'My test description',
655 'content' => 'My test content',
656 'entity_table' => 'civicrm_activity',
657 'entity_id' => $entity->id
,
659 $fileId = $createResult['id'];
660 $this->assertEquals('fa-file-image-o', $createResult['values'][$fileId]['icon']);
667 protected function tmpFile($name) {
668 $tmpDir = sys_get_temp_dir();
669 $this->assertTrue($tmpDir && is_dir($tmpDir), 'Tmp dir must exist: ' . $tmpDir);
670 return $tmpDir . '/' . self
::getFilePrefix() . $name;
673 protected function cleanupFiles() {
674 $config = CRM_Core_Config
::singleton();
677 $config->customFileUploadDir
,
679 foreach ($dirs as $dir) {
680 $files = (array) glob($dir . "/" . self
::getFilePrefix() . "*");
681 foreach ($files as $file) {