INFRA-132 - Drupal.Array.Array.CommaLastItem
[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 * Include class definitions
30 */
31 require_once 'CiviTest/CiviUnitTestCase.php';
32
33
34 /**
35 * Test for the Attachment API
36 *
37 * @package CiviCRM_APIv3
38 * @subpackage API_Contact
39 */
40 class api_v3_AttachmentTest extends CiviUnitTestCase {
41 protected static $filePrefix = NULL;
42
43 /**
44 * @return string
45 */
46 public static function getFilePrefix() {
47 if (!self::$filePrefix) {
48 self::$filePrefix = "test_" . CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC) . '_';
49 }
50 return self::$filePrefix;
51 }
52
53
54 protected function setUp() {
55 parent::setUp();
56 $this->useTransaction(TRUE);
57
58 $this->cleanupFiles();
59 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
60 }
61
62 protected function tearDown() {
63 parent::tearDown();
64 $this->cleanupFiles();
65 \Civi\Core\Container::singleton(TRUE);
66 }
67
68 /**
69 * @return array
70 */
71 public function okCreateProvider() {
72 $cases = array(); // array($entityClass, $createParams, $expectedContent)
73
74 $cases[] = array(
75 'CRM_Activity_DAO_Activity',
76 array(
77 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
78 'mime_type' => 'text/plain',
79 'description' => 'My test description',
80 'content' => 'My test content',
81 ),
82 'My test content',
83 );
84
85 $cases[] = array(
86 'CRM_Activity_DAO_Activity',
87 array(
88 'name' => self::getFilePrefix() . 'exampleWithEmptyContent.txt',
89 'mime_type' => 'text/plain',
90 'description' => 'My test description',
91 'content' => '',
92 ),
93 '',
94 );
95
96 $cases[] = array(
97 'CRM_Activity_DAO_Activity',
98 array(
99 'name' => self::getFilePrefix() . 'exampleFromMove.txt',
100 'mime_type' => 'text/plain',
101 'description' => 'My test description',
102 'options' => array(
103 'move-file' => $this->tmpFile('mytest.txt'),
104 ),
105 ),
106 'This comes from a file',
107 );
108
109 return $cases;
110 }
111
112 /**
113 * @return array
114 */
115 public function badCreateProvider() {
116 $cases = array(); // array($entityClass, $createParams, $expectedError)
117
118 $cases[] = array(
119 'CRM_Activity_DAO_Activity',
120 array(
121 'id' => 12345,
122 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
123 'mime_type' => 'text/plain',
124 'description' => 'My test description',
125 'content' => 'My test content',
126 ),
127 '/Invalid ID/',
128 );
129 $cases[] = array(
130 'CRM_Activity_DAO_Activity',
131 array(
132 'name' => self::getFilePrefix() . 'failedExample.txt',
133 'mime_type' => 'text/plain',
134 'description' => 'My test description',
135 ),
136 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
137 );
138 $cases[] = array(
139 'CRM_Activity_DAO_Activity',
140 array(
141 'name' => self::getFilePrefix() . 'failedExample.txt',
142 'mime_type' => 'text/plain',
143 'description' => 'My test description',
144 'content' => 'too much content',
145 'options' => array(
146 'move-file' => $this->tmpFile('too-much.txt'),
147 ),
148 ),
149 "/'content' and 'options.move-file' are mutually exclusive/",
150 );
151 $cases[] = array(
152 'CRM_Activity_DAO_Activity',
153 array(
154 'name' => 'inv/alid.txt',
155 'mime_type' => 'text/plain',
156 'description' => 'My test description',
157 'content' => 'My test content',
158 ),
159 "/Malformed name/",
160 );
161 $cases[] = array(
162 'CRM_Core_DAO_Domain',
163 array(
164 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
165 'mime_type' => 'text/plain',
166 'description' => 'My test description',
167 'content' => 'My test content',
168 ),
169 "/Unrecognized target entity/",
170 );
171
172 return $cases;
173 }
174
175 /**
176 * @return array
177 */
178 public function badUpdateProvider() {
179 $cases = array(); // array($entityClass, $createParams, $updateParams, $expectedError)
180
181 $readOnlyFields = array(
182 'name' => 'newname.txt',
183 'entity_table' => 'civicrm_domain',
184 'entity_id' => 5,
185 'upload_date' => '2010-11-12 13:14:15',
186 );
187 foreach ($readOnlyFields as $readOnlyField => $newValue) {
188 $cases[] = array(
189 'CRM_Activity_DAO_Activity',
190 array(
191 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
192 'mime_type' => 'text/plain',
193 'description' => 'My test description',
194 'content' => 'My test content',
195 ),
196 array(
197 'check_permissions' => 1,
198 $readOnlyField => $newValue,
199 ),
200 "/Cannot modify $readOnlyField/",
201 );
202 }
203
204 return $cases;
205 }
206
207 /**
208 * @return array
209 */
210 public function okGetProvider() {
211 $cases = array(); // array($getParams, $expectedNames)
212
213 // Each search runs in a DB which contains these attachments:
214 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
215 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
216
217 $cases[] = array(
218 array('entity_table' => 'civicrm_activity'),
219 array(
220 self::getFilePrefix() . 'example_123.csv',
221 self::getFilePrefix() . 'example_123.txt',
222 self::getFilePrefix() . 'example_456.csv',
223 self::getFilePrefix() . 'example_456.txt',
224 ),
225 );
226 $cases[] = array(
227 array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
228 array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_456.txt'),
229 );
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
254 /**
255 * @return array
256 */
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),
274 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
275 );
276 $cases[] = array(
277 array('entity_table' => 'civicrm_activity', 'name' => 'example_456.csv'),
278 "/Get by name is not currently supported/",
279 );
280 $cases[] = array(
281 array('entity_table' => 'civicrm_activity', 'content' => 'test'),
282 "/Get by content is not currently supported/",
283 );
284 $cases[] = array(
285 array('entity_table' => 'civicrm_activity', 'path' => '/home/foo'),
286 "/Get by path is not currently supported/",
287 );
288 $cases[] = array(
289 array('entity_table' => 'civicrm_activity', 'url' => '/index.php'),
290 "/Get by url is not currently supported/",
291 );
292
293 return $cases;
294 }
295
296 /**
297 * Create an attachment using "content" and then "get" the attachment
298 *
299 * @param string $testEntityClass
300 * E.g. "CRM_Core_DAO_Activity".
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
555 /**
556 * @param $exists
557 * @param array $apiResult
558 */
559 protected function assertAttachmentExistence($exists, $apiResult) {
560 $fileId = $apiResult['id'];
561 $this->assertTrue(is_numeric($fileId));
562 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
563 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
564 1 => array($fileId, 'Int'),
565 ));
566 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
567 1 => array($fileId, 'Int'),
568 ));
569 }
570
571 /**
572 * @param $name
573 * @return string
574 */
575 protected function tmpFile($name) {
576 $tmpDir = sys_get_temp_dir();
577 $this->assertTrue($tmpDir && is_dir($tmpDir), 'Tmp dir must exist: ' . $tmpDir);
578 return $tmpDir . '/' . self::getFilePrefix() . $name;
579 }
580
581 protected function cleanupFiles() {
582 $config = CRM_Core_Config::singleton();
583 $dirs = array(
584 sys_get_temp_dir(),
585 $config->customFileUploadDir,
586 );
587 foreach ($dirs as $dir) {
588 $files = (array) glob($dir . "/" . self::getFilePrefix() . "*");
589 foreach ($files as $file) {
590 unlink($file);
591 }
592
593 }
594 }
595
596 }