3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Core_BAO_Tag
extends CRM_Core_DAO_Tag
{
43 public function __construct() {
44 parent
::__construct();
48 * Fetch object based on array of properties.
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
52 * @param array $defaults
53 * (reference ) an assoc array to hold the flattened values.
56 * CRM_Core_DAO_Tag object on success, otherwise null
58 public static function retrieve(&$params, &$defaults) {
59 $tag = new CRM_Core_DAO_Tag();
60 $tag->copyValues($params);
61 if ($tag->find(TRUE)) {
62 CRM_Core_DAO
::storeValues($tag, $defaults);
71 * @param string $usedFor
72 * @param bool $excludeHidden
76 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
77 if (!isset($this->tree
)) {
78 $this->buildTree($usedFor, $excludeHidden);
84 * Build a nested array from hierarchical tags.
86 * Supports infinite levels of nesting.
87 * @param null $usedFor
88 * @param bool $excludeHidden
90 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
91 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
95 $whereClause[] = "used_for like '%{$usedFor}%'";
98 $whereClause[] = "is_tagset = 0";
101 if (!empty($whereClause)) {
102 $sql .= " WHERE " . implode(' AND ', $whereClause);
105 $sql .= " ORDER BY parent_id,name";
107 $dao = CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
111 while ($dao->fetch()) {
112 $thisref = &$refs[$dao->id
];
114 $thisref['parent_id'] = $dao->parent_id
;
115 $thisref['name'] = $dao->name
;
116 $thisref['description'] = $dao->description
;
117 $thisref['is_selectable'] = $dao->is_selectable
;
119 if (!$dao->parent_id
) {
120 $this->tree
[$dao->id
] = &$thisref;
123 $refs[$dao->parent_id
]['children'][$dao->id
] = &$thisref;
129 * Get tags used for the given entity/entities.
131 * @param array $usedFor
132 * @param bool $buildSelect
134 * @param int $parentId
138 public static function getTagsUsedFor(
139 $usedFor = ['civicrm_contact'],
146 if (empty($usedFor)) {
149 if (!is_array($usedFor)) {
150 $usedFor = [$usedFor];
153 if ($parentId === NULL) {
154 $parentClause = " parent_id IS NULL AND ";
157 $parentClause = " parent_id = {$parentId} AND ";
160 foreach ($usedFor as $entityTable) {
161 $tag = new CRM_Core_DAO_Tag();
163 $tag->orderBy('parent_id');
165 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
168 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
175 while ($tag->fetch()) {
177 $tags[$tag->id
] = $tag->name
;
180 $tags[$tag->id
]['name'] = $tag->name
;
181 $tags[$tag->id
]['parent_id'] = $tag->parent_id
;
182 $tags[$tag->id
]['is_tagset'] = $tag->is_tagset
;
183 $tags[$tag->id
]['used_for'] = $tag->used_for
;
184 $tags[$tag->id
]['description'] = $tag->description
;
185 $tags[$tag->id
]['color'] = !empty($tag->color
) ?
$tag->color
: NULL;
194 * Function to retrieve tags.
196 * @param string $usedFor
197 * Which type of tag entity.
200 * @param int $parentId
201 * Parent id if you want need only children.
202 * @param string $separator
203 * Separator to indicate children.
204 * @param bool $formatSelectable
205 * Add special property for non-selectable.
206 * tag, so they cannot be selected
210 public static function getTags(
211 $usedFor = 'civicrm_contact',
214 $separator = ' ',
215 $formatSelectable = FALSE
217 if (!is_array($tags)) {
220 // We need to build a list of tags ordered by hierarchy and sorted by
221 // name. The hierarchy will be communicated by an accumulation of
222 // separators in front of the name to give it a visual offset.
223 // Instead of recursively making mysql queries, we'll make one big
224 // query and build the hierarchy with the algorithm below.
225 $args = [1 => ['%' . $usedFor . '%', 'String']];
226 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
228 WHERE used_for LIKE %1";
230 $query .= " AND parent_id = %2";
231 $args[2] = [$parentId, 'Integer'];
233 $query .= " ORDER BY name";
234 $dao = CRM_Core_DAO
::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
236 // Sort the tags into the correct storage by the parent_id/is_tagset
237 // filter the filter was in place previously, we're just reusing it.
238 // $roots represents the current leaf nodes that need to be checked for
239 // children. $rows represents the unplaced nodes, not all of much
240 // are necessarily placed.
242 while ($dao->fetch()) {
243 // note that we are prepending id with "crm_disabled_opt" which identifies
244 // them as disabled so that they cannot be selected. We do some magic
245 // in crm-select2 js function that marks option values to "disabled"
246 // current QF version in CiviCRM does not support passing this attribute,
247 // so this is another ugly hack / workaround,
248 // also know one is too keen to upgrade QF :P
250 if ($formatSelectable && !$dao->is_selectable
) {
251 $idPrefix = "crm_disabled_opt";
253 if ($dao->parent_id
== $parentId && $dao->is_tagset
== 0) {
257 'name' => $dao->name
,
258 'idPrefix' => $idPrefix,
265 'name' => $dao->name
,
266 'parent_id' => $dao->parent_id
,
267 'idPrefix' => $idPrefix,
272 // While we have nodes left to build, shift the first (alphabetically)
273 // node of the list, place it in our tags list and loop through the
274 // list of unplaced nodes to find its children. We make a copy to
275 // iterate through because we must modify the unplaced nodes list
277 while (count($roots)) {
279 $current_rows = $rows;
280 $root = array_shift($roots);
281 $tags[$root['id']] = [
287 // As you find the children, append them to the end of the new set
288 // of roots (maintain alphabetical ordering). Also remove the node
289 // from the set of unplaced nodes.
290 if (is_array($current_rows)) {
291 foreach ($current_rows as $key => $row) {
292 if ($row['parent_id'] == $root['id']) {
295 'prefix' => $tags[$root['id']][0] . $separator,
296 'name' => $row['name'],
297 'idPrefix' => $row['idPrefix'],
304 //As a group, insert the new roots into the beginning of the roots
305 //list. This maintains the hierarchical ordering of the tags.
306 $roots = array_merge($new_roots, $roots);
309 // Prefix each name with the calcuated spacing to give the visual
310 // appearance of ordering when transformed into HTML in the form layer.
311 // here is the actual code that to prepends and set disabled attribute for
312 // non-selectable tags
314 foreach ($tags as $key => $tag) {
315 if (!empty($tag[2])) {
316 $key = $tag[2] . "-" . $key;
318 $formattedTags[$key] = $tag[0] . $tag[1];
321 $tags = $formattedTags;
326 * @param string $usedFor
327 * @param bool $allowSelectingNonSelectable
328 * @param null $exclude
330 * @throws \CiviCRM_API3_Exception
332 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
336 'sort' => "name ASC",
339 'return' => ['name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'],
342 $params['used_for'] = ['LIKE' => "%$usedFor%"];
345 $params['id'] = ['!=' => $exclude];
348 foreach (CRM_Utils_Array
::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
350 'text' => $tag['name'],
352 'description' => CRM_Utils_Array
::value('description', $tag),
353 'parent_id' => CRM_Utils_Array
::value('parent_id', $tag),
354 'used_for' => CRM_Utils_Array
::value('used_for', $tag),
355 'color' => CRM_Utils_Array
::value('color', $tag),
357 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
358 $allTags[$id]['disabled'] = TRUE;
361 return CRM_Utils_Array
::buildTree($allTags);
372 public static function del($id) {
373 // since this is a destructive operation, lets make sure
374 // id is a positive number
375 CRM_Utils_Type
::validate($id, 'Positive');
377 // delete all crm_entity_tag records with the selected tag id
378 $entityTag = new CRM_Core_DAO_EntityTag();
379 $entityTag->tag_id
= $id;
380 $entityTag->delete();
382 // delete from tag table
383 $tag = new CRM_Core_DAO_Tag();
386 CRM_Utils_Hook
::pre('delete', 'Tag', $id, $tag);
388 if ($tag->delete()) {
389 CRM_Utils_Hook
::post('delete', 'Tag', $id, $tag);
396 * Takes an associative array and creates a tag object.
398 * The function extract all the params it needs to initialize the create a
399 * contact object. the params array could contain additional unused name/value
402 * @param array $params
403 * (reference) an assoc array of name/value pairs.
405 * (optional) the array that holds all the db ids - we are moving away from this in bao.
408 * @return CRM_Core_DAO_Tag|null
409 * object on success, otherwise null
411 public static function add(&$params, $ids = []) {
412 $id = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('tag', $ids));
413 if (!$id && !self
::dataExists($params)) {
417 // Check permission to create or modify reserved tag
418 if (!empty($params['check_permissions']) && !CRM_Core_Permission
::check('administer reserved tags')) {
419 if (!empty($params['is_reserved']) ||
($id && CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_reserved'))) {
420 throw new CRM_Core_Exception('Insufficient permission to administer reserved tag.');
424 // Check permission to create or modify tagset
425 if (!empty($params['check_permissions']) && !CRM_Core_Permission
::check('administer Tagsets')) {
426 if (!empty($params['is_tagset']) ||
($id && CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_tagset'))) {
427 throw new CRM_Core_Exception('Insufficient permission to administer tagset.');
431 $tag = new CRM_Core_DAO_Tag();
433 // if parent id is set then inherit used for and is hidden properties
434 if (!empty($params['parent_id'])) {
435 // get parent details
436 $params['used_for'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
438 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
439 $params['used_for'] = implode(',', $params['used_for']);
442 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
443 $params['color'] = '';
446 $tag->copyValues($params);
448 $hook = !$id ?
'create' : 'edit';
449 CRM_Utils_Hook
::pre($hook, 'Tag', $tag->id
, $params);
451 // save creator id and time
453 $session = CRM_Core_Session
::singleton();
454 $tag->created_id
= $session->get('userID');
455 $tag->created_date
= date('YmdHis');
459 CRM_Utils_Hook
::post($hook, 'Tag', $tag->id
, $tag);
461 // if we modify parent tag, then we need to update all children
463 if (!$tag->parent_id
&& $tag->used_for
) {
464 CRM_Core_DAO
::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
466 1 => [$tag->used_for
, 'String'],
467 2 => [$tag->id
, 'Integer'],
476 * Check if there is data to create the object.
478 * @param array $params
479 * (reference ) an assoc array of name/value pairs.
483 public static function dataExists(&$params) {
484 // Disallow empty values except for the number zero.
485 // TODO: create a utility for this since it's needed in many places
486 if (!empty($params['name']) ||
(string) $params['name'] === '0') {
494 * Get the tag sets for a entity object.
496 * @param string $entityTable
502 public static function getTagSet($entityTable) {
504 $query = "SELECT name, id FROM civicrm_tag
505 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
506 $dao = CRM_Core_DAO
::executeQuery($query, [
508 '%' . $entityTable . '%',
511 ], TRUE, NULL, FALSE, FALSE);
512 while ($dao->fetch()) {
513 $tagSets[$dao->id
] = $dao->name
;
519 * Get the tags that are not children of a tagset.
522 * associated array of tag name and id
524 public static function getTagsNotInTagset() {
525 $tags = $tagSets = [];
526 // first get all the tag sets
527 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
528 $dao = CRM_Core_DAO
::executeQuery($query);
529 while ($dao->fetch()) {
530 $tagSets[] = $dao->id
;
534 if (!empty($tagSets)) {
535 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
538 // get that tags that don't have tagset as parent
539 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
540 $dao = CRM_Core_DAO
::executeQuery($query);
541 while ($dao->fetch()) {
542 $tags[$dao->id
] = $dao->name
;
551 * @param string $searchString
554 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
556 public static function getChildTags($searchString = NULL) {
559 $whereClauses = ['parent.is_tagset <> 1'];
561 $whereClauses[] = " child.name LIKE '%$searchString%' ";
564 // only fetch those tags which has child tags
565 $dao = CRM_Utils_SQL_Select
::from('civicrm_tag parent')
566 ->join('child', 'INNER JOIN civicrm_tag child ON child.parent_id = parent.id ')
567 ->select('parent.id as parent_id, GROUP_CONCAT(child.id) as child_id')
568 ->where($whereClauses)
569 ->groupBy('parent.id')
571 while ($dao->fetch()) {
572 $childTagIDs[$dao->parent_id
] = (array) explode(',', $dao->child_id
);
573 $parentID = $dao->parent_id
;
575 // recursively search for parent tag ID and it's child if any
577 $newParentID = CRM_Core_DAO
::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
579 $childTagIDs[$newParentID] = [$parentID];
581 $parentID = $newParentID;
586 // check if child tag has any childs, if found then include those child tags inside parent tag
587 // i.e. format Array('parent_tag' => array('child_tag_1', ...), 'child_tag_1' => array(child_tag_1_1, ..), ..)
588 // to Array('parent_tag' => array('child_tag_1', 'child_tag_1_1'...), ..)
589 foreach ($childTagIDs as $parentTagID => $childTags) {
590 foreach ($childTags as $childTag) {
591 // if $childTag has any child tag of its own
592 if (array_key_exists($childTag, $childTagIDs)) {
593 $childTagIDs[$parentTagID] = array_merge($childTagIDs[$parentTagID], $childTagIDs[$childTag]);