Merge pull request #10946 from mattwire/CRM-21037_activity_sendsms_unittests
[civicrm-core.git] / tests / phpunit / api / v3 / CustomValueTest.php
1 <?php
2 /**
3 * +--------------------------------------------------------------------+
4 * | CiviCRM version 5 |
5 * +--------------------------------------------------------------------+
6 * | Copyright CiviCRM LLC (c) 2004-2018 |
7 * +--------------------------------------------------------------------+
8 * | This file is a part of CiviCRM. |
9 * | |
10 * | CiviCRM is free software; you can copy, modify, and distribute it |
11 * | under the terms of the GNU Affero General Public License |
12 * | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 * | |
14 * | CiviCRM is distributed in the hope that it will be useful, but |
15 * | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 * | See the GNU Affero General Public License for more details. |
18 * | |
19 * | You should have received a copy of the GNU Affero General Public |
20 * | License and the CiviCRM Licensing Exception along |
21 * | with this program; if not, contact CiviCRM LLC |
22 * | at info[AT]civicrm[DOT]org. If you have questions about the |
23 * | GNU Affero General Public License or the licensing of CiviCRM, |
24 * | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 * +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Class api_v3_CustomValueTest
30 * @group headless
31 */
32 class api_v3_CustomValueTest extends CiviUnitTestCase {
33 protected $_apiversion = 3;
34 protected $ids;
35 protected $optionGroup;
36
37 public $DBResetRequired = FALSE;
38
39 public function setUp() {
40 parent::setUp();
41 }
42
43 public function _populateOptionAndCustomGroup($type = NULL) {
44 $dataValues = array(
45 'integer' => array(1, 2, 3),
46 'number' => array(10.11, 20.22, 30.33),
47 'string' => array(substr(sha1(rand()), 0, 4) . '(', substr(sha1(rand()), 0, 3) . '|', substr(sha1(rand()), 0, 2) . ','),
48 // 'country' => array_rand(CRM_Core_PseudoConstant::country(FALSE, FALSE), 3),
49 // This does not work in the test at the moment due to caching issues.
50 //'state_province' => array_rand(CRM_Core_PseudoConstant::stateProvince(FALSE, FALSE), 3),
51 'date' => NULL,
52 'contact' => NULL,
53 'boolean' => NULL,
54 );
55
56 $dataValues = !empty($type) ? array($type => $dataValues[$type]) : $dataValues;
57
58 foreach ($dataValues as $dataType => $values) {
59 $this->optionGroup[$dataType] = array('values' => $values);
60 if (!empty($values)) {
61 $result = $this->callAPISuccess('OptionGroup', 'create',
62 array(
63 'name' => "{$dataType}_group",
64 'api.option_value.create' => array('label' => "$dataType 1", 'value' => $values[0]),
65 'api.option_value.create.1' => array('label' => "$dataType 2", 'value' => $values[1]),
66 'api.option_value.create.2' => array('label' => "$dataType 3", 'value' => $values[2]),
67 )
68 );
69 $this->optionGroup[$dataType]['id'] = $result['id'];
70 }
71 elseif ($dataType == 'contact') {
72 for ($i = 0; $i < 3; $i++) {
73 $result = $this->callAPISuccess('Contact', 'create', array('contact_type' => 'Individual', 'email' => substr(sha1(rand()), 0, 7) . '@yahoo.com'));
74 $this->optionGroup[$dataType]['values'][$i] = $result['id'];
75 }
76 }
77 $this->ids[$dataType] = $this->entityCustomGroupWithSingleFieldCreate("$dataType Custom Group", 'Contacts');
78 }
79
80 }
81
82 public function tearDown() {
83 $tablesToTruncate = array(
84 'civicrm_email',
85 'civicrm_custom_field',
86 'civicrm_custom_group',
87 'civicrm_contact',
88 );
89
90 // true tells quickCleanup to drop any tables that might have been created in the test
91 $this->quickCleanup($tablesToTruncate, TRUE);
92
93 // cleanup created option group for each custom-set before running next test
94 if (!empty($this->optionGroup)) {
95 foreach ($this->optionGroup as $type => $value) {
96 if (!empty($value['id'])) {
97 $count = $this->callAPISuccess('OptionGroup', 'get', array('id' => $value['id']));
98 if ((bool) $count['count']) {
99 $this->callAPISuccess('OptionGroup', 'delete', array('id' => $value['id']));
100 }
101 }
102 }
103 }
104 }
105
106 public function testCreateCustomValue() {
107 $this->_populateOptionAndCustomGroup();
108
109 $customFieldDataType = CRM_Core_BAO_CustomField::dataType();
110 $dataToHtmlTypes = CRM_Core_BAO_CustomField::dataToHtml();
111 $count = 0;
112 $optionSupportingHTMLTypes = array('Select', 'Radio', 'CheckBox', 'AdvMulti-Select', 'Autocomplete-Select', 'Multi-Select');
113
114 foreach ($customFieldDataType as $dataType => $label) {
115 switch ($dataType) {
116 // case 'Country':
117 // case 'StateProvince':
118 case 'String':
119 case 'Link':
120 case 'Int':
121 case 'Float':
122 case 'Money':
123 case 'Date':
124 case 'Boolean':
125
126 //Based on the custom field data-type choose desired SQL operators(to test with) and basic $type
127 if (in_array($dataType, array('String', 'Link'))) {
128 $validSQLOperators = array('=', '!=', 'IN', 'NOT IN', 'LIKE', 'NOT LIKE', 'IS NOT NULL', 'IS NULL');
129 $type = 'string';
130 }
131 elseif ($dataType == 'Boolean') {
132 $validSQLOperators = array('=', '!=', 'IS NOT NULL', 'IS NULL');
133 $type = 'boolean';
134 }
135 else {
136 if ($dataType == 'Country') {
137 $type = 'country';
138 }
139 elseif ($dataType == 'StateProvince') {
140 $type = 'state_province';
141 }
142 elseif ($dataType == 'ContactReference') {
143 $type = 'contact';
144 }
145 elseif ($dataType == 'Date') {
146 $type = 'date';
147 }
148 else {
149 $type = $dataType == 'Int' ? 'integer' : 'number';
150 }
151 $validSQLOperators = array('=', '!=', 'IN', 'NOT IN', '<=', '>=', '>', '<', 'IS NOT NULL', 'IS NULL');
152 }
153
154 //Create custom field of $dataType and html-type $html
155 foreach ($dataToHtmlTypes[$count] as $html) {
156 // per CRM-18568 the like operator does not currently work for fields with options.
157 // the LIKE operator could potentially bypass ACLs (as could IS NOT NULL) and some thought needs to be given
158 // to it.
159 if (in_array($html, $optionSupportingHTMLTypes)) {
160 $validSQLOperators = array_diff($validSQLOperators, array('LIKE', 'NOT LIKE'));
161 }
162 $params = array(
163 'custom_group_id' => $this->ids[$type]['custom_group_id'],
164 'label' => "$dataType - $html",
165 'data_type' => $dataType,
166 'html_type' => $html,
167 'default_value' => NULL,
168 );
169 if (!in_array($html, array('Text', 'TextArea')) && !in_array($dataType, array('Link', 'Date', 'ContactReference', 'Boolean'))) {
170 $params += array('option_group_id' => $this->optionGroup[$type]['id']);
171 }
172 $customField = $this->customFieldCreate($params);
173 //Now test with $validSQLOperator SQL operators against its custom value(s)
174 $this->_testCustomValue($customField['values'][$customField['id']], $validSQLOperators, $type);
175 }
176 $count++;
177 break;
178
179 default:
180 // skipping File data-type & state province due to caching issues
181 $count++;
182 break;
183 }
184 }
185 }
186
187 public function _testCustomValue($customField, $sqlOps, $type) {
188 $isSerialized = CRM_Core_BAO_CustomField::isSerialized($customField);
189 $customId = $customField['id'];
190 $params = array(
191 'contact_type' => 'Individual',
192 'email' => substr(sha1(rand()), 0, 7) . 'man1@yahoo.com',
193 );
194 $result = $this->callAPISuccess('Contact', 'create', $params);
195 $contactId = $result['id'];
196
197 $count = rand(1, 2);
198
199 if ($isSerialized) {
200 $selectedValue = $this->optionGroup[$type]['values'];
201 $notselectedValue = $selectedValue[$count];
202 unset($selectedValue[$count]);
203 }
204 elseif ($customField['html_type'] == 'Link') {
205 $selectedValue = "http://" . substr(sha1(rand()), 0, 7) . ".com";
206 $notselectedValue = "http://" . substr(sha1(rand()), 0, 7) . ".com";
207 }
208 elseif ($type == 'date') {
209 $selectedValue = date('Ymd');
210 $notselectedValue = $lesserSelectedValue = date('Ymd', strtotime('yesterday'));
211 $greaterSelectedValue = date('Ymd', strtotime('+ 1 day'));
212 }
213 elseif ($type == 'contact') {
214 $selectedValue = $this->optionGroup[$type]['values'][1];
215 $notselectedValue = $this->optionGroup[$type]['values'][0];
216 }
217 elseif ($type == 'boolean') {
218 $selectedValue = 1;
219 $notselectedValue = 0;
220 }
221 else {
222 $selectedValue = $this->optionGroup[$type]['values'][0];
223 $notselectedValue = $this->optionGroup[$type]['values'][$count];
224 if (in_array(">", $sqlOps)) {
225 $greaterSelectedValue = $selectedValue + 1;
226 $lesserSelectedValue = $selectedValue - 1;
227 }
228 }
229
230 $params = array('entity_id' => $contactId, 'custom_' . $customId => $selectedValue);
231 $this->callAPISuccess('CustomValue', 'create', $params);
232
233 foreach ($sqlOps as $op) {
234 $qillOp = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
235 switch ($op) {
236 case '=':
237 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => (is_array($selectedValue) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $selectedValue) : $selectedValue)));
238 $this->assertEquals($contactId, $result['id']);
239 break;
240
241 case '!=':
242 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $notselectedValue)));
243 $this->assertEquals(TRUE, array_key_exists($contactId, $result['values']));
244 break;
245
246 case '>':
247 case '<':
248 case '>=':
249 case '<=':
250 if ($isSerialized) {
251 continue;
252 }
253 // To be precise in for these operator we can't just rely on one contact,
254 // hence creating multiple contact with custom value less/more then $selectedValue respectively
255 $result = $this->callAPISuccess('Contact', 'create', array('contact_type' => 'Individual', 'email' => substr(sha1(rand()), 0, 7) . 'man2@yahoo.com'));
256 $contactId2 = $result['id'];
257 $this->callAPISuccess('CustomValue', 'create', array('entity_id' => $contactId2, 'custom_' . $customId => $lesserSelectedValue));
258
259 if ($op == '>') {
260 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $lesserSelectedValue)));
261 $this->assertEquals($contactId, $result['id']);
262 }
263 elseif ($op == '<') {
264 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $selectedValue)));
265 $this->assertEquals($contactId2, $result['id']);
266 }
267 else {
268 $result = $this->callAPISuccess('Contact', 'create', array('contact_type' => 'Individual', 'email' => substr(sha1(rand()), 0, 7) . 'man3@yahoo.com'));
269 $contactId3 = $result['id'];
270 $this->callAPISuccess('CustomValue', 'create', array('entity_id' => $contactId3, 'custom_' . $customId => $greaterSelectedValue));
271
272 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $selectedValue)));
273
274 $this->assertEquals($contactId, $result['values'][$contactId]['id']);
275 if ($op == '>=') {
276 $this->assertEquals($contactId3, $result['values'][$contactId3]['id']);
277 }
278 else {
279 $this->assertEquals($contactId2, $result['values'][$contactId2]['id']);
280 }
281 $this->callAPISuccess('contact', 'delete', array('id' => $contactId3));
282 }
283
284 $this->callAPISuccess('contact', 'delete', array('id' => $contactId2));
285 break;
286
287 case 'IN':
288 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => (array) $selectedValue)));
289 $this->assertEquals($contactId, $result['id']);
290 break;
291
292 case 'NOT IN':
293 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => (array) $notselectedValue)));
294 $this->assertEquals($contactId, $result['id']);
295 break;
296
297 case 'LIKE':
298 $selectedValue = is_array($selectedValue) ? $selectedValue[0] : $selectedValue;
299 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => "%$selectedValue%")));
300 $this->assertEquals($contactId, $result['id']);
301 break;
302
303 case 'NOT LIKE':
304 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $notselectedValue)));
305 $this->assertEquals($contactId, $result['id']);
306 break;
307
308 case 'IS NULL':
309 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => 1)));
310 $this->assertEquals(FALSE, array_key_exists($contactId, $result['values']));
311 break;
312
313 case 'IS NOT NULL':
314 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => 1)));
315 $this->assertEquals($contactId, $result['id']);
316 break;
317 }
318 }
319
320 $this->callAPISuccess('Contact', 'delete', array('id' => $contactId));
321 }
322
323 /**
324 * Ensure custom data is updated when option values are modified
325 *
326 * @link https://issues.civicrm.org/jira/browse/CRM-11856
327 *
328 * @throws \CiviCRM_API3_Exception
329 */
330 public function testAlterOptionValue() {
331 $this->_populateOptionAndCustomGroup('string');
332
333 $selectField = $this->customFieldCreate(array(
334 'custom_group_id' => $this->ids['string']['custom_group_id'],
335 'label' => 'Custom Select',
336 'html_type' => 'Select',
337 'option_group_id' => $this->optionGroup['string']['id'],
338 ));
339 $selectField = civicrm_api3('customField', 'getsingle', array('id' => $selectField['id']));
340 $radioField = $this->customFieldCreate(array(
341 'custom_group_id' => $this->ids['string']['custom_group_id'],
342 'label' => 'Custom Radio',
343 'html_type' => 'Radio',
344 'option_group_id' => $selectField['option_group_id'],
345 ));
346 $multiSelectField = $this->customFieldCreate(array(
347 'custom_group_id' => $this->ids['string']['custom_group_id'],
348 'label' => 'Custom Multi-Select',
349 'html_type' => 'Multi-Select',
350 'option_group_id' => $selectField['option_group_id'],
351 ));
352 $selectName = 'custom_' . $selectField['id'];
353 $radioName = 'custom_' . $radioField['id'];
354 $multiSelectName = 'custom_' . $multiSelectField['id'];
355 $controlFieldName = 'custom_' . $this->ids['string']['custom_field_id'];
356
357 $params = array(
358 'first_name' => 'abc4',
359 'last_name' => 'xyz4',
360 'contact_type' => 'Individual',
361 'email' => 'man4@yahoo.com',
362 $selectName => $this->optionGroup['string']['values'][0],
363 $multiSelectName => $this->optionGroup['string']['values'],
364 $radioName => $this->optionGroup['string']['values'][1],
365 // The control group in a science experiment should be unaffected
366 $controlFieldName => $this->optionGroup['string']['values'][2],
367 );
368
369 $contact = $this->callAPISuccess('Contact', 'create', $params);
370
371 $result = $this->callAPISuccess('Contact', 'getsingle', array(
372 'id' => $contact['id'],
373 'return' => array($selectName, $multiSelectName),
374 ));
375 $this->assertEquals($params[$selectName], $result[$selectName]);
376 $this->assertEquals($params[$multiSelectName], $result[$multiSelectName]);
377
378 $this->callAPISuccess('OptionValue', 'create', array(
379 'value' => 'one-modified',
380 'option_group_id' => $selectField['option_group_id'],
381 'name' => 'string 1',
382 'options' => array(
383 'match-mandatory' => array('option_group_id', 'name'),
384 ),
385 ));
386
387 $result = $this->callAPISuccess('Contact', 'getsingle', array(
388 'id' => $contact['id'],
389 'return' => array($selectName, $multiSelectName, $controlFieldName, $radioName),
390 ));
391 // Ensure the relevant fields have been updated
392 $this->assertEquals('one-modified', $result[$selectName]);
393 $this->assertEquals(array('one-modified', $params[$radioName], $params[$controlFieldName]), $result[$multiSelectName]);
394 // This field should not have changed because we didn't alter this option
395 $this->assertEquals($params[$radioName], $result[$radioName]);
396 // This should not have changed because this field doesn't use the affected option group
397 $this->assertEquals($params[$controlFieldName], $result[$controlFieldName]);
398 // Add test of proof that multivalue fields.
399 $this->callAPISuccess('CustomValue', 'create', array(
400 'entity_id' => $contact['id'],
401 $multiSelectName => array($params[$radioName], $params[$controlFieldName]),
402 ));
403 $result = $this->callAPISuccess('Contact', 'getsingle', array(
404 'id' => $contact['id'],
405 'return' => array($selectName, $multiSelectName, $controlFieldName, $radioName),
406 ));
407
408 $this->assertEquals(array($params[$radioName], $params[$controlFieldName]), $result[$multiSelectName]);
409 }
410
411 public function testGettree() {
412 $cg = $this->callAPISuccess('CustomGroup', 'create', array(
413 'title' => 'TestGettree',
414 'extends' => 'Individual',
415 ));
416 $cf = $this->callAPISuccess('CustomField', 'create', array(
417 'custom_group_id' => $cg['id'],
418 'label' => 'Got Options',
419 'name' => 'got_options',
420 "data_type" => "String",
421 "html_type" => "Multi-Select",
422 'option_values' => array('1' => 'One', '2' => 'Two', '3' => 'Three'),
423 ));
424 $fieldName = 'custom_' . $cf['id'];
425 $contact = $this->individualCreate(array($fieldName => array('2', '3')));
426
427 // Verify values are formatted correctly
428 $tree = $this->callAPISuccess('CustomValue', 'gettree', array('entity_type' => 'Contact', 'entity_id' => $contact));
429 $this->assertEquals(array('2', '3'), $tree['values']['TestGettree']['fields']['got_options']['value']['data']);
430 $this->assertEquals('Two, Three', $tree['values']['TestGettree']['fields']['got_options']['value']['display']);
431
432 // Try limiting the return params
433 $tree = $this->callAPISuccess('CustomValue', 'gettree', array(
434 'entity_type' => 'Contact',
435 'entity_id' => $contact,
436 'return' => array(
437 'custom_group.id',
438 'custom_field.id',
439 ),
440 ));
441 $this->assertEquals(array('2', '3'), $tree['values']['TestGettree']['fields']['got_options']['value']['data']);
442 $this->assertEquals('Two, Three', $tree['values']['TestGettree']['fields']['got_options']['value']['display']);
443 $this->assertEquals(array('id', 'fields'), array_keys($tree['values']['TestGettree']));
444
445 // Ensure display values are returned even if data is not
446 $tree = $this->callAPISuccess('CustomValue', 'gettree', array(
447 'entity_type' => 'Contact',
448 'entity_id' => $contact,
449 'return' => array(
450 'custom_value.display',
451 ),
452 ));
453 $this->assertEquals('Two, Three', $tree['values']['TestGettree']['fields']['got_options']['value']['display']);
454 $this->assertFalse(isset($tree['values']['TestGettree']['fields']['got_options']['value']['data']));
455
456 // Verify that custom set appears for individuals even who don't have any custom data
457 $contact2 = $this->individualCreate();
458 $tree = $this->callAPISuccess('CustomValue', 'gettree', array('entity_type' => 'Contact', 'entity_id' => $contact2));
459 $this->assertArrayHasKey('TestGettree', $tree['values']);
460
461 // Verify that custom set doesn't appear for other contact types
462 $org = $this->organizationCreate();
463 $tree = $this->callAPISuccess('CustomValue', 'gettree', array('entity_type' => 'Contact', 'entity_id' => $org));
464 $this->assertArrayNotHasKey('TestGettree', $tree['values']);
465
466 }
467
468 public function testGettree_getfields() {
469 $fields = $this->callAPISuccess('CustomValue', 'getfields', array('api_action' => 'gettree'));
470 $fields = $fields['values'];
471 $this->assertTrue((bool) $fields['entity_id']['api.required']);
472 $this->assertTrue((bool) $fields['entity_type']['api.required']);
473 $this->assertEquals('custom_group.id', $fields['custom_group.id']['name']);
474 $this->assertEquals('custom_field.id', $fields['custom_field.id']['name']);
475 $this->assertEquals('custom_value.id', $fields['custom_value.id']['name']);
476 }
477
478 /**
479 * Test that custom fields in greeting strings are updated.
480 */
481 public function testUpdateCustomGreetings() {
482 // Create a custom group with one field.
483 $customGroupResult = $this->callAPISuccess('CustomGroup', 'create', array(
484 'sequential' => 1,
485 'title' => "test custom group",
486 'extends' => "Individual",
487 ));
488 $customFieldResult = $this->callAPISuccess('CustomField', 'create', array(
489 'custom_group_id' => $customGroupResult['id'],
490 'label' => "greeting test",
491 'data_type' => "String",
492 'html_type' => "Text",
493 ));
494 $customFieldId = $customFieldResult['id'];
495
496 // Create a contact with an email greeting format that includes the new custom field.
497 $contactResult = $this->callAPISuccess('Contact', 'create', array(
498 'contact_type' => 'Individual',
499 'email' => substr(sha1(rand()), 0, 7) . '@yahoo.com',
500 'email_greeting_id' => "Customized",
501 'email_greeting_custom' => "Dear {contact.custom_{$customFieldId}}",
502 ));
503 $cid = $contactResult['id'];
504
505 // Define testing values.
506 $uniq = uniqid();
507 $testGreetingValue = "Dear $uniq";
508
509 // Update contact's custom field with CustomValue.create
510 $customValueResult = $this->callAPISuccess('CustomValue', 'create', array(
511 'entity_id' => $cid,
512 "custom_{$customFieldId}" => $uniq,
513 'entity_table' => "civicrm_contact",
514 ));
515
516 $contact = $this->callAPISuccessGetSingle('Contact', array('id' => $cid, 'return' => 'email_greeting'));
517 $this->assertEquals($testGreetingValue, $contact['email_greeting_display']);
518
519 }
520
521 }