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