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;
48 protected function setUp() {
50 $this->useTransaction(TRUE);
52 $this->cleanupFiles();
53 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
56 protected function tearDown() {
58 $this->cleanupFiles();
65 public function okCreateProvider() {
66 // 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 // array($entityClass, $createParams, $expectedError)
115 'CRM_Activity_DAO_Activity',
118 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
119 'mime_type' => 'text/plain',
120 'description' => 'My test description',
121 'content' => 'My test content',
126 'CRM_Activity_DAO_Activity',
128 'name' => self
::getFilePrefix() . 'failedExample.txt',
129 'mime_type' => 'text/plain',
130 'description' => 'My test description',
132 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
135 'CRM_Activity_DAO_Activity',
137 'name' => self
::getFilePrefix() . 'failedExample.txt',
138 'mime_type' => 'text/plain',
139 'description' => 'My test description',
140 'content' => 'too much content',
142 'move-file' => $this->tmpFile('too-much.txt'),
145 "/'content' and 'options.move-file' are mutually exclusive/",
148 'CRM_Activity_DAO_Activity',
150 'name' => 'inv/alid.txt',
151 'mime_type' => 'text/plain',
152 'description' => 'My test description',
153 'content' => 'My test content',
158 'CRM_Core_DAO_Domain',
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,
166 "/Unrecognized target entity/",
175 public function badUpdateProvider() {
176 // array($entityClass, $createParams, $updateParams, $expectedError)
180 'name' => 'newname.txt',
181 'entity_table' => 'civicrm_domain',
183 'upload_date' => '2010-11-12 13:14:15',
185 foreach ($readOnlyFields as $readOnlyField => $newValue) {
187 'CRM_Activity_DAO_Activity',
189 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
190 'mime_type' => 'text/plain',
191 'description' => 'My test description',
192 'content' => 'My test content',
195 'check_permissions' => 1,
196 $readOnlyField => $newValue,
198 "/Cannot modify $readOnlyField/",
208 public function okGetProvider() {
209 // array($getParams, $expectedNames)
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)
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.
221 // array('entity_table' => 'civicrm_activity'),
223 // self::getFilePrefix() . 'example_123.csv',
224 // self::getFilePrefix() . 'example_123.txt',
225 // self::getFilePrefix() . 'example_456.csv',
226 // self::getFilePrefix() . 'example_456.txt',
230 // array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
231 // array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_456.txt'),
235 ['entity_table' => 'civicrm_activity', 'entity_id' => '123'],
236 [self
::getFilePrefix() . 'example_123.txt', self
::getFilePrefix() . 'example_123.csv'],
239 ['entity_table' => 'civicrm_activity', 'entity_id' => '456'],
240 [self
::getFilePrefix() . 'example_456.txt', self
::getFilePrefix() . 'example_456.csv'],
243 ['entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/csv'],
244 [self
::getFilePrefix() . 'example_456.csv'],
247 ['entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/html'],
251 ['entity_table' => 'civicrm_activity', 'entity_id' => '999'],
261 public function badGetProvider() {
262 // array($getParams, $expectedNames)
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)
270 ['check_permissions' => 1, 'mime_type' => 'text/plain'],
271 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
274 ['check_permissions' => 1, 'entity_id' => '123'],
275 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
278 ['check_permissions' => 1],
279 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
282 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'name' => 'example_456.csv'],
283 "/Get by name is not currently supported/",
286 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'content' => 'test'],
287 "/Get by content is not currently supported/",
290 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'path' => '/home/foo'],
291 "/Get by path is not currently supported/",
294 ['entity_table' => 'civicrm_activity', 'entity_id' => '123', 'url' => '/index.php'],
295 "/Get by url is not currently supported/",
302 * Create an attachment using "content" and then "get" the attachment.
304 * @param string $testEntityClass
305 * E.g. "CRM_Core_DAO_Activity".
306 * @param array $createParams
307 * @param string $expectedContent
308 * @dataProvider okCreateProvider
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
));
315 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
[
316 'entity_table' => $entity_table,
317 'entity_id' => $entity->id
,
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);
329 $getResult = $this->callAPISuccess('Attachment', 'get', [
330 'entity_table' => $entity_table,
331 'entity_id' => $entity->id
,
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);
341 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
344 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
346 $getResult2 = $this->callAPISuccess('Attachment', 'get', [
347 'entity_table' => $entity_table,
348 'entity_id' => $entity->id
,
349 'return' => ['content'],
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");
358 * @param $testEntityClass
359 * @param $createParams
360 * @param $expectedError
361 * @dataProvider badCreateProvider
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
));
368 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams +
[
369 'entity_table' => $entity_table,
370 'entity_id' => $entity->id
,
372 $this->assertRegExp($expectedError, $createResult['error_message']);
376 * @param $testEntityClass
377 * @param $createParams
378 * @param $updateParams
379 * @param $expectedError
380 * @dataProvider badUpdateProvider
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
));
387 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
[
388 'entity_table' => $entity_table,
389 'entity_id' => $entity->id
,
391 $fileId = $createResult['id'];
392 $this->assertTrue(is_numeric($fileId));
394 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams +
[
397 $this->assertRegExp($expectedError, $updateResult['error_message']);
401 * If one submits a weird file name, it should be automatically converted
404 public function testCreateWithWeirdName() {
405 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
406 $this->assertTrue(is_numeric($entity->id
));
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
,
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']);
423 public function testCreateShouldSetCreatedIdAsTheLoggedInUser() {
424 $loggedInUser = $this->createLoggedInUser();
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
));
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
,
439 $fileId = $createResult['id'];
440 $this->assertEquals($loggedInUser, $createResult['values'][$fileId]['created_id']);
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
));
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
,
457 $fileId = $createResult['id'];
458 $this->assertEmpty($createResult['values'][$fileId]['created_id']);
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
));
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
,
476 $createResult = $this->callAPISuccess('Attachment', 'create', $attachmentParams);
478 $fileId = $createResult['id'];
479 $this->assertEmpty($createResult['values'][$fileId]['created_id']);
481 $attachmentParams['id'] = $fileId;
482 $attachmentParams['description'] = 'My updated description';
484 $loggedInUser = $this->createLoggedInUser();
486 $this->callAPISuccess('Attachment', 'create', $attachmentParams);
488 $updatedAttachment = $this->callAPISuccess('Attachment', 'get', [
490 'entity_id' => $attachmentParams['entity_id'],
491 'entity_table' => $attachmentParams['entity_table'],
494 $this->assertNotEmpty($loggedInUser);
495 $this->assertEmpty($updatedAttachment['values'][$fileId]['created_id']);
496 $this->assertEquals($attachmentParams['description'], $updatedAttachment['values'][$fileId]['description']);
501 * @param $expectedNames
502 * @dataProvider okGetProvider
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,
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) {
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']));
529 sort($expectedNames);
530 $this->assertEquals($expectedNames, $actualNames);
535 * @param $expectedError
536 * @dataProvider badGetProvider
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,
552 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
553 $this->assertRegExp($expectedError, $getResult['error_message']);
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.
561 public function testGetThenUpdate() {
562 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
563 $this->assertTrue(is_numeric($entity->id
));
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
,
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);
578 $getResult = $this->callAPISuccess('Attachment', 'get', [
581 $this->assertTrue(is_array($getResult['values'][$fileId]));
583 $updateParams = $getResult['values'][$fileId];
584 $updateParams['description'] = 'new description';
585 $this->callAPISuccess('Attachment', 'create', $updateParams);
586 $this->assertAttachmentExistence(TRUE, $createResult);
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.
593 public function testDeleteByID() {
594 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
595 $this->assertTrue(is_numeric($entity->id
));
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
,
605 $this->assertTrue(is_numeric($createResults[$n]['id']));
606 $this->assertEquals(self
::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
608 $this->assertAttachmentExistence(TRUE, $createResults['first']);
609 $this->assertAttachmentExistence(TRUE, $createResults['second']);
611 $this->callAPISuccess('Attachment', 'delete', [
612 'id' => $createResults['first']['id'],
614 $this->assertAttachmentExistence(FALSE, $createResults['first']);
615 $this->assertAttachmentExistence(TRUE, $createResults['second']);
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.
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
,
635 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
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']);
643 $this->callAPISuccess('Attachment', 'delete', [
644 'entity_table' => 'civicrm_activity',
645 'entity_id' => $entities[$e]->id
,
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']);
654 * Ensure mime type is converted to appropriate icon.
656 public function testGetIcon() {
657 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
658 $this->assertTrue(is_numeric($entity->id
));
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
,
668 $fileId = $createResult['id'];
669 $this->assertEquals('fa-file-word-o', $createResult['values'][$fileId]['icon']);
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
,
679 $fileId = $createResult['id'];
680 $this->assertEquals('fa-file-image-o', $createResult['values'][$fileId]['icon']);
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;
693 protected function cleanupFiles() {
694 $config = CRM_Core_Config
::singleton();
697 $config->customFileUploadDir
,
699 foreach ($dirs as $dir) {
700 $files = (array) glob($dir . "/" . self
::getFilePrefix() . "*");
701 foreach ($files as $file) {