Merge pull request #7895 from cividesk/CRM-18130-master
[civicrm-core.git] / tests / phpunit / api / v3 / AttachmentTest.php
CommitLineData
56154d36
TO
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
56154d36
TO
28/**
29 * Test for the Attachment API
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contact
acb109b7 33 * @group headless
56154d36
TO
34 */
35class api_v3_AttachmentTest extends CiviUnitTestCase {
36 protected static $filePrefix = NULL;
37
f0be539a
EM
38 /**
39 * @return string
40 */
56154d36
TO
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
49 protected function setUp() {
50 parent::setUp();
51 $this->useTransaction(TRUE);
52
53 $this->cleanupFiles();
54 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
55 }
56
57 protected function tearDown() {
58 parent::tearDown();
59 $this->cleanupFiles();
048222df 60 \Civi::reset();
56154d36
TO
61 }
62
f0be539a
EM
63 /**
64 * @return array
65 */
56154d36
TO
66 public function okCreateProvider() {
67 $cases = array(); // array($entityClass, $createParams, $expectedContent)
68
69 $cases[] = array(
70 'CRM_Activity_DAO_Activity',
71 array(
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[] = array(
81 'CRM_Activity_DAO_Activity',
82 array(
83 'name' => self::getFilePrefix() . 'exampleWithEmptyContent.txt',
84 'mime_type' => 'text/plain',
85 'description' => 'My test description',
86 'content' => '',
87 ),
88 '',
89 );
90
91 $cases[] = array(
92 'CRM_Activity_DAO_Activity',
93 array(
94 'name' => self::getFilePrefix() . 'exampleFromMove.txt',
95 'mime_type' => 'text/plain',
96 'description' => 'My test description',
97 'options' => array(
98 'move-file' => $this->tmpFile('mytest.txt'),
21dfd5f5 99 ),
56154d36
TO
100 ),
101 'This comes from a file',
102 );
103
104 return $cases;
105 }
106
f0be539a
EM
107 /**
108 * @return array
109 */
56154d36
TO
110 public function badCreateProvider() {
111 $cases = array(); // array($entityClass, $createParams, $expectedError)
112
113 $cases[] = array(
114 'CRM_Activity_DAO_Activity',
115 array(
116 'id' => 12345,
117 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
118 'mime_type' => 'text/plain',
119 'description' => 'My test description',
120 'content' => 'My test content',
121 ),
122 '/Invalid ID/',
123 );
124 $cases[] = array(
125 'CRM_Activity_DAO_Activity',
126 array(
127 'name' => self::getFilePrefix() . 'failedExample.txt',
128 'mime_type' => 'text/plain',
129 'description' => 'My test description',
130 ),
131 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
132 );
133 $cases[] = array(
134 'CRM_Activity_DAO_Activity',
135 array(
136 'name' => self::getFilePrefix() . 'failedExample.txt',
137 'mime_type' => 'text/plain',
138 'description' => 'My test description',
139 'content' => 'too much content',
140 'options' => array(
21dfd5f5 141 'move-file' => $this->tmpFile('too-much.txt'),
56154d36
TO
142 ),
143 ),
144 "/'content' and 'options.move-file' are mutually exclusive/",
145 );
146 $cases[] = array(
147 'CRM_Activity_DAO_Activity',
148 array(
149 'name' => 'inv/alid.txt',
150 'mime_type' => 'text/plain',
151 'description' => 'My test description',
152 'content' => 'My test content',
153 ),
154 "/Malformed name/",
155 );
156 $cases[] = array(
157 'CRM_Core_DAO_Domain',
158 array(
159 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
160 'mime_type' => 'text/plain',
161 'description' => 'My test description',
162 'content' => 'My test content',
163 ),
164 "/Unrecognized target entity/",
165 );
166
167 return $cases;
168 }
169
f0be539a
EM
170 /**
171 * @return array
172 */
56154d36
TO
173 public function badUpdateProvider() {
174 $cases = array(); // array($entityClass, $createParams, $updateParams, $expectedError)
175
176 $readOnlyFields = array(
177 'name' => 'newname.txt',
178 'entity_table' => 'civicrm_domain',
179 'entity_id' => 5,
180 'upload_date' => '2010-11-12 13:14:15',
181 );
182 foreach ($readOnlyFields as $readOnlyField => $newValue) {
183 $cases[] = array(
184 'CRM_Activity_DAO_Activity',
185 array(
186 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
187 'mime_type' => 'text/plain',
188 'description' => 'My test description',
189 'content' => 'My test content',
190 ),
191 array(
192 'check_permissions' => 1,
193 $readOnlyField => $newValue,
194 ),
21dfd5f5 195 "/Cannot modify $readOnlyField/",
56154d36
TO
196 );
197 }
198
199 return $cases;
200 }
201
f0be539a
EM
202 /**
203 * @return array
204 */
56154d36
TO
205 public function okGetProvider() {
206 $cases = array(); // array($getParams, $expectedNames)
207
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)
211
e6b62a18
TO
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.
215
216 //$cases[] = array(
217 // array('entity_table' => 'civicrm_activity'),
218 // array(
219 // self::getFilePrefix() . 'example_123.csv',
220 // self::getFilePrefix() . 'example_123.txt',
221 // self::getFilePrefix() . 'example_456.csv',
222 // self::getFilePrefix() . 'example_456.txt',
223 // ),
224 //);
225 //$cases[] = array(
226 // array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
227 // array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_456.txt'),
228 //);
229
56154d36
TO
230 $cases[] = array(
231 array('entity_table' => 'civicrm_activity', 'entity_id' => '123'),
232 array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_123.csv'),
233 );
234 $cases[] = array(
235 array('entity_table' => 'civicrm_activity', 'entity_id' => '456'),
236 array(self::getFilePrefix() . 'example_456.txt', self::getFilePrefix() . 'example_456.csv'),
237 );
238 $cases[] = array(
239 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/csv'),
240 array(self::getFilePrefix() . 'example_456.csv'),
241 );
242 $cases[] = array(
243 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/html'),
244 array(),
245 );
246 $cases[] = array(
247 array('entity_table' => 'civicrm_activity', 'entity_id' => '999'),
248 array(),
249 );
250
251 return $cases;
252 }
253
f0be539a
EM
254 /**
255 * @return array
256 */
56154d36
TO
257 public function badGetProvider() {
258 $cases = array(); // array($getParams, $expectedNames)
259
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)
263
264 $cases[] = array(
265 array('check_permissions' => 1, 'mime_type' => 'text/plain'),
266 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
267 );
268 $cases[] = array(
269 array('check_permissions' => 1, 'entity_id' => '123'),
270 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
271 );
272 $cases[] = array(
273 array('check_permissions' => 1),
92915c55 274 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
56154d36
TO
275 );
276 $cases[] = array(
e6b62a18 277 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'name' => 'example_456.csv'),
56154d36
TO
278 "/Get by name is not currently supported/",
279 );
280 $cases[] = array(
e6b62a18 281 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'content' => 'test'),
56154d36
TO
282 "/Get by content is not currently supported/",
283 );
284 $cases[] = array(
e6b62a18 285 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'path' => '/home/foo'),
56154d36
TO
286 "/Get by path is not currently supported/",
287 );
288 $cases[] = array(
e6b62a18 289 array('entity_table' => 'civicrm_activity', 'entity_id' => '123', 'url' => '/index.php'),
56154d36
TO
290 "/Get by url is not currently supported/",
291 );
292
293 return $cases;
294 }
295
296 /**
fe482240 297 * Create an attachment using "content" and then "get" the attachment.
56154d36 298 *
e16033b4
TO
299 * @param string $testEntityClass
300 * E.g. "CRM_Core_DAO_Activity".
56154d36
TO
301 * @param array $createParams
302 * @param string $expectedContent
303 * @dataProvider okCreateProvider
304 */
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));
309
310 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams + array(
311 'entity_table' => $entity_table,
312 'entity_id' => $entity->id,
313 ));
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);
323
324 $getResult = $this->callAPISuccess('Attachment', 'get', array(
325 'entity_table' => $entity_table,
326 'entity_id' => $entity->id,
327 ));
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");
331 }
332 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
333
334 $getResult2 = $this->callAPISuccess('Attachment', 'get', array(
335 'entity_table' => $entity_table,
336 'entity_id' => $entity->id,
337 'return' => array('content'),
338 ));
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");
342 }
343 }
344
345 /**
346 * @param $testEntityClass
347 * @param $createParams
348 * @param $expectedError
349 * @dataProvider badCreateProvider
350 */
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));
355
356 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams + array(
357 'entity_table' => $entity_table,
358 'entity_id' => $entity->id,
359 ));
360 $this->assertRegExp($expectedError, $createResult['error_message']);
361 }
362
363 /**
364 * @param $testEntityClass
365 * @param $createParams
366 * @param $updateParams
367 * @param $expectedError
368 * @dataProvider badUpdateProvider
369 */
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));
374
375 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams + array(
376 'entity_table' => $entity_table,
377 'entity_id' => $entity->id,
378 ));
379 $fileId = $createResult['id'];
380 $this->assertTrue(is_numeric($fileId));
381
382 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams + array(
383 'id' => $fileId,
384 ));
385 $this->assertRegExp($expectedError, $updateResult['error_message']);
386 }
387
388 /**
389 * If one submits a weird file name, it should be automatically converted
390 * to something safe.
391 */
392 public function testCreateWithWeirdName() {
393 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
394 $this->assertTrue(is_numeric($entity->id));
395
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,
403 ));
404 $fileId = $createResult['id'];
405 $this->assertTrue(is_numeric($fileId));
406 $this->assertEquals(self::getFilePrefix() . 'weird_na_me.txt', $createResult['values'][$fileId]['name']);
407 }
408
409 /**
410 * @param $getParams
411 * @param $expectedNames
412 * @dataProvider okGetProvider
413 */
414 public function testGet($getParams, $expectedNames) {
415 foreach (array(123, 456) as $entity_id) {
416 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
417 $this->callAPISuccess('Attachment', 'create', array(
418 'name' => self::getFilePrefix() . 'example_' . $entity_id . $ext,
419 'mime_type' => $mime,
420 'description' => 'My test description',
421 'content' => 'My test content',
422 'entity_table' => 'civicrm_activity',
423 'entity_id' => $entity_id,
424 ));
425 }
426 }
427
428 $getResult = $this->callAPISuccess('Attachment', 'get', $getParams);
429 $actualNames = array_values(CRM_Utils_Array::collect('name', $getResult['values']));
430 sort($actualNames);
431 sort($expectedNames);
432 $this->assertEquals($expectedNames, $actualNames);
433 }
434
435 /**
436 * @param $getParams
437 * @param $expectedError
438 * @dataProvider badGetProvider
439 */
440 public function testGetError($getParams, $expectedError) {
441 foreach (array(123, 456) as $entity_id) {
442 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
443 $this->callAPISuccess('Attachment', 'create', array(
444 'name' => self::getFilePrefix() . 'example_' . $entity_id . $ext,
445 'mime_type' => $mime,
446 'description' => 'My test description',
447 'content' => 'My test content',
448 'entity_table' => 'civicrm_activity',
449 'entity_id' => $entity_id,
450 ));
451 }
452 }
453
454 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
455 $this->assertRegExp($expectedError, $getResult['error_message']);
456 }
457
458 /**
459 * Take the values from a "get", make a small change, and then send
460 * the full thing back in as an update ("create"). This ensures some
461 * consistency in the acceptable formats.
462 */
463 public function testGetThenUpdate() {
464 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
465 $this->assertTrue(is_numeric($entity->id));
466
467 $createResult = $this->callAPISuccess('Attachment', 'create', array(
468 'name' => self::getFilePrefix() . 'getThenUpdate.txt',
469 'mime_type' => 'text/plain',
470 'description' => 'My test description',
471 'content' => 'My test content',
472 'entity_table' => 'civicrm_activity',
473 'entity_id' => $entity->id,
474 ));
475 $fileId = $createResult['id'];
476 $this->assertTrue(is_numeric($fileId));
477 $this->assertEquals(self::getFilePrefix() . 'getThenUpdate.txt', $createResult['values'][$fileId]['name']);
478 $this->assertAttachmentExistence(TRUE, $createResult);
479
480 $getResult = $this->callAPISuccess('Attachment', 'get', array(
481 'id' => $fileId,
482 ));
483 $this->assertTrue(is_array($getResult['values'][$fileId]));
484
485 $updateParams = $getResult['values'][$fileId];
486 $updateParams['description'] = 'new description';
487 $this->callAPISuccess('Attachment', 'create', $updateParams);
488 $this->assertAttachmentExistence(TRUE, $createResult);
489 }
490
491 /**
492 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
493 * in the DB and the filesystem.
494 */
495 public function testDeleteByID() {
496 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
497 $this->assertTrue(is_numeric($entity->id));
498
499 foreach (array('first', 'second') as $n) {
500 $createResults[$n] = $this->callAPISuccess('Attachment', 'create', array(
501 'name' => self::getFilePrefix() . 'testDeleteByID.txt',
502 'mime_type' => 'text/plain',
503 'content' => 'My test content',
504 'entity_table' => 'civicrm_activity',
505 'entity_id' => $entity->id,
506 ));
507 $this->assertTrue(is_numeric($createResults[$n]['id']));
508 $this->assertEquals(self::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
509 }
510 $this->assertAttachmentExistence(TRUE, $createResults['first']);
511 $this->assertAttachmentExistence(TRUE, $createResults['second']);
512
513 $this->callAPISuccess('Attachment', 'delete', array(
514 'id' => $createResults['first']['id'],
515 ));
516 $this->assertAttachmentExistence(FALSE, $createResults['first']);
517 $this->assertAttachmentExistence(TRUE, $createResults['second']);
518 }
519
520 /**
521 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
522 * in the DB and the filesystem.
523 */
524 public function testDeleteByEntity() {
525 // create 2 entities (keepme,delme) -- each with 2 attachments (first,second)
526 foreach (array('keepme', 'delme') as $e) {
527 $entities[$e] = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
528 $this->assertTrue(is_numeric($entities[$e]->id));
529 foreach (array('first', 'second') as $n) {
530 $createResults[$e][$n] = $this->callAPISuccess('Attachment', 'create', array(
531 'name' => self::getFilePrefix() . 'testDeleteByEntity.txt',
532 'mime_type' => 'text/plain',
533 'content' => 'My test content',
534 'entity_table' => 'civicrm_activity',
535 'entity_id' => $entities[$e]->id,
536 ));
537 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
538 }
539 }
540 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
541 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
542 $this->assertAttachmentExistence(TRUE, $createResults['delme']['first']);
543 $this->assertAttachmentExistence(TRUE, $createResults['delme']['second']);
544
545 $this->callAPISuccess('Attachment', 'delete', array(
546 'entity_table' => 'civicrm_activity',
547 'entity_id' => $entities[$e]->id,
548 ));
549 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
550 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
551 $this->assertAttachmentExistence(FALSE, $createResults['delme']['first']);
552 $this->assertAttachmentExistence(FALSE, $createResults['delme']['second']);
553 }
554
f0be539a
EM
555 /**
556 * @param $name
557 * @return string
558 */
56154d36
TO
559 protected function tmpFile($name) {
560 $tmpDir = sys_get_temp_dir();
561 $this->assertTrue($tmpDir && is_dir($tmpDir), 'Tmp dir must exist: ' . $tmpDir);
562 return $tmpDir . '/' . self::getFilePrefix() . $name;
563 }
564
565 protected function cleanupFiles() {
566 $config = CRM_Core_Config::singleton();
567 $dirs = array(
568 sys_get_temp_dir(),
569 $config->customFileUploadDir,
570 );
571 foreach ($dirs as $dir) {
572 $files = (array) glob($dir . "/" . self::getFilePrefix() . "*");
573 foreach ($files as $file) {
574 unlink($file);
575 }
576
577 }
578 }
96025800 579
56154d36 580}