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