Merge pull request #17252 from civicrm/5.25
[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
TO
415 $tag = new CRM_Core_DAO_Tag();
416
417 // if parent id is set then inherit used for and is hidden properties
a7488080 418 if (!empty($params['parent_id'])) {
6a488035
TO
419 // get parent details
420 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
421 }
d3cbd0a5
CW
422 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
423 $params['used_for'] = implode(',', $params['used_for']);
424 }
425
426 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
427 $params['color'] = '';
428 }
6a488035
TO
429
430 $tag->copyValues($params);
9b576df4
EM
431 $tag->id = $id;
432 $hook = !$id ? 'create' : 'edit';
d989d349 433 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
6a488035
TO
434
435 // save creator id and time
436 if (!$tag->id) {
353ffa53
TO
437 $session = CRM_Core_Session::singleton();
438 $tag->created_id = $session->get('userID');
6a488035
TO
439 $tag->created_date = date('YmdHis');
440 }
441
442 $tag->save();
d989d349 443 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
6a488035
TO
444
445 // if we modify parent tag, then we need to update all children
d3cbd0a5
CW
446 $tag->find(TRUE);
447 if (!$tag->parent_id && $tag->used_for) {
6a488035 448 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
be2fb01f
CW
449 [
450 1 => [$tag->used_for, 'String'],
451 2 => [$tag->id, 'Integer'],
452 ]
6a488035
TO
453 );
454 }
455
29303dfc
CW
456 CRM_Core_PseudoConstant::flush();
457
6a488035
TO
458 return $tag;
459 }
460
461 /**
fe482240 462 * Check if there is data to create the object.
6a488035 463 *
6a0b768e
TO
464 * @param array $params
465 * (reference ) an assoc array of name/value pairs.
6a488035 466 *
5c766a0b 467 * @return bool
6a488035 468 */
00be9182 469 public static function dataExists(&$params) {
5ba3bfc8
CW
470 // Disallow empty values except for the number zero.
471 // TODO: create a utility for this since it's needed in many places
472 if (!empty($params['name']) || (string) $params['name'] === '0') {
6a488035
TO
473 return TRUE;
474 }
475
476 return FALSE;
477 }
478
479 /**
fe482240 480 * Get the tag sets for a entity object.
6a488035 481 *
6a0b768e
TO
482 * @param string $entityTable
483 * Entity_table.
6a488035 484 *
a6c01b45
CW
485 * @return array
486 * array of tag sets
6a488035 487 */
00be9182 488 public static function getTagSet($entityTable) {
be2fb01f 489 $tagSets = [];
6a488035
TO
490 $query = "SELECT name, id FROM civicrm_tag
491 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
be2fb01f 492 $dao = CRM_Core_DAO::executeQuery($query, [
518fa0ee
SL
493 1 => [
494 '%' . $entityTable . '%',
495 'String',
496 ],
497 ], TRUE, NULL, FALSE, FALSE);
6a488035
TO
498 while ($dao->fetch()) {
499 $tagSets[$dao->id] = $dao->name;
500 }
6a488035
TO
501 return $tagSets;
502 }
503
504 /**
100fef9d 505 * Get the tags that are not children of a tagset.
6a488035 506 *
a6c01b45
CW
507 * @return array
508 * associated array of tag name and id
6a488035 509 */
00be9182 510 public static function getTagsNotInTagset() {
be2fb01f 511 $tags = $tagSets = [];
6a488035
TO
512 // first get all the tag sets
513 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
33621c4f 514 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
515 while ($dao->fetch()) {
516 $tagSets[] = $dao->id;
517 }
518
519 $parentClause = '';
520 if (!empty($tagSets)) {
521 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
522 }
523
524 // get that tags that don't have tagset as parent
525 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
526 $dao = CRM_Core_DAO::executeQuery($query);
527 while ($dao->fetch()) {
528 $tags[$dao->id] = $dao->name;
529 }
530
531 return $tags;
532 }
96025800 533
dfe61fcf 534 /**
535 * Get child tags IDs
536 *
6e80ee11 537 * @param string $searchString
538 *
518fa0ee 539 * @return array
dfe61fcf 540 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
541 */
6e80ee11 542 public static function getChildTags($searchString = NULL) {
be2fb01f 543 $childTagIDs = [];
dfe61fcf 544
be2fb01f 545 $whereClauses = ['parent.is_tagset <> 1'];
6e80ee11 546 if ($searchString) {
547 $whereClauses[] = " child.name LIKE '%$searchString%' ";
548 }
549
dfe61fcf 550 // only fetch those tags which has child tags
6e80ee11 551 $dao = CRM_Utils_SQL_Select::from('civicrm_tag parent')
518fa0ee
SL
552 ->join('child', 'INNER JOIN civicrm_tag child ON child.parent_id = parent.id ')
553 ->select('parent.id as parent_id, GROUP_CONCAT(child.id) as child_id')
554 ->where($whereClauses)
555 ->groupBy('parent.id')
556 ->execute();
dfe61fcf 557 while ($dao->fetch()) {
558 $childTagIDs[$dao->parent_id] = (array) explode(',', $dao->child_id);
97dcf1d8 559 $parentID = $dao->parent_id;
560 if ($searchString) {
561 // recursively search for parent tag ID and it's child if any
562 while ($parentID) {
563 $newParentID = CRM_Core_DAO::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
564 if ($newParentID) {
be2fb01f 565 $childTagIDs[$newParentID] = [$parentID];
97dcf1d8 566 }
567 $parentID = $newParentID;
568 }
569 }
dfe61fcf 570 }
571
572 // check if child tag has any childs, if found then include those child tags inside parent tag
573 // i.e. format Array('parent_tag' => array('child_tag_1', ...), 'child_tag_1' => array(child_tag_1_1, ..), ..)
574 // to Array('parent_tag' => array('child_tag_1', 'child_tag_1_1'...), ..)
575 foreach ($childTagIDs as $parentTagID => $childTags) {
576 foreach ($childTags as $childTag) {
577 // if $childTag has any child tag of its own
578 if (array_key_exists($childTag, $childTagIDs)) {
579 $childTagIDs[$parentTagID] = array_merge($childTagIDs[$parentTagID], $childTagIDs[$childTag]);
580 }
581 }
582 }
583
584 return $childTagIDs;
585 }
586
6a488035 587}