Merge pull request #17008 from ivan-compucorp/CPS-70-fix-radio-value
[civicrm-core.git] / CRM / Core / BAO / Tag.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17class CRM_Core_BAO_Tag extends CRM_Core_DAO_Tag {
18
f47539f6 19 /**
20 * @var array
21 */
22 protected $tree;
23
6a488035 24 /**
fe482240 25 * Class constructor.
6a488035 26 */
00be9182 27 public function __construct() {
6a488035
TO
28 parent::__construct();
29 }
30
31 /**
fe482240 32 * Fetch object based on array of properties.
6a488035 33 *
6a0b768e
TO
34 * @param array $params
35 * (reference ) an assoc array of name/value pairs.
36 * @param array $defaults
37 * (reference ) an assoc array to hold the flattened values.
6a488035 38 *
a6c01b45
CW
39 * @return object
40 * CRM_Core_DAO_Tag object on success, otherwise null
6a488035 41 */
00be9182 42 public static function retrieve(&$params, &$defaults) {
6a488035
TO
43 $tag = new CRM_Core_DAO_Tag();
44 $tag->copyValues($params);
45 if ($tag->find(TRUE)) {
46 CRM_Core_DAO::storeValues($tag, $defaults);
47 return $tag;
48 }
49 return NULL;
50 }
51
b5c2afd0 52 /**
f47539f6 53 * Get tag tree.
54 *
55 * @param string $usedFor
b5c2afd0
EM
56 * @param bool $excludeHidden
57 *
58 * @return mixed
59 */
00be9182 60 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
6a488035
TO
61 if (!isset($this->tree)) {
62 $this->buildTree($usedFor, $excludeHidden);
63 }
64 return $this->tree;
65 }
66
b5c2afd0 67 /**
f47539f6 68 * Build a nested array from hierarchical tags.
69 *
70 * Supports infinite levels of nesting.
b5c2afd0
EM
71 * @param null $usedFor
72 * @param bool $excludeHidden
73 */
00be9182 74 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
6dac2504 75 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
6a488035 76
be2fb01f 77 $whereClause = [];
6a488035
TO
78 if ($usedFor) {
79 $whereClause[] = "used_for like '%{$usedFor}%'";
80 }
81 if ($excludeHidden) {
82 $whereClause[] = "is_tagset = 0";
83 }
84
85 if (!empty($whereClause)) {
86 $sql .= " WHERE " . implode(' AND ', $whereClause);
87 }
88
89 $sql .= " ORDER BY parent_id,name";
90
be2fb01f 91 $dao = CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
6a488035 92
be2fb01f
CW
93 $refs = [];
94 $this->tree = [];
6a488035 95 while ($dao->fetch()) {
80257742
CW
96 $thisref = &$refs[$dao->id];
97
98 $thisref['parent_id'] = $dao->parent_id;
99 $thisref['name'] = $dao->name;
100 $thisref['description'] = $dao->description;
6dac2504 101 $thisref['is_selectable'] = $dao->is_selectable;
80257742 102
6a488035 103 if (!$dao->parent_id) {
80257742 104 $this->tree[$dao->id] = &$thisref;
6a488035
TO
105 }
106 else {
80257742 107 $refs[$dao->parent_id]['children'][$dao->id] = &$thisref;
6a488035
TO
108 }
109 }
6a488035
TO
110 }
111
b5c2afd0 112 /**
f47539f6 113 * Get tags used for the given entity/entities.
114 *
b5c2afd0
EM
115 * @param array $usedFor
116 * @param bool $buildSelect
117 * @param bool $all
100fef9d 118 * @param int $parentId
b5c2afd0
EM
119 *
120 * @return array
121 */
af9b09df 122 public static function getTagsUsedFor(
be2fb01f 123 $usedFor = ['civicrm_contact'],
af9b09df
TO
124 $buildSelect = TRUE,
125 $all = FALSE,
126 $parentId = NULL
6a488035 127 ) {
be2fb01f 128 $tags = [];
6a488035
TO
129
130 if (empty($usedFor)) {
131 return $tags;
132 }
133 if (!is_array($usedFor)) {
be2fb01f 134 $usedFor = [$usedFor];
6a488035
TO
135 }
136
137 if ($parentId === NULL) {
138 $parentClause = " parent_id IS NULL AND ";
139 }
140 else {
141 $parentClause = " parent_id = {$parentId} AND ";
142 }
143
144 foreach ($usedFor as $entityTable) {
145 $tag = new CRM_Core_DAO_Tag();
146 $tag->fields();
147 $tag->orderBy('parent_id');
148 if ($buildSelect) {
149 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
150 }
151 else {
152 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
153 }
154 if (!$all) {
155 $tag->is_tagset = 0;
156 }
157 $tag->find();
158
159 while ($tag->fetch()) {
160 if ($buildSelect) {
161 $tags[$tag->id] = $tag->name;
162 }
163 else {
164 $tags[$tag->id]['name'] = $tag->name;
165 $tags[$tag->id]['parent_id'] = $tag->parent_id;
166 $tags[$tag->id]['is_tagset'] = $tag->is_tagset;
167 $tags[$tag->id]['used_for'] = $tag->used_for;
eb98e026 168 $tags[$tag->id]['description'] = $tag->description;
d73974ac 169 $tags[$tag->id]['color'] = !empty($tag->color) ? $tag->color : NULL;
6a488035
TO
170 }
171 }
6a488035
TO
172 }
173
174 return $tags;
175 }
176
b5c2afd0 177 /**
fe482240 178 * Function to retrieve tags.
47358d92 179 *
6a0b768e
TO
180 * @param string $usedFor
181 * Which type of tag entity.
182 * @param array $tags
183 * Tags array.
184 * @param int $parentId
185 * Parent id if you want need only children.
186 * @param string $separator
187 * Separator to indicate children.
188 * @param bool $formatSelectable
189 * Add special property for non-selectable.
47358d92 190 * tag, so they cannot be selected
b5c2afd0
EM
191 *
192 * @return array
193 */
2da40d21 194 public static function getTags(
f9f40af3 195 $usedFor = 'civicrm_contact',
be2fb01f 196 &$tags = [],
2aa397bc 197 $parentId = NULL,
47358d92 198 $separator = '&nbsp;&nbsp;',
199 $formatSelectable = FALSE
6a488035 200 ) {
dee5ccbb 201 if (!is_array($tags)) {
be2fb01f 202 $tags = [];
dee5ccbb 203 }
6a488035 204 // We need to build a list of tags ordered by hierarchy and sorted by
b44e3f84 205 // name. The hierarchy will be communicated by an accumulation of
6a488035
TO
206 // separators in front of the name to give it a visual offset.
207 // Instead of recursively making mysql queries, we'll make one big
b44e3f84 208 // query and build the hierarchy with the algorithm below.
be2fb01f 209 $args = [1 => ['%' . $usedFor . '%', 'String']];
47358d92 210 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
6a488035
TO
211 FROM civicrm_tag
212 WHERE used_for LIKE %1";
213 if ($parentId) {
214 $query .= " AND parent_id = %2";
be2fb01f 215 $args[2] = [$parentId, 'Integer'];
6a488035
TO
216 }
217 $query .= " ORDER BY name";
218 $dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
219
220 // Sort the tags into the correct storage by the parent_id/is_tagset
221 // filter the filter was in place previously, we're just reusing it.
222 // $roots represents the current leaf nodes that need to be checked for
223 // children. $rows represents the unplaced nodes, not all of much
224 // are necessarily placed.
be2fb01f 225 $roots = $rows = [];
6a488035 226 while ($dao->fetch()) {
47358d92 227 // note that we are prepending id with "crm_disabled_opt" which identifies
228 // them as disabled so that they cannot be selected. We do some magic
229 // in crm-select2 js function that marks option values to "disabled"
230 // current QF version in CiviCRM does not support passing this attribute,
231 // so this is another ugly hack / workaround,
232 // also know one is too keen to upgrade QF :P
233 $idPrefix = '';
234 if ($formatSelectable && !$dao->is_selectable) {
235 $idPrefix = "crm_disabled_opt";
236 }
6a488035 237 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
be2fb01f 238 $roots[] = [
47358d92 239 'id' => $dao->id,
240 'prefix' => '',
241 'name' => $dao->name,
242 'idPrefix' => $idPrefix,
be2fb01f 243 ];
6a488035
TO
244 }
245 else {
be2fb01f 246 $rows[] = [
47358d92 247 'id' => $dao->id,
248 'prefix' => '',
249 'name' => $dao->name,
250 'parent_id' => $dao->parent_id,
251 'idPrefix' => $idPrefix,
be2fb01f 252 ];
6a488035
TO
253 }
254 }
47358d92 255
6a488035
TO
256 // While we have nodes left to build, shift the first (alphabetically)
257 // node of the list, place it in our tags list and loop through the
258 // list of unplaced nodes to find its children. We make a copy to
259 // iterate through because we must modify the unplaced nodes list
260 // during the loop.
261 while (count($roots)) {
be2fb01f 262 $new_roots = [];
353ffa53
TO
263 $current_rows = $rows;
264 $root = array_shift($roots);
be2fb01f 265 $tags[$root['id']] = [
47358d92 266 $root['prefix'],
267 $root['name'],
268 $root['idPrefix'],
be2fb01f 269 ];
6a488035
TO
270
271 // As you find the children, append them to the end of the new set
272 // of roots (maintain alphabetical ordering). Also remove the node
273 // from the set of unplaced nodes.
274 if (is_array($current_rows)) {
275 foreach ($current_rows as $key => $row) {
276 if ($row['parent_id'] == $root['id']) {
be2fb01f 277 $new_roots[] = [
47358d92 278 'id' => $row['id'],
279 'prefix' => $tags[$root['id']][0] . $separator,
280 'name' => $row['name'],
281 'idPrefix' => $row['idPrefix'],
be2fb01f 282 ];
6a488035
TO
283 unset($rows[$key]);
284 }
285 }
286 }
287
288 //As a group, insert the new roots into the beginning of the roots
289 //list. This maintains the hierarchical ordering of the tags.
290 $roots = array_merge($new_roots, $roots);
291 }
292
293 // Prefix each name with the calcuated spacing to give the visual
294 // appearance of ordering when transformed into HTML in the form layer.
47358d92 295 // here is the actual code that to prepends and set disabled attribute for
296 // non-selectable tags
be2fb01f 297 $formattedTags = [];
47358d92 298 foreach ($tags as $key => $tag) {
299 if (!empty($tag[2])) {
86bfa4f6 300 $key = $tag[2] . "-" . $key;
47358d92 301 }
302 $formattedTags[$key] = $tag[0] . $tag[1];
6a488035
TO
303 }
304
47358d92 305 $tags = $formattedTags;
6a488035
TO
306 return $tags;
307 }
308
b733747a
CW
309 /**
310 * @param string $usedFor
311 * @param bool $allowSelectingNonSelectable
312 * @param null $exclude
313 * @return array
314 * @throws \CiviCRM_API3_Exception
315 */
316 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
be2fb01f
CW
317 $params = [
318 'options' => [
016cf488 319 'limit' => 0,
320 'sort' => "name ASC",
be2fb01f 321 ],
b733747a 322 'is_tagset' => 0,
be2fb01f
CW
323 'return' => ['name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'],
324 ];
b733747a 325 if ($usedFor) {
be2fb01f 326 $params['used_for'] = ['LIKE' => "%$usedFor%"];
b733747a
CW
327 }
328 if ($exclude) {
be2fb01f 329 $params['id'] = ['!=' => $exclude];
b733747a 330 }
be2fb01f 331 $allTags = [];
b733747a 332 foreach (CRM_Utils_Array::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
be2fb01f 333 $allTags[$id] = [
b733747a
CW
334 'text' => $tag['name'],
335 'id' => $id,
6b409353
CW
336 'description' => $tag['description'] ?? NULL,
337 'parent_id' => $tag['parent_id'] ?? NULL,
338 'used_for' => $tag['used_for'] ?? NULL,
339 'color' => $tag['color'] ?? NULL,
be2fb01f 340 ];
b733747a
CW
341 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
342 $allTags[$id]['disabled'] = TRUE;
343 }
344 }
345 return CRM_Utils_Array::buildTree($allTags);
346 }
347
6a488035 348 /**
fe482240 349 * Delete the tag.
6a488035 350 *
6a0b768e
TO
351 * @param int $id
352 * Tag id.
6a488035 353 *
5c766a0b 354 * @return bool
6a488035 355 */
00be9182 356 public static function del($id) {
6a488035 357 // since this is a destructive operation, lets make sure
b44e3f84 358 // id is a positive number
6a488035
TO
359 CRM_Utils_Type::validate($id, 'Positive');
360
361 // delete all crm_entity_tag records with the selected tag id
362 $entityTag = new CRM_Core_DAO_EntityTag();
363 $entityTag->tag_id = $id;
364 $entityTag->delete();
365
366 // delete from tag table
367 $tag = new CRM_Core_DAO_Tag();
368 $tag->id = $id;
369
370 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
371
372 if ($tag->delete()) {
373 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
6a488035
TO
374 return TRUE;
375 }
376 return FALSE;
377 }
378
379 /**
bd525987 380 * Takes an associative array and creates a tag object.
6a488035
TO
381 *
382 * The function extract all the params it needs to initialize the create a
383 * contact object. the params array could contain additional unused name/value
384 * pairs
385 *
6a0b768e
TO
386 * @param array $params
387 * (reference) an assoc array of name/value pairs.
388 * @param array $ids
389 * (optional) the array that holds all the db ids - we are moving away from this in bao.
d989d349 390 * signatures
6a488035 391 *
d3cbd0a5
CW
392 * @return CRM_Core_DAO_Tag|null
393 * object on success, otherwise null
6a488035 394 */
be2fb01f 395 public static function add(&$params, $ids = []) {
8df1a020 396 $id = $params['id'] ?? $ids['tag'] ?? NULL;
9b576df4 397 if (!$id && !self::dataExists($params)) {
6a488035
TO
398 return NULL;
399 }
400
592dd7d8
CW
401 // Check permission to create or modify reserved tag
402 if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('administer reserved tags')) {
403 if (!empty($params['is_reserved']) || ($id && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_reserved'))) {
404 throw new CRM_Core_Exception('Insufficient permission to administer reserved tag.');
405 }
406 }
407
408 // Check permission to create or modify tagset
409 if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('administer Tagsets')) {
410 if (!empty($params['is_tagset']) || ($id && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_tagset'))) {
411 throw new CRM_Core_Exception('Insufficient permission to administer tagset.');
412 }
413 }
414
6a488035 415 // if parent id is set then inherit used for and is hidden properties
a7488080 416 if (!empty($params['parent_id'])) {
6a488035
TO
417 // get parent details
418 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
419 }
d3cbd0a5
CW
420 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
421 $params['used_for'] = implode(',', $params['used_for']);
422 }
423
3a839de8 424 // Hack to make white null, because html5 color widget can't be empty
d3cbd0a5
CW
425 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
426 $params['color'] = '';
427 }
6a488035 428
6a488035 429 // save creator id and time
3a839de8
CW
430 if (!$id) {
431 $params['created_id'] = $params['created_id'] ?? CRM_Core_Session::getLoggedInContactID();
432 $params['created_date'] = $params['created_date'] ?? date('YmdHis');
6a488035
TO
433 }
434
3a839de8 435 $tag = self::writeRecord($params);
6a488035
TO
436
437 // if we modify parent tag, then we need to update all children
3a839de8
CW
438 if ($id) {
439 $tag->find(TRUE);
440 if (!$tag->parent_id && $tag->used_for) {
441 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2", [
be2fb01f
CW
442 1 => [$tag->used_for, 'String'],
443 2 => [$tag->id, 'Integer'],
3a839de8
CW
444 ]);
445 }
6a488035
TO
446 }
447
29303dfc
CW
448 CRM_Core_PseudoConstant::flush();
449
6a488035
TO
450 return $tag;
451 }
452
453 /**
fe482240 454 * Check if there is data to create the object.
6a488035 455 *
6a0b768e 456 * @param array $params
6a488035 457 *
5c766a0b 458 * @return bool
6a488035 459 */
3a839de8 460 public static function dataExists($params) {
5ba3bfc8
CW
461 // Disallow empty values except for the number zero.
462 // TODO: create a utility for this since it's needed in many places
463 if (!empty($params['name']) || (string) $params['name'] === '0') {
6a488035
TO
464 return TRUE;
465 }
466
467 return FALSE;
468 }
469
470 /**
fe482240 471 * Get the tag sets for a entity object.
6a488035 472 *
6a0b768e
TO
473 * @param string $entityTable
474 * Entity_table.
6a488035 475 *
a6c01b45
CW
476 * @return array
477 * array of tag sets
6a488035 478 */
00be9182 479 public static function getTagSet($entityTable) {
be2fb01f 480 $tagSets = [];
6a488035
TO
481 $query = "SELECT name, id FROM civicrm_tag
482 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
be2fb01f 483 $dao = CRM_Core_DAO::executeQuery($query, [
518fa0ee
SL
484 1 => [
485 '%' . $entityTable . '%',
486 'String',
487 ],
488 ], TRUE, NULL, FALSE, FALSE);
6a488035
TO
489 while ($dao->fetch()) {
490 $tagSets[$dao->id] = $dao->name;
491 }
6a488035
TO
492 return $tagSets;
493 }
494
495 /**
100fef9d 496 * Get the tags that are not children of a tagset.
6a488035 497 *
a6c01b45
CW
498 * @return array
499 * associated array of tag name and id
6a488035 500 */
00be9182 501 public static function getTagsNotInTagset() {
be2fb01f 502 $tags = $tagSets = [];
6a488035
TO
503 // first get all the tag sets
504 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
33621c4f 505 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
506 while ($dao->fetch()) {
507 $tagSets[] = $dao->id;
508 }
509
510 $parentClause = '';
511 if (!empty($tagSets)) {
512 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
513 }
514
515 // get that tags that don't have tagset as parent
516 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
517 $dao = CRM_Core_DAO::executeQuery($query);
518 while ($dao->fetch()) {
519 $tags[$dao->id] = $dao->name;
520 }
521
522 return $tags;
523 }
96025800 524
dfe61fcf 525 /**
526 * Get child tags IDs
527 *
6e80ee11 528 * @param string $searchString
529 *
518fa0ee 530 * @return array
dfe61fcf 531 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
532 */
6e80ee11 533 public static function getChildTags($searchString = NULL) {
be2fb01f 534 $childTagIDs = [];
dfe61fcf 535
be2fb01f 536 $whereClauses = ['parent.is_tagset <> 1'];
6e80ee11 537 if ($searchString) {
538 $whereClauses[] = " child.name LIKE '%$searchString%' ";
539 }
540
dfe61fcf 541 // only fetch those tags which has child tags
6e80ee11 542 $dao = CRM_Utils_SQL_Select::from('civicrm_tag parent')
518fa0ee
SL
543 ->join('child', 'INNER JOIN civicrm_tag child ON child.parent_id = parent.id ')
544 ->select('parent.id as parent_id, GROUP_CONCAT(child.id) as child_id')
545 ->where($whereClauses)
546 ->groupBy('parent.id')
547 ->execute();
dfe61fcf 548 while ($dao->fetch()) {
549 $childTagIDs[$dao->parent_id] = (array) explode(',', $dao->child_id);
97dcf1d8 550 $parentID = $dao->parent_id;
551 if ($searchString) {
552 // recursively search for parent tag ID and it's child if any
553 while ($parentID) {
554 $newParentID = CRM_Core_DAO::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
555 if ($newParentID) {
be2fb01f 556 $childTagIDs[$newParentID] = [$parentID];
97dcf1d8 557 }
558 $parentID = $newParentID;
559 }
560 }
dfe61fcf 561 }
562
563 // check if child tag has any childs, if found then include those child tags inside parent tag
564 // i.e. format Array('parent_tag' => array('child_tag_1', ...), 'child_tag_1' => array(child_tag_1_1, ..), ..)
565 // to Array('parent_tag' => array('child_tag_1', 'child_tag_1_1'...), ..)
566 foreach ($childTagIDs as $parentTagID => $childTags) {
567 foreach ($childTags as $childTag) {
568 // if $childTag has any child tag of its own
569 if (array_key_exists($childTag, $childTagIDs)) {
570 $childTagIDs[$parentTagID] = array_merge($childTagIDs[$parentTagID], $childTagIDs[$childTag]);
571 }
572 }
573 }
574
575 return $childTagIDs;
576 }
577
6a488035 578}