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 * Fetch object based on array of properties.
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.
33 * CRM_Core_DAO_Tag object on success, otherwise null
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);
48 * @param string $usedFor
49 * @param bool $excludeHidden
53 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
54 if (!isset($this->tree
)) {
55 $this->buildTree($usedFor, $excludeHidden);
61 * Build a nested array from hierarchical tags.
63 * Supports infinite levels of nesting.
65 * @param string|null $usedFor
66 * @param bool $excludeHidden
68 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
69 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
73 $whereClause[] = "used_for like '%{$usedFor}%'";
76 $whereClause[] = "is_tagset = 0";
79 if (!empty($whereClause)) {
80 $sql .= " WHERE " . implode(' AND ', $whereClause);
83 $sql .= " ORDER BY parent_id,name";
85 $dao = CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
89 while ($dao->fetch()) {
90 $thisref = &$refs[$dao->id
];
92 $thisref['parent_id'] = $dao->parent_id
;
93 $thisref['name'] = $dao->name
;
94 $thisref['description'] = $dao->description
;
95 $thisref['is_selectable'] = $dao->is_selectable
;
97 if (!$dao->parent_id
) {
98 $this->tree
[$dao->id
] = &$thisref;
101 $refs[$dao->parent_id
]['children'][$dao->id
] = &$thisref;
107 * Get tags used for the given entity/entities.
109 * @param array $usedFor
110 * @param bool $buildSelect
112 * @param int $parentId
116 public static function getTagsUsedFor(
117 $usedFor = ['civicrm_contact'],
124 if (empty($usedFor)) {
127 if (!is_array($usedFor)) {
128 $usedFor = [$usedFor];
131 if ($parentId === NULL) {
132 $parentClause = " parent_id IS NULL AND ";
135 $parentClause = " parent_id = {$parentId} AND ";
138 foreach ($usedFor as $entityTable) {
139 $tag = new CRM_Core_DAO_Tag();
141 $tag->orderBy('parent_id');
143 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
146 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
153 while ($tag->fetch()) {
155 $tags[$tag->id
] = $tag->name
;
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;
172 * Function to retrieve tags.
174 * @param string $usedFor
175 * Which type of tag entity.
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
188 public static function getTags(
189 $usedFor = 'civicrm_contact',
192 $separator = ' ',
193 $formatSelectable = FALSE
195 if (!is_array($tags)) {
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
206 WHERE used_for LIKE %1";
208 $query .= " AND parent_id = %2";
209 $args[2] = [$parentId, 'Integer'];
211 $query .= " ORDER BY name";
212 $dao = CRM_Core_DAO
::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
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.
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
228 if ($formatSelectable && !$dao->is_selectable
) {
229 $idPrefix = "crm_disabled_opt";
231 if ($dao->parent_id
== $parentId && $dao->is_tagset
== 0) {
235 'name' => $dao->name
,
236 'idPrefix' => $idPrefix,
243 'name' => $dao->name
,
244 'parent_id' => $dao->parent_id
,
245 'idPrefix' => $idPrefix,
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
255 while (count($roots)) {
257 $current_rows = $rows;
258 $root = array_shift($roots);
259 $tags[$root['id']] = [
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']) {
273 'prefix' => $tags[$root['id']][0] . $separator,
274 'name' => $row['name'],
275 'idPrefix' => $row['idPrefix'],
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);
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
292 foreach ($tags as $key => $tag) {
293 if (!empty($tag[2])) {
294 $key = $tag[2] . "-" . $key;
296 $formattedTags[$key] = $tag[0] . $tag[1];
299 $tags = $formattedTags;
304 * @param string $usedFor
305 * @param bool $allowSelectingNonSelectable
306 * @param null $exclude
308 * @throws \CiviCRM_API3_Exception
310 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
314 'sort' => "name ASC",
317 'return' => ['name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'],
320 $params['used_for'] = ['LIKE' => "%$usedFor%"];
323 $params['id'] = ['!=' => $exclude];
326 foreach (CRM_Utils_Array
::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
328 'text' => $tag['name'],
330 'description' => $tag['description'] ??
NULL,
331 'parent_id' => $tag['parent_id'] ??
NULL,
332 'used_for' => $tag['used_for'] ??
NULL,
333 'color' => $tag['color'] ??
NULL,
335 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
336 $allTags[$id]['disabled'] = TRUE;
339 return CRM_Utils_Array
::buildTree($allTags);
349 public static function del($id) {
350 return (bool) static::deleteRecord(['id' => $id]);
354 * Takes an associative array and creates a tag object.
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
360 * @param array $params
361 * (reference) an assoc array of name/value pairs.
363 * (optional) the array that holds all the db ids - we are moving away from this in bao.
366 * @return CRM_Core_DAO_Tag|null
367 * object on success, otherwise null
369 public static function add(&$params, $ids = []) {
370 $id = $params['id'] ??
$ids['tag'] ??
NULL;
371 if (!$id && !self
::dataExists($params)) {
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.');
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.');
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');
394 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
395 $params['used_for'] = implode(',', $params['used_for']);
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'] = '';
403 // save creator id and time
405 $params['created_id'] = $params['created_id'] ?? CRM_Core_Session
::getLoggedInContactID();
406 $params['created_date'] = $params['created_date'] ??
date('YmdHis');
409 $tag = self
::writeRecord($params);
411 // if we modify parent tag, then we need to update all children
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'],
422 CRM_Core_PseudoConstant
::flush();
428 * Check if there is data to create the object.
430 * @param array $params
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') {
445 * Get the tag sets for a entity object.
447 * @param string $entityTable
453 public static function getTagSet($entityTable) {
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, [
459 '%' . $entityTable . '%',
462 ], TRUE, NULL, FALSE, FALSE);
463 while ($dao->fetch()) {
464 $tagSets[$dao->id
] = $dao->name
;
470 * Get the tags that are not children of a tagset.
473 * associated array of tag name and id
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
;
485 if (!empty($tagSets)) {
486 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
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
;
502 * @param string $searchString
505 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
507 public static function getChildTags($searchString = NULL) {
510 $whereClauses = ['parent.is_tagset <> 1'];
512 $whereClauses[] = " child.name LIKE '%$searchString%' ";
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')
522 while ($dao->fetch()) {
523 $childTagIDs[$dao->parent_id
] = (array) explode(',', $dao->child_id
);
524 $parentID = $dao->parent_id
;
526 // recursively search for parent tag ID and it's child if any
528 $newParentID = CRM_Core_DAO
::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
530 $childTagIDs[$newParentID] = [$parentID];
532 $parentID = $newParentID;
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]);