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