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
{
27 public function __construct() {
28 parent
::__construct();
32 * Fetch object based on array of properties.
34 * @param array $params
35 * (reference ) an assoc array of name/value pairs.
36 * @param array $defaults
37 * (reference ) an assoc array to hold the flattened values.
40 * CRM_Core_DAO_Tag object on success, otherwise null
42 public static function retrieve(&$params, &$defaults) {
43 $tag = new CRM_Core_DAO_Tag();
44 $tag->copyValues($params);
45 if ($tag->find(TRUE)) {
46 CRM_Core_DAO
::storeValues($tag, $defaults);
55 * @param string $usedFor
56 * @param bool $excludeHidden
60 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
61 if (!isset($this->tree
)) {
62 $this->buildTree($usedFor, $excludeHidden);
68 * Build a nested array from hierarchical tags.
70 * Supports infinite levels of nesting.
71 * @param null $usedFor
72 * @param bool $excludeHidden
74 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
75 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
79 $whereClause[] = "used_for like '%{$usedFor}%'";
82 $whereClause[] = "is_tagset = 0";
85 if (!empty($whereClause)) {
86 $sql .= " WHERE " . implode(' AND ', $whereClause);
89 $sql .= " ORDER BY parent_id,name";
91 $dao = CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
95 while ($dao->fetch()) {
96 $thisref = &$refs[$dao->id
];
98 $thisref['parent_id'] = $dao->parent_id
;
99 $thisref['name'] = $dao->name
;
100 $thisref['description'] = $dao->description
;
101 $thisref['is_selectable'] = $dao->is_selectable
;
103 if (!$dao->parent_id
) {
104 $this->tree
[$dao->id
] = &$thisref;
107 $refs[$dao->parent_id
]['children'][$dao->id
] = &$thisref;
113 * Get tags used for the given entity/entities.
115 * @param array $usedFor
116 * @param bool $buildSelect
118 * @param int $parentId
122 public static function getTagsUsedFor(
123 $usedFor = ['civicrm_contact'],
130 if (empty($usedFor)) {
133 if (!is_array($usedFor)) {
134 $usedFor = [$usedFor];
137 if ($parentId === NULL) {
138 $parentClause = " parent_id IS NULL AND ";
141 $parentClause = " parent_id = {$parentId} AND ";
144 foreach ($usedFor as $entityTable) {
145 $tag = new CRM_Core_DAO_Tag();
147 $tag->orderBy('parent_id');
149 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
152 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
159 while ($tag->fetch()) {
161 $tags[$tag->id
] = $tag->name
;
164 $tags[$tag->id
]['name'] = $tag->name
;
165 $tags[$tag->id
]['parent_id'] = $tag->parent_id
;
166 $tags[$tag->id
]['is_tagset'] = $tag->is_tagset
;
167 $tags[$tag->id
]['used_for'] = $tag->used_for
;
168 $tags[$tag->id
]['description'] = $tag->description
;
169 $tags[$tag->id
]['color'] = !empty($tag->color
) ?
$tag->color
: NULL;
178 * Function to retrieve tags.
180 * @param string $usedFor
181 * Which type of tag entity.
184 * @param int $parentId
185 * Parent id if you want need only children.
186 * @param string $separator
187 * Separator to indicate children.
188 * @param bool $formatSelectable
189 * Add special property for non-selectable.
190 * tag, so they cannot be selected
194 public static function getTags(
195 $usedFor = 'civicrm_contact',
198 $separator = ' ',
199 $formatSelectable = FALSE
201 if (!is_array($tags)) {
204 // We need to build a list of tags ordered by hierarchy and sorted by
205 // name. The hierarchy will be communicated by an accumulation of
206 // separators in front of the name to give it a visual offset.
207 // Instead of recursively making mysql queries, we'll make one big
208 // query and build the hierarchy with the algorithm below.
209 $args = [1 => ['%' . $usedFor . '%', 'String']];
210 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
212 WHERE used_for LIKE %1";
214 $query .= " AND parent_id = %2";
215 $args[2] = [$parentId, 'Integer'];
217 $query .= " ORDER BY name";
218 $dao = CRM_Core_DAO
::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
220 // Sort the tags into the correct storage by the parent_id/is_tagset
221 // filter the filter was in place previously, we're just reusing it.
222 // $roots represents the current leaf nodes that need to be checked for
223 // children. $rows represents the unplaced nodes, not all of much
224 // are necessarily placed.
226 while ($dao->fetch()) {
227 // note that we are prepending id with "crm_disabled_opt" which identifies
228 // them as disabled so that they cannot be selected. We do some magic
229 // in crm-select2 js function that marks option values to "disabled"
230 // current QF version in CiviCRM does not support passing this attribute,
231 // so this is another ugly hack / workaround,
232 // also know one is too keen to upgrade QF :P
234 if ($formatSelectable && !$dao->is_selectable
) {
235 $idPrefix = "crm_disabled_opt";
237 if ($dao->parent_id
== $parentId && $dao->is_tagset
== 0) {
241 'name' => $dao->name
,
242 'idPrefix' => $idPrefix,
249 'name' => $dao->name
,
250 'parent_id' => $dao->parent_id
,
251 'idPrefix' => $idPrefix,
256 // While we have nodes left to build, shift the first (alphabetically)
257 // node of the list, place it in our tags list and loop through the
258 // list of unplaced nodes to find its children. We make a copy to
259 // iterate through because we must modify the unplaced nodes list
261 while (count($roots)) {
263 $current_rows = $rows;
264 $root = array_shift($roots);
265 $tags[$root['id']] = [
271 // As you find the children, append them to the end of the new set
272 // of roots (maintain alphabetical ordering). Also remove the node
273 // from the set of unplaced nodes.
274 if (is_array($current_rows)) {
275 foreach ($current_rows as $key => $row) {
276 if ($row['parent_id'] == $root['id']) {
279 'prefix' => $tags[$root['id']][0] . $separator,
280 'name' => $row['name'],
281 'idPrefix' => $row['idPrefix'],
288 //As a group, insert the new roots into the beginning of the roots
289 //list. This maintains the hierarchical ordering of the tags.
290 $roots = array_merge($new_roots, $roots);
293 // Prefix each name with the calcuated spacing to give the visual
294 // appearance of ordering when transformed into HTML in the form layer.
295 // here is the actual code that to prepends and set disabled attribute for
296 // non-selectable tags
298 foreach ($tags as $key => $tag) {
299 if (!empty($tag[2])) {
300 $key = $tag[2] . "-" . $key;
302 $formattedTags[$key] = $tag[0] . $tag[1];
305 $tags = $formattedTags;
310 * @param string $usedFor
311 * @param bool $allowSelectingNonSelectable
312 * @param null $exclude
314 * @throws \CiviCRM_API3_Exception
316 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
320 'sort' => "name ASC",
323 'return' => ['name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'],
326 $params['used_for'] = ['LIKE' => "%$usedFor%"];
329 $params['id'] = ['!=' => $exclude];
332 foreach (CRM_Utils_Array
::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
334 'text' => $tag['name'],
336 'description' => CRM_Utils_Array
::value('description', $tag),
337 'parent_id' => CRM_Utils_Array
::value('parent_id', $tag),
338 'used_for' => CRM_Utils_Array
::value('used_for', $tag),
339 'color' => CRM_Utils_Array
::value('color', $tag),
341 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
342 $allTags[$id]['disabled'] = TRUE;
345 return CRM_Utils_Array
::buildTree($allTags);
356 public static function del($id) {
357 // since this is a destructive operation, lets make sure
358 // id is a positive number
359 CRM_Utils_Type
::validate($id, 'Positive');
361 // delete all crm_entity_tag records with the selected tag id
362 $entityTag = new CRM_Core_DAO_EntityTag();
363 $entityTag->tag_id
= $id;
364 $entityTag->delete();
366 // delete from tag table
367 $tag = new CRM_Core_DAO_Tag();
370 CRM_Utils_Hook
::pre('delete', 'Tag', $id, $tag);
372 if ($tag->delete()) {
373 CRM_Utils_Hook
::post('delete', 'Tag', $id, $tag);
380 * Takes an associative array and creates a tag object.
382 * The function extract all the params it needs to initialize the create a
383 * contact object. the params array could contain additional unused name/value
386 * @param array $params
387 * (reference) an assoc array of name/value pairs.
389 * (optional) the array that holds all the db ids - we are moving away from this in bao.
392 * @return CRM_Core_DAO_Tag|null
393 * object on success, otherwise null
395 public static function add(&$params, $ids = []) {
396 $id = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('tag', $ids));
397 if (!$id && !self
::dataExists($params)) {
401 // Check permission to create or modify reserved tag
402 if (!empty($params['check_permissions']) && !CRM_Core_Permission
::check('administer reserved tags')) {
403 if (!empty($params['is_reserved']) ||
($id && CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_reserved'))) {
404 throw new CRM_Core_Exception('Insufficient permission to administer reserved tag.');
408 // Check permission to create or modify tagset
409 if (!empty($params['check_permissions']) && !CRM_Core_Permission
::check('administer Tagsets')) {
410 if (!empty($params['is_tagset']) ||
($id && CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_tagset'))) {
411 throw new CRM_Core_Exception('Insufficient permission to administer tagset.');
415 $tag = new CRM_Core_DAO_Tag();
417 // if parent id is set then inherit used for and is hidden properties
418 if (!empty($params['parent_id'])) {
419 // get parent details
420 $params['used_for'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
422 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
423 $params['used_for'] = implode(',', $params['used_for']);
426 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
427 $params['color'] = '';
430 $tag->copyValues($params);
432 $hook = !$id ?
'create' : 'edit';
433 CRM_Utils_Hook
::pre($hook, 'Tag', $tag->id
, $params);
435 // save creator id and time
437 $session = CRM_Core_Session
::singleton();
438 $tag->created_id
= $session->get('userID');
439 $tag->created_date
= date('YmdHis');
443 CRM_Utils_Hook
::post($hook, 'Tag', $tag->id
, $tag);
445 // if we modify parent tag, then we need to update all children
447 if (!$tag->parent_id
&& $tag->used_for
) {
448 CRM_Core_DAO
::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
450 1 => [$tag->used_for
, 'String'],
451 2 => [$tag->id
, 'Integer'],
460 * Check if there is data to create the object.
462 * @param array $params
463 * (reference ) an assoc array of name/value pairs.
467 public static function dataExists(&$params) {
468 // Disallow empty values except for the number zero.
469 // TODO: create a utility for this since it's needed in many places
470 if (!empty($params['name']) ||
(string) $params['name'] === '0') {
478 * Get the tag sets for a entity object.
480 * @param string $entityTable
486 public static function getTagSet($entityTable) {
488 $query = "SELECT name, id FROM civicrm_tag
489 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
490 $dao = CRM_Core_DAO
::executeQuery($query, [
492 '%' . $entityTable . '%',
495 ], TRUE, NULL, FALSE, FALSE);
496 while ($dao->fetch()) {
497 $tagSets[$dao->id
] = $dao->name
;
503 * Get the tags that are not children of a tagset.
506 * associated array of tag name and id
508 public static function getTagsNotInTagset() {
509 $tags = $tagSets = [];
510 // first get all the tag sets
511 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
512 $dao = CRM_Core_DAO
::executeQuery($query);
513 while ($dao->fetch()) {
514 $tagSets[] = $dao->id
;
518 if (!empty($tagSets)) {
519 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
522 // get that tags that don't have tagset as parent
523 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
524 $dao = CRM_Core_DAO
::executeQuery($query);
525 while ($dao->fetch()) {
526 $tags[$dao->id
] = $dao->name
;
535 * @param string $searchString
538 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
540 public static function getChildTags($searchString = NULL) {
543 $whereClauses = ['parent.is_tagset <> 1'];
545 $whereClauses[] = " child.name LIKE '%$searchString%' ";
548 // only fetch those tags which has child tags
549 $dao = CRM_Utils_SQL_Select
::from('civicrm_tag parent')
550 ->join('child', 'INNER JOIN civicrm_tag child ON child.parent_id = parent.id ')
551 ->select('parent.id as parent_id, GROUP_CONCAT(child.id) as child_id')
552 ->where($whereClauses)
553 ->groupBy('parent.id')
555 while ($dao->fetch()) {
556 $childTagIDs[$dao->parent_id
] = (array) explode(',', $dao->child_id
);
557 $parentID = $dao->parent_id
;
559 // recursively search for parent tag ID and it's child if any
561 $newParentID = CRM_Core_DAO
::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
563 $childTagIDs[$newParentID] = [$parentID];
565 $parentID = $newParentID;
570 // check if child tag has any childs, if found then include those child tags inside parent tag
571 // i.e. format Array('parent_tag' => array('child_tag_1', ...), 'child_tag_1' => array(child_tag_1_1, ..), ..)
572 // to Array('parent_tag' => array('child_tag_1', 'child_tag_1_1'...), ..)
573 foreach ($childTagIDs as $parentTagID => $childTags) {
574 foreach ($childTags as $childTag) {
575 // if $childTag has any child tag of its own
576 if (array_key_exists($childTag, $childTagIDs)) {
577 $childTagIDs[$parentTagID] = array_merge($childTagIDs[$parentTagID], $childTagIDs[$childTag]);