Merge pull request #17709 from spalmstr/dev/core#1768
[civicrm-core.git] / CRM / Contact / BAO / ContactType.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 use Civi\Api4\ContactType;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19 class CRM_Contact_BAO_ContactType extends CRM_Contact_DAO_ContactType {
20
21 /**
22 * Fetch object based on array of properties.
23 *
24 * @param array $params
25 * (reference ) an assoc array of name/value pairs.
26 * @param array $defaults
27 * (reference ) an assoc array to hold the flattened values.
28 *
29 * @return CRM_Contact_DAO_ContactType|null
30 * object on success, null otherwise
31 */
32 public static function retrieve(&$params, &$defaults) {
33 $contactType = new CRM_Contact_DAO_ContactType();
34 $contactType->copyValues($params);
35 if ($contactType->find(TRUE)) {
36 CRM_Core_DAO::storeValues($contactType, $defaults);
37 return $contactType;
38 }
39 return NULL;
40 }
41
42 /**
43 * Is this contact type active.
44 *
45 * @param string $contactType
46 *
47 * @return bool
48 */
49 public static function isActive($contactType) {
50 $contact = self::contactTypeInfo(FALSE);
51 return array_key_exists($contactType, $contact);
52 }
53
54 /**
55 * Retrieve basic contact type information.
56 *
57 * @todo - call getAllContactTypes & return filtered results.
58 *
59 * @param bool $includeInactive
60 *
61 * @return array
62 * Array of basic contact types information.
63 *
64 * @throws \API_Exception
65 * @throws \Civi\API\Exception\UnauthorizedException
66 */
67 public static function basicTypeInfo($includeInactive = FALSE) {
68 $cacheKey = 'CRM_CT_BTI_' . (int) $includeInactive;
69 if (!Civi::cache('contactTypes')->has($cacheKey)) {
70 $contactType = ContactType::get()->setCheckPermissions(FALSE)->setSelect(['*'])->addWhere('parent_id', 'IS NULL');
71 if ($includeInactive === FALSE) {
72 $contactType->addWhere('is_active', '=', 1);
73 }
74 Civi::cache('contactTypes')->set($cacheKey, (array) $contactType->execute()->indexBy('name'));
75 }
76 return Civi::cache('contactTypes')->get($cacheKey);
77 }
78
79 /**
80 * Retrieve all basic contact types.
81 *
82 * @param bool $all
83 *
84 * @return array
85 * Array of basic contact types
86 *
87 * @throws \API_Exception
88 * @throws \Civi\API\Exception\UnauthorizedException
89 */
90 public static function basicTypes($all = FALSE) {
91 return array_keys(self::basicTypeInfo($all));
92 }
93
94 /**
95 * @param bool $all
96 * @param string $key
97 *
98 * @return array
99 * @throws \API_Exception
100 * @throws \Civi\API\Exception\UnauthorizedException
101 */
102 public static function basicTypePairs($all = FALSE, $key = 'name') {
103 $subtypes = self::basicTypeInfo($all);
104
105 $pairs = [];
106 foreach ($subtypes as $name => $info) {
107 $index = ($key == 'name') ? $name : $info[$key];
108 $pairs[$index] = $info['label'];
109 }
110 return $pairs;
111 }
112
113 /**
114 * Retrieve all subtypes Information.
115 *
116 * @todo - call getAllContactTypes & return filtered results.
117 *
118 * @param array $contactType
119 * ..
120 * @param bool $all
121 * @param bool $ignoreCache
122 *
123 * @return array
124 * Array of sub type information
125 */
126 public static function subTypeInfo($contactType = NULL, $all = FALSE, $ignoreCache = FALSE) {
127 $argString = $all ? 'CRM_CT_STI_1_' : 'CRM_CT_STI_0_';
128 if (!empty($contactType)) {
129 $contactType = (array) $contactType;
130 $argString .= implode('_', $contactType);
131 }
132 if (!Civi::cache('contactTypes')->has($argString) || $ignoreCache) {
133 $ctWHERE = '';
134 if (!empty($contactType)) {
135 $ctWHERE = " AND parent.name IN ('" . implode("','", $contactType) . "')";
136 }
137
138 $sql = "
139 SELECT subtype.*, parent.name as parent, parent.label as parent_label
140 FROM civicrm_contact_type subtype
141 INNER JOIN civicrm_contact_type parent ON subtype.parent_id = parent.id
142 WHERE subtype.name IS NOT NULL AND subtype.parent_id IS NOT NULL {$ctWHERE}
143 ";
144 if ($all === FALSE) {
145 $sql .= " AND subtype.is_active = 1 AND parent.is_active = 1 ORDER BY parent.id";
146 }
147 $dao = CRM_Core_DAO::executeQuery($sql, [],
148 FALSE, 'CRM_Contact_DAO_ContactType'
149 );
150 $values = [];
151 while ($dao->fetch()) {
152 $value = [];
153 CRM_Core_DAO::storeValues($dao, $value);
154 $value['parent'] = $dao->parent;
155 $value['parent_label'] = $dao->parent_label;
156 $values[$dao->name] = $value;
157 }
158 Civi::cache('contactTypes')->set($argString, $values);
159 }
160 return Civi::cache('contactTypes')->get($argString);
161 }
162
163 /**
164 *
165 * retrieve all subtypes
166 *
167 * @param array $contactType
168 * ..
169 * @param bool $all
170 * @param string $columnName
171 * @param bool $ignoreCache
172 *
173 * @return array
174 * all subtypes OR list of subtypes associated to
175 * a given basic contact type
176 */
177 public static function subTypes($contactType = NULL, $all = FALSE, $columnName = 'name', $ignoreCache = FALSE) {
178 if ($columnName === 'name') {
179 return array_keys(self::subTypeInfo($contactType, $all, $ignoreCache));
180 }
181 else {
182 return array_values(self::subTypePairs($contactType, FALSE, NULL, $ignoreCache));
183 }
184 }
185
186 /**
187 *
188 * retrieve subtype pairs with name as 'subtype-name' and 'label' as value
189 *
190 * @param array $contactType
191 * @param bool $all
192 * @param string $labelPrefix
193 * @param bool $ignoreCache
194 *
195 * @return array
196 * list of subtypes with name as 'subtype-name' and 'label' as value
197 */
198 public static function subTypePairs($contactType = NULL, $all = FALSE, $labelPrefix = '- ', $ignoreCache = FALSE) {
199 $subtypes = self::subTypeInfo($contactType, $all, $ignoreCache);
200
201 $pairs = [];
202 foreach ($subtypes as $name => $info) {
203 $pairs[$name] = $labelPrefix . $info['label'];
204 }
205 return $pairs;
206 }
207
208 /**
209 *
210 * retrieve list of all types i.e basic + subtypes.
211 *
212 * @param bool $all
213 *
214 * @return array
215 * Array of basic types + all subtypes.
216 */
217 public static function contactTypes($all = FALSE) {
218 return array_keys(self::contactTypeInfo($all));
219 }
220
221 /**
222 * Retrieve info array about all types i.e basic + subtypes.
223 *
224 * @todo deprecate calling this with $all = TRUE in favour of getAllContactTypes
225 * & ideally add getActiveContactTypes & call that from this fully
226 * deprecated function.
227 *
228 * @param bool $all
229 *
230 * @return array
231 * Array of basic types + all subtypes.
232 * @throws \API_Exception
233 */
234 public static function contactTypeInfo($all = FALSE) {
235 $contactTypes = self::getAllContactTypes();
236 if (!$all) {
237 foreach ($contactTypes as $index => $value) {
238 if (!$value['is_active']) {
239 unset($contactTypes[$index]);
240 }
241 }
242 }
243 return $contactTypes;
244 }
245
246 /**
247 * Retrieve basic type pairs with name as 'built-in name' and 'label' as value.
248 *
249 * @param bool $all
250 * @param null $typeName
251 * @param null $delimiter
252 *
253 * @return array
254 * Array of basictypes with name as 'built-in name' and 'label' as value
255 * @throws \API_Exception
256 */
257 public static function contactTypePairs($all = FALSE, $typeName = NULL, $delimiter = NULL) {
258 $types = self::contactTypeInfo($all);
259
260 if ($typeName && !is_array($typeName)) {
261 $typeName = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($typeName, CRM_Core_DAO::VALUE_SEPARATOR));
262 }
263
264 $pairs = [];
265 if ($typeName) {
266 foreach ($typeName as $type) {
267 if (array_key_exists($type, $types)) {
268 $pairs[$type] = $types[$type]['label'];
269 }
270 }
271 }
272 else {
273 foreach ($types as $name => $info) {
274 $pairs[$name] = $info['label'];
275 }
276 }
277
278 return !$delimiter ? $pairs : implode($delimiter, $pairs);
279 }
280
281 /**
282 * Get a list of elements for select box.
283 * Note that this used to default to using the hex(01) character - which results in an invalid character being used in form fields
284 * which was not handled well be anything that loaded & resaved the html (outside core)
285 * The use of this separator is now explicit in the calling functions as a step towards it's removal
286 *
287 * @param bool $all
288 * @param bool $isSeparator
289 * @param string $separator
290 *
291 * @return mixed
292 */
293 public static function getSelectElements(
294 $all = FALSE,
295 $isSeparator = TRUE,
296 $separator = '__'
297 ) {
298 // @todo - use Cache class - ie like Civi::cache('contactTypes')
299 static $_cache = NULL;
300
301 if ($_cache === NULL) {
302 $_cache = [];
303 }
304
305 // @todo - call getAllContactTypes & return filtered results.
306 $argString = $all ? 'CRM_CT_GSE_1' : 'CRM_CT_GSE_0';
307 $argString .= $isSeparator ? '_1' : '_0';
308 $argString .= $separator;
309 $argString = CRM_Utils_Cache::cleanKey($argString);
310 if (!array_key_exists($argString, $_cache)) {
311 $cache = CRM_Utils_Cache::singleton();
312 $_cache[$argString] = $cache->get($argString);
313
314 if (!$_cache[$argString]) {
315 $_cache[$argString] = [];
316
317 $sql = '
318 SELECT c.name as child_name , c.label as child_label , c.id as child_id,
319 p.name as parent_name, p.label as parent_label, p.id as parent_id
320 FROM civicrm_contact_type c
321 LEFT JOIN civicrm_contact_type p ON ( c.parent_id = p.id )
322 WHERE ( c.name IS NOT NULL )
323 ';
324
325 if ($all === FALSE) {
326 $sql .= '
327 AND c.is_active = 1
328 AND ( p.is_active = 1 OR p.id IS NULL )
329 ';
330 }
331 $sql .= " ORDER BY c.id";
332
333 $values = [];
334 $dao = CRM_Core_DAO::executeQuery($sql);
335 while ($dao->fetch()) {
336 if (!empty($dao->parent_id)) {
337 $key = $isSeparator ? $dao->parent_name . $separator . $dao->child_name : $dao->child_name;
338 $label = "- {$dao->child_label}";
339 $pName = $dao->parent_name;
340 }
341 else {
342 $key = $dao->child_name;
343 $label = $dao->child_label;
344 $pName = $dao->child_name;
345 }
346
347 if (!isset($values[$pName])) {
348 $values[$pName] = [];
349 }
350 $values[$pName][] = ['key' => $key, 'label' => $label];
351 }
352
353 $selectElements = [];
354 foreach ($values as $pName => $elements) {
355 foreach ($elements as $element) {
356 $selectElements[$element['key']] = $element['label'];
357 }
358 }
359 $_cache[$argString] = $selectElements;
360
361 $cache->set($argString, $_cache[$argString]);
362 }
363 }
364 return $_cache[$argString];
365 }
366
367 /**
368 * Check if a given type is a subtype.
369 *
370 * @param string $subType
371 * Contact subType.
372 * @param bool $ignoreCache
373 *
374 * @return bool
375 * true if subType, false otherwise.
376 */
377 public static function isaSubType($subType, $ignoreCache = FALSE) {
378 return in_array($subType, self::subTypes(NULL, TRUE, 'name', $ignoreCache));
379 }
380
381 /**
382 * Retrieve the basic contact type associated with given subType.
383 *
384 * @param array|string $subType contact subType.
385 * @return array|string
386 * basicTypes.
387 */
388 public static function getBasicType($subType) {
389 // @todo - use Cache class - ie like Civi::cache('contactTypes')
390 static $_cache = NULL;
391 if ($_cache === NULL) {
392 $_cache = [];
393 }
394
395 $isArray = TRUE;
396 if ($subType && !is_array($subType)) {
397 $subType = [$subType];
398 $isArray = FALSE;
399 }
400 $argString = implode('_', $subType);
401
402 if (!array_key_exists($argString, $_cache)) {
403 $_cache[$argString] = [];
404
405 $sql = "
406 SELECT subtype.name as contact_subtype, type.name as contact_type
407 FROM civicrm_contact_type subtype
408 INNER JOIN civicrm_contact_type type ON ( subtype.parent_id = type.id )
409 WHERE subtype.name IN ('" . implode("','", $subType) . "' )";
410 $dao = CRM_Core_DAO::executeQuery($sql);
411 while ($dao->fetch()) {
412 if (!$isArray) {
413 $_cache[$argString] = $dao->contact_type;
414 break;
415 }
416 $_cache[$argString][$dao->contact_subtype] = $dao->contact_type;
417 }
418 }
419 return $_cache[$argString];
420 }
421
422 /**
423 * Suppress all subtypes present in given array.
424 *
425 * @param array $subTypes
426 * Contact subTypes.
427 * @param bool $ignoreCache
428 *
429 * @return array
430 * Array of suppressed subTypes.
431 */
432 public static function suppressSubTypes(&$subTypes, $ignoreCache = FALSE) {
433 $subTypes = array_diff($subTypes, self::subTypes(NULL, TRUE, 'name', $ignoreCache));
434 return $subTypes;
435 }
436
437 /**
438 * Verify if a given subtype is associated with a given basic contact type.
439 *
440 * @param string $subType
441 * Contact subType.
442 * @param string $contactType
443 * Contact Type.
444 * @param bool $ignoreCache
445 * @param string $columnName
446 *
447 * @return bool
448 * true if contact extends, false otherwise.
449 */
450 public static function isExtendsContactType($subType, $contactType, $ignoreCache = FALSE, $columnName = 'name') {
451 $subType = (array) CRM_Utils_Array::explodePadded($subType);
452 $subtypeList = self::subTypes($contactType, TRUE, $columnName, $ignoreCache);
453 $intersection = array_intersect($subType, $subtypeList);
454 return $subType == $intersection;
455 }
456
457 /**
458 * Create shortcuts menu for contactTypes.
459 *
460 * @return array
461 * of contactTypes
462 */
463 public static function getCreateNewList() {
464 $shortCuts = [];
465 //@todo FIXME - using the CRM_Core_DAO::VALUE_SEPARATOR creates invalid html - if you can find the form
466 // this is loaded onto then replace with something like '__' & test
467 $separator = CRM_Core_DAO::VALUE_SEPARATOR;
468 $contactTypes = self::getSelectElements(FALSE, TRUE, $separator);
469 foreach ($contactTypes as $key => $value) {
470 if ($key) {
471 $typeValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $key);
472 $cType = $typeValue['0'] ?? NULL;
473 $typeUrl = 'ct=' . $cType;
474 if ($csType = CRM_Utils_Array::value('1', $typeValue)) {
475 $typeUrl .= "&cst=$csType";
476 }
477 $shortCut = [
478 'path' => 'civicrm/contact/add',
479 'query' => "$typeUrl&reset=1",
480 'ref' => "new-$value",
481 'title' => $value,
482 ];
483 if ($csType = CRM_Utils_Array::value('1', $typeValue)) {
484 $shortCuts[$cType]['shortCuts'][] = $shortCut;
485 }
486 else {
487 $shortCuts[$cType] = $shortCut;
488 }
489 }
490 }
491 return $shortCuts;
492 }
493
494 /**
495 * Delete Contact SubTypes.
496 *
497 * @param int $contactTypeId
498 * ID of the Contact Subtype to be deleted.
499 *
500 * @return bool
501 */
502 public static function del($contactTypeId) {
503
504 if (!$contactTypeId) {
505 return FALSE;
506 }
507
508 $params = ['id' => $contactTypeId];
509 self::retrieve($params, $typeInfo);
510 $name = $typeInfo['name'];
511 // check if any custom group
512 $custom = new CRM_Core_DAO_CustomGroup();
513 $custom->whereAdd("extends_entity_column_value LIKE '%" .
514 CRM_Core_DAO::VALUE_SEPARATOR .
515 $name .
516 CRM_Core_DAO::VALUE_SEPARATOR . "%'"
517 );
518 if ($custom->find()) {
519 return FALSE;
520 }
521
522 // remove subtype for existing contacts
523 $sql = "
524 UPDATE civicrm_contact SET contact_sub_type = NULL
525 WHERE contact_sub_type = '$name'";
526 CRM_Core_DAO::executeQuery($sql);
527
528 // remove subtype from contact type table
529 $contactType = new CRM_Contact_DAO_ContactType();
530 $contactType->id = $contactTypeId;
531 $contactType->delete();
532
533 // remove navigation entry if any
534 if ($name) {
535 $sql = '
536 DELETE
537 FROM civicrm_navigation
538 WHERE name = %1';
539 $params = [1 => ["New $name", 'String']];
540 CRM_Core_DAO::executeQuery($sql, $params);
541 CRM_Core_BAO_Navigation::resetNavigation();
542 Civi::cache('contactTypes')->clear();
543 }
544 return TRUE;
545 }
546
547 /**
548 * Add or update Contact SubTypes.
549 *
550 * @param array $params
551 * An assoc array of name/value pairs.
552 *
553 * @return object|void
554 * @throws \CRM_Core_Exception
555 */
556 public static function add($params) {
557
558 // label or name
559 if (empty($params['id']) && empty($params['label'])) {
560 // @todo consider throwing exception instead.
561 return NULL;
562 }
563 if (empty($params['id']) && empty($params['name'])) {
564 $params['name'] = ucfirst(CRM_Utils_String::munge($params['label']));
565 }
566 if (!empty($params['parent_id']) &&
567 !CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_ContactType', $params['parent_id'])
568 ) {
569 return NULL;
570 }
571
572 $contactType = new CRM_Contact_DAO_ContactType();
573 $contactType->copyValues($params);
574 $contactType->id = $params['id'] ?? NULL;
575
576 $contactType->save();
577 if ($contactType->find(TRUE)) {
578 $contactName = $contactType->name;
579 $contact = ucfirst($contactType->label);
580 $active = $contactType->is_active;
581 }
582
583 if (!empty($params['id'])) {
584 $newParams = [
585 'label' => ts("New %1", [1 => $contact]),
586 'is_active' => $contactType->is_active,
587 ];
588 CRM_Core_BAO_Navigation::processUpdate(['name' => "New $contactName"], $newParams);
589 }
590 else {
591 $name = self::getBasicType($contactName);
592 if (!$name) {
593 return NULL;
594 }
595 $value = ['name' => "New $name"];
596 CRM_Core_BAO_Navigation::retrieve($value, $navinfo);
597 $navigation = [
598 'label' => ts("New %1", [1 => $contact]),
599 'name' => "New $contactName",
600 'url' => "civicrm/contact/add?ct=$name&cst=$contactName&reset=1",
601 'permission' => 'add contacts',
602 'parent_id' => $navinfo['id'],
603 'is_active' => $active,
604 ];
605 CRM_Core_BAO_Navigation::add($navigation);
606 }
607 CRM_Core_BAO_Navigation::resetNavigation();
608 Civi::cache('contactTypes')->clear();
609
610 return $contactType;
611 }
612
613 /**
614 * Update the is_active flag in the db.
615 *
616 * @param int $id
617 * Id of the database record.
618 * @param bool $is_active
619 * Value we want to set the is_active field.
620 *
621 * @return bool
622 * true if we found and updated the object, else false
623 */
624 public static function setIsActive($id, $is_active) {
625 $params = ['id' => $id];
626 self::retrieve($params, $contactinfo);
627 $params = ['name' => "New $contactinfo[name]"];
628 $newParams = ['is_active' => $is_active];
629 CRM_Core_BAO_Navigation::processUpdate($params, $newParams);
630 CRM_Core_BAO_Navigation::resetNavigation();
631 return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_ContactType', $id,
632 'is_active', $is_active
633 );
634 }
635
636 /**
637 * @param string $typeName
638 *
639 * @return string
640 * @throws \API_Exception
641 */
642 public static function getLabel($typeName) {
643 $types = self::contactTypeInfo(TRUE);
644
645 if (array_key_exists($typeName, $types)) {
646 return $types[$typeName]['label'];
647 }
648 return $typeName;
649 }
650
651 /**
652 * Check whether allow to change any contact's subtype
653 * on the basis of custom data and relationship of specific subtype
654 * currently used in contact/edit form amd in import validation
655 *
656 * @param int $contactId
657 * Contact id.
658 * @param string $subType
659 * Subtype.
660 *
661 * @return bool
662 * @throws \CRM_Core_Exception
663 */
664 public static function isAllowEdit($contactId, $subType = NULL) {
665
666 if (!$contactId) {
667 return TRUE;
668 }
669
670 if (empty($subType)) {
671 $subType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
672 $contactId,
673 'contact_sub_type'
674 );
675 }
676
677 if (self::hasCustomData($subType, $contactId) || self::hasRelationships($contactId, $subType)) {
678 return FALSE;
679 }
680
681 return TRUE;
682 }
683
684 /**
685 * @param $contactType
686 * @param int $contactId
687 *
688 * @return bool
689 */
690 public static function hasCustomData($contactType, $contactId = NULL) {
691 $subTypeClause = '';
692
693 if (self::isaSubType($contactType)) {
694 $subType = $contactType;
695 $contactType = self::getBasicType($subType);
696
697 // check for empty custom data which extends subtype
698 $subTypeValue = CRM_Core_DAO::VALUE_SEPARATOR . $subType . CRM_Core_DAO::VALUE_SEPARATOR;
699 $subTypeClause = " AND extends_entity_column_value LIKE '%{$subTypeValue}%' ";
700 }
701 $query = "SELECT table_name FROM civicrm_custom_group WHERE extends = '{$contactType}' {$subTypeClause}";
702
703 $dao = CRM_Core_DAO::executeQuery($query);
704 while ($dao->fetch()) {
705 $sql = "SELECT count(id) FROM {$dao->table_name}";
706 if ($contactId) {
707 $sql .= " WHERE entity_id = {$contactId}";
708 }
709 $sql .= " LIMIT 1";
710
711 $customDataCount = CRM_Core_DAO::singleValueQuery($sql);
712 if (!empty($customDataCount)) {
713 return TRUE;
714 }
715 }
716 return FALSE;
717 }
718
719 /**
720 * @todo what does this function do?
721 * @param int $contactId
722 * @param $contactType
723 *
724 * @return bool
725 */
726 public static function hasRelationships($contactId, $contactType) {
727 $subTypeClause = NULL;
728 if (self::isaSubType($contactType)) {
729 $subType = $contactType;
730 $contactType = self::getBasicType($subType);
731 $subTypeClause = " AND ( ( crt.contact_type_a = '{$contactType}' AND crt.contact_sub_type_a = '{$subType}') OR
732 ( crt.contact_type_b = '{$contactType}' AND crt.contact_sub_type_b = '{$subType}') ) ";
733 }
734 else {
735 $subTypeClause = " AND ( crt.contact_type_a = '{$contactType}' OR crt.contact_type_b = '{$contactType}' ) ";
736 }
737
738 // check relationships for
739 $relationshipQuery = "
740 SELECT count(cr.id) FROM civicrm_relationship cr
741 INNER JOIN civicrm_relationship_type crt ON
742 ( cr.relationship_type_id = crt.id {$subTypeClause} )
743 WHERE ( cr.contact_id_a = {$contactId} OR cr.contact_id_b = {$contactId} )
744 LIMIT 1";
745
746 $relationshipCount = CRM_Core_DAO::singleValueQuery($relationshipQuery);
747
748 if (!empty($relationshipCount)) {
749 return TRUE;
750 }
751
752 return FALSE;
753 }
754
755 /**
756 * @param $contactType
757 * @param array $subtypeSet
758 *
759 * @return array
760 * @throws \CRM_Core_Exception
761 * @todo what does this function do?
762 */
763 public static function getSubtypeCustomPair($contactType, $subtypeSet = []) {
764 if (empty($subtypeSet)) {
765 return $subtypeSet;
766 }
767
768 $customSet = $subTypeClause = [];
769 foreach ($subtypeSet as $subtype) {
770 $subtype = CRM_Utils_Type::escape($subtype, 'String');
771 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype . CRM_Core_DAO::VALUE_SEPARATOR;
772 $subTypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%' ";
773 }
774 $query = 'SELECT table_name
775 FROM civicrm_custom_group
776 WHERE extends = %1 AND ' . implode(" OR ", $subTypeClause);
777 $dao = CRM_Core_DAO::executeQuery($query, [1 => [$contactType, 'String']]);
778 while ($dao->fetch()) {
779 $customSet[] = $dao->table_name;
780 }
781 return array_unique($customSet);
782 }
783
784 /**
785 * Function that does something.
786 *
787 * @param int $contactID
788 * @param string $contactType
789 * @param array $oldSubtypeSet
790 * @param array $newSubtypeSet
791 *
792 * @return bool
793 * @throws \CRM_Core_Exception
794 *
795 * @todo what does this function do?
796 */
797 public static function deleteCustomSetForSubtypeMigration(
798 $contactID,
799 $contactType,
800 $oldSubtypeSet = [],
801 $newSubtypeSet = []
802 ) {
803 $oldCustomSet = self::getSubtypeCustomPair($contactType, $oldSubtypeSet);
804 $newCustomSet = self::getSubtypeCustomPair($contactType, $newSubtypeSet);
805
806 $customToBeRemoved = array_diff($oldCustomSet, $newCustomSet);
807 foreach ($customToBeRemoved as $customTable) {
808 self::deleteCustomRowsForEntityID($customTable, $contactID);
809 }
810 return TRUE;
811 }
812
813 /**
814 * Delete content / rows of a custom table specific to a subtype for a given custom-group.
815 * This function currently works for contact subtypes only and could be later improved / genralized
816 * to work for other subtypes as well.
817 *
818 * @param int $gID
819 * Custom group id.
820 * @param array $subtypes
821 * List of subtypes related to which entry is to be removed.
822 * @param array $subtypesToPreserve
823 *
824 * @return bool
825 *
826 * @throws \CRM_Core_Exception
827 */
828 public static function deleteCustomRowsOfSubtype($gID, $subtypes = [], $subtypesToPreserve = []) {
829 if (!$gID or empty($subtypes)) {
830 return FALSE;
831 }
832
833 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $gID, 'table_name');
834
835 // drop triggers CRM-13587
836 CRM_Core_DAO::dropTriggers($tableName);
837
838 foreach ($subtypesToPreserve as $subtypeToPreserve) {
839 $subtypeToPreserve = CRM_Utils_Type::escape($subtypeToPreserve, 'String');
840 $subtypesToPreserveClause[] = "(civicrm_contact.contact_sub_type NOT LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . $subtypeToPreserve . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
841 }
842 $subtypesToPreserveClause = implode(' AND ', $subtypesToPreserveClause);
843
844 $subtypeClause = [];
845 foreach ($subtypes as $subtype) {
846 $subtype = CRM_Utils_Type::escape($subtype, 'String');
847 $subtypeClause[] = "( civicrm_contact.contact_sub_type LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . $subtype . CRM_Core_DAO::VALUE_SEPARATOR . "%'"
848 . " AND " . $subtypesToPreserveClause . ")";
849 }
850 $subtypeClause = implode(' OR ', $subtypeClause);
851
852 $query = "DELETE custom.*
853 FROM {$tableName} custom
854 INNER JOIN civicrm_contact ON civicrm_contact.id = custom.entity_id
855 WHERE ($subtypeClause)";
856
857 CRM_Core_DAO::singleValueQuery($query);
858
859 // rebuild triggers CRM-13587
860 CRM_Core_DAO::triggerRebuild($tableName);
861 }
862
863 /**
864 * Delete content / rows of a custom table specific entity-id for a given custom-group table.
865 *
866 * @param int $customTable
867 * Custom table name.
868 * @param int $entityID
869 * Entity id.
870 *
871 * @return null|string
872 *
873 * @throws \CRM_Core_Exception
874 */
875 public static function deleteCustomRowsForEntityID($customTable, $entityID) {
876 $customTable = CRM_Utils_Type::escape($customTable, 'String');
877 $query = "DELETE FROM {$customTable} WHERE entity_id = %1";
878 return CRM_Core_DAO::singleValueQuery($query, [1 => [$entityID, 'Integer']]);
879 }
880
881 /**
882 * Get all contact types, leveraging caching.
883 *
884 * @return array
885 *
886 * @throws \API_Exception
887 */
888 protected static function getAllContactTypes() {
889 if (!Civi::cache('contactTypes')->has('all')) {
890 $contactTypes = (array) ContactType::get()->setCheckPermissions(FALSE)
891 ->setSelect(['id', 'name', 'label', 'description', 'is_active', 'is_reserved', 'image_URL', 'parent_id', 'parent_id:name', 'parent_id:label'])
892 ->execute()->indexBy('name');
893
894 foreach ($contactTypes as $id => $contactType) {
895 $contactTypes[$id]['parent'] = $contactType['parent_id:name'];
896 $contactTypes[$id]['parent_label'] = $contactType['parent_id:label'];
897 unset($contactTypes[$id]['parent_id:name'], $contactTypes[$id]['parent_id:label']);
898 }
899 Civi::cache('contactTypes')->set('all', $contactTypes);
900 }
901 $contactTypes = Civi::cache('contactTypes')->get('all');
902 return $contactTypes;
903 }
904
905 }