3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_BAO_Tag
extends CRM_Core_DAO_Tag
{
25 * Retrieve DB object and copy to defaults array.
27 * @param array $params
28 * Array of criteria values.
29 * @param array $defaults
30 * Array to be populated with found values.
33 * The DAO object, if found.
37 public static function retrieve($params, &$defaults) {
38 return self
::commonRetrieve(self
::class, $params, $defaults);
44 * @param string $usedFor
45 * @param bool $excludeHidden
49 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
50 if (!isset($this->tree
)) {
51 $this->buildTree($usedFor, $excludeHidden);
57 * Build a nested array from hierarchical tags.
59 * Supports infinite levels of nesting.
61 * @param string|null $usedFor
62 * @param bool $excludeHidden
64 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
65 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
69 $whereClause[] = "used_for like '%{$usedFor}%'";
72 $whereClause[] = "is_tagset = 0";
75 if (!empty($whereClause)) {
76 $sql .= " WHERE " . implode(' AND ', $whereClause);
79 $sql .= " ORDER BY parent_id,name";
81 $dao = CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
85 while ($dao->fetch()) {
86 $thisref = &$refs[$dao->id
];
88 $thisref['parent_id'] = $dao->parent_id
;
89 $thisref['name'] = $dao->name
;
90 $thisref['description'] = $dao->description
;
91 $thisref['is_selectable'] = $dao->is_selectable
;
93 if (!$dao->parent_id
) {
94 $this->tree
[$dao->id
] = &$thisref;
97 $refs[$dao->parent_id
]['children'][$dao->id
] = &$thisref;
103 * Get tags used for the given entity/entities.
105 * @param array $usedFor
106 * @param bool $buildSelect
108 * @param int $parentId
112 public static function getTagsUsedFor(
113 $usedFor = ['civicrm_contact'],
120 if (empty($usedFor)) {
123 if (!is_array($usedFor)) {
124 $usedFor = [$usedFor];
127 if ($parentId === NULL) {
128 $parentClause = " parent_id IS NULL AND ";
131 $parentClause = " parent_id = {$parentId} AND ";
134 foreach ($usedFor as $entityTable) {
135 $tag = new CRM_Core_DAO_Tag();
137 $tag->orderBy('parent_id');
139 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
142 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
149 while ($tag->fetch()) {
151 $tags[$tag->id
] = $tag->name
;
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;
168 * Function to retrieve tags.
170 * @param string $usedFor
171 * Which type of tag entity.
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
184 public static function getTags(
185 $usedFor = 'civicrm_contact',
188 $separator = ' ',
189 $formatSelectable = FALSE
191 if (!is_array($tags)) {
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
202 WHERE used_for LIKE %1";
204 $query .= " AND parent_id = %2";
205 $args[2] = [$parentId, 'Integer'];
207 $query .= " ORDER BY name";
208 $dao = CRM_Core_DAO
::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
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.
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
224 if ($formatSelectable && !$dao->is_selectable
) {
225 $idPrefix = "crm_disabled_opt";
227 if ($dao->parent_id
== $parentId && $dao->is_tagset
== 0) {
231 'name' => $dao->name
,
232 'idPrefix' => $idPrefix,
239 'name' => $dao->name
,
240 'parent_id' => $dao->parent_id
,
241 'idPrefix' => $idPrefix,
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
251 while (count($roots)) {
253 $current_rows = $rows;
254 $root = array_shift($roots);
255 $tags[$root['id']] = [
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']) {
269 'prefix' => $tags[$root['id']][0] . $separator,
270 'name' => $row['name'],
271 'idPrefix' => $row['idPrefix'],
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);
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
288 foreach ($tags as $key => $tag) {
289 if (!empty($tag[2])) {
290 $key = $tag[2] . "-" . $key;
292 $formattedTags[$key] = $tag[0] . $tag[1];
295 $tags = $formattedTags;
300 * @param string $usedFor
301 * @param bool $allowSelectingNonSelectable
302 * @param null $exclude
304 * @throws \CiviCRM_API3_Exception
306 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
310 'sort' => "name ASC",
313 'return' => ['name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'],
316 $params['used_for'] = ['LIKE' => "%$usedFor%"];
319 $params['id'] = ['!=' => $exclude];
322 foreach (CRM_Utils_Array
::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
324 'text' => $tag['name'],
326 'description' => $tag['description'] ??
NULL,
327 'parent_id' => $tag['parent_id'] ??
NULL,
328 'used_for' => $tag['used_for'] ??
NULL,
329 'color' => $tag['color'] ??
NULL,
331 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
332 $allTags[$id]['disabled'] = TRUE;
335 return CRM_Utils_Array
::buildTree($allTags);
345 public static function del($id) {
346 return (bool) static::deleteRecord(['id' => $id]);
350 * Takes an associative array and creates a tag object.
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
356 * @param array $params
357 * (reference) an assoc array of name/value pairs.
359 * (optional) the array that holds all the db ids - we are moving away from this in bao.
362 * @return CRM_Core_DAO_Tag|null
363 * object on success, otherwise null
365 public static function add(&$params, $ids = []) {
366 $id = $params['id'] ??
$ids['tag'] ??
NULL;
367 if (!$id && !self
::dataExists($params)) {
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.');
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.');
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');
390 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
391 $params['used_for'] = implode(',', $params['used_for']);
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'] = '';
399 // save creator id and time
401 $params['created_id'] = $params['created_id'] ?? CRM_Core_Session
::getLoggedInContactID();
402 $params['created_date'] = $params['created_date'] ??
date('YmdHis');
405 $tag = self
::writeRecord($params);
407 // if we modify parent tag, then we need to update all children
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'],
418 CRM_Core_PseudoConstant
::flush();
424 * Check if there is data to create the object.
426 * @param array $params
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') {
441 * Get the tag sets for a entity object.
443 * @param string $entityTable
449 public static function getTagSet($entityTable) {
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, [
455 '%' . $entityTable . '%',
458 ], TRUE, NULL, FALSE, FALSE);
459 while ($dao->fetch()) {
460 $tagSets[$dao->id
] = $dao->name
;
466 * Get the tags that are not children of a tagset.
469 * associated array of tag name and id
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
;
481 if (!empty($tagSets)) {
482 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
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
;
498 * @param string $searchString
501 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
503 public static function getChildTags($searchString = NULL) {
506 $whereClauses = ['parent.is_tagset <> 1'];
508 $whereClauses[] = " child.name LIKE '%$searchString%' ";
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')
518 while ($dao->fetch()) {
519 $childTagIDs[$dao->parent_id
] = (array) explode(',', $dao->child_id
);
520 $parentID = $dao->parent_id
;
522 // recursively search for parent tag ID and it's child if any
524 $newParentID = CRM_Core_DAO
::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
526 $childTagIDs[$newParentID] = [$parentID];
528 $parentID = $newParentID;
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]);