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