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