Merge in 5.16
[civicrm-core.git] / CRM / Core / BAO / Tag.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33class CRM_Core_BAO_Tag extends CRM_Core_DAO_Tag {
34
f47539f6 35 /**
36 * @var array
37 */
38 protected $tree;
39
6a488035 40 /**
fe482240 41 * Class constructor.
6a488035 42 */
00be9182 43 public function __construct() {
6a488035
TO
44 parent::__construct();
45 }
46
47 /**
fe482240 48 * Fetch object based on array of properties.
6a488035 49 *
6a0b768e
TO
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.
6a488035 54 *
a6c01b45
CW
55 * @return object
56 * CRM_Core_DAO_Tag object on success, otherwise null
6a488035 57 */
00be9182 58 public static function retrieve(&$params, &$defaults) {
6a488035
TO
59 $tag = new CRM_Core_DAO_Tag();
60 $tag->copyValues($params);
61 if ($tag->find(TRUE)) {
62 CRM_Core_DAO::storeValues($tag, $defaults);
63 return $tag;
64 }
65 return NULL;
66 }
67
b5c2afd0 68 /**
f47539f6 69 * Get tag tree.
70 *
71 * @param string $usedFor
b5c2afd0
EM
72 * @param bool $excludeHidden
73 *
74 * @return mixed
75 */
00be9182 76 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
6a488035
TO
77 if (!isset($this->tree)) {
78 $this->buildTree($usedFor, $excludeHidden);
79 }
80 return $this->tree;
81 }
82
b5c2afd0 83 /**
f47539f6 84 * Build a nested array from hierarchical tags.
85 *
86 * Supports infinite levels of nesting.
b5c2afd0
EM
87 * @param null $usedFor
88 * @param bool $excludeHidden
89 */
00be9182 90 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
6dac2504 91 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
6a488035 92
be2fb01f 93 $whereClause = [];
6a488035
TO
94 if ($usedFor) {
95 $whereClause[] = "used_for like '%{$usedFor}%'";
96 }
97 if ($excludeHidden) {
98 $whereClause[] = "is_tagset = 0";
99 }
100
101 if (!empty($whereClause)) {
102 $sql .= " WHERE " . implode(' AND ', $whereClause);
103 }
104
105 $sql .= " ORDER BY parent_id,name";
106
be2fb01f 107 $dao = CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
6a488035 108
be2fb01f
CW
109 $refs = [];
110 $this->tree = [];
6a488035 111 while ($dao->fetch()) {
80257742
CW
112 $thisref = &$refs[$dao->id];
113
114 $thisref['parent_id'] = $dao->parent_id;
115 $thisref['name'] = $dao->name;
116 $thisref['description'] = $dao->description;
6dac2504 117 $thisref['is_selectable'] = $dao->is_selectable;
80257742 118
6a488035 119 if (!$dao->parent_id) {
80257742 120 $this->tree[$dao->id] = &$thisref;
6a488035
TO
121 }
122 else {
80257742 123 $refs[$dao->parent_id]['children'][$dao->id] = &$thisref;
6a488035
TO
124 }
125 }
6a488035
TO
126 }
127
b5c2afd0 128 /**
f47539f6 129 * Get tags used for the given entity/entities.
130 *
b5c2afd0
EM
131 * @param array $usedFor
132 * @param bool $buildSelect
133 * @param bool $all
100fef9d 134 * @param int $parentId
b5c2afd0
EM
135 *
136 * @return array
137 */
af9b09df 138 public static function getTagsUsedFor(
be2fb01f 139 $usedFor = ['civicrm_contact'],
af9b09df
TO
140 $buildSelect = TRUE,
141 $all = FALSE,
142 $parentId = NULL
6a488035 143 ) {
be2fb01f 144 $tags = [];
6a488035
TO
145
146 if (empty($usedFor)) {
147 return $tags;
148 }
149 if (!is_array($usedFor)) {
be2fb01f 150 $usedFor = [$usedFor];
6a488035
TO
151 }
152
153 if ($parentId === NULL) {
154 $parentClause = " parent_id IS NULL AND ";
155 }
156 else {
157 $parentClause = " parent_id = {$parentId} AND ";
158 }
159
160 foreach ($usedFor as $entityTable) {
161 $tag = new CRM_Core_DAO_Tag();
162 $tag->fields();
163 $tag->orderBy('parent_id');
164 if ($buildSelect) {
165 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
166 }
167 else {
168 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
169 }
170 if (!$all) {
171 $tag->is_tagset = 0;
172 }
173 $tag->find();
174
175 while ($tag->fetch()) {
176 if ($buildSelect) {
177 $tags[$tag->id] = $tag->name;
178 }
179 else {
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;
eb98e026 184 $tags[$tag->id]['description'] = $tag->description;
d73974ac 185 $tags[$tag->id]['color'] = !empty($tag->color) ? $tag->color : NULL;
6a488035
TO
186 }
187 }
6a488035
TO
188 }
189
190 return $tags;
191 }
192
b5c2afd0 193 /**
fe482240 194 * Function to retrieve tags.
47358d92 195 *
6a0b768e
TO
196 * @param string $usedFor
197 * Which type of tag entity.
198 * @param array $tags
199 * Tags array.
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.
47358d92 206 * tag, so they cannot be selected
b5c2afd0
EM
207 *
208 * @return array
209 */
2da40d21 210 public static function getTags(
f9f40af3 211 $usedFor = 'civicrm_contact',
be2fb01f 212 &$tags = [],
2aa397bc 213 $parentId = NULL,
47358d92 214 $separator = '&nbsp;&nbsp;',
215 $formatSelectable = FALSE
6a488035 216 ) {
dee5ccbb 217 if (!is_array($tags)) {
be2fb01f 218 $tags = [];
dee5ccbb 219 }
6a488035 220 // We need to build a list of tags ordered by hierarchy and sorted by
b44e3f84 221 // name. The hierarchy will be communicated by an accumulation of
6a488035
TO
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
b44e3f84 224 // query and build the hierarchy with the algorithm below.
be2fb01f 225 $args = [1 => ['%' . $usedFor . '%', 'String']];
47358d92 226 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
6a488035
TO
227 FROM civicrm_tag
228 WHERE used_for LIKE %1";
229 if ($parentId) {
230 $query .= " AND parent_id = %2";
be2fb01f 231 $args[2] = [$parentId, 'Integer'];
6a488035
TO
232 }
233 $query .= " ORDER BY name";
234 $dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
235
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.
be2fb01f 241 $roots = $rows = [];
6a488035 242 while ($dao->fetch()) {
47358d92 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
249 $idPrefix = '';
250 if ($formatSelectable && !$dao->is_selectable) {
251 $idPrefix = "crm_disabled_opt";
252 }
6a488035 253 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
be2fb01f 254 $roots[] = [
47358d92 255 'id' => $dao->id,
256 'prefix' => '',
257 'name' => $dao->name,
258 'idPrefix' => $idPrefix,
be2fb01f 259 ];
6a488035
TO
260 }
261 else {
be2fb01f 262 $rows[] = [
47358d92 263 'id' => $dao->id,
264 'prefix' => '',
265 'name' => $dao->name,
266 'parent_id' => $dao->parent_id,
267 'idPrefix' => $idPrefix,
be2fb01f 268 ];
6a488035
TO
269 }
270 }
47358d92 271
6a488035
TO
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
276 // during the loop.
277 while (count($roots)) {
be2fb01f 278 $new_roots = [];
353ffa53
TO
279 $current_rows = $rows;
280 $root = array_shift($roots);
be2fb01f 281 $tags[$root['id']] = [
47358d92 282 $root['prefix'],
283 $root['name'],
284 $root['idPrefix'],
be2fb01f 285 ];
6a488035
TO
286
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']) {
be2fb01f 293 $new_roots[] = [
47358d92 294 'id' => $row['id'],
295 'prefix' => $tags[$root['id']][0] . $separator,
296 'name' => $row['name'],
297 'idPrefix' => $row['idPrefix'],
be2fb01f 298 ];
6a488035
TO
299 unset($rows[$key]);
300 }
301 }
302 }
303
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);
307 }
308
309 // Prefix each name with the calcuated spacing to give the visual
310 // appearance of ordering when transformed into HTML in the form layer.
47358d92 311 // here is the actual code that to prepends and set disabled attribute for
312 // non-selectable tags
be2fb01f 313 $formattedTags = [];
47358d92 314 foreach ($tags as $key => $tag) {
315 if (!empty($tag[2])) {
86bfa4f6 316 $key = $tag[2] . "-" . $key;
47358d92 317 }
318 $formattedTags[$key] = $tag[0] . $tag[1];
6a488035
TO
319 }
320
47358d92 321 $tags = $formattedTags;
6a488035
TO
322 return $tags;
323 }
324
b733747a
CW
325 /**
326 * @param string $usedFor
327 * @param bool $allowSelectingNonSelectable
328 * @param null $exclude
329 * @return array
330 * @throws \CiviCRM_API3_Exception
331 */
332 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
be2fb01f
CW
333 $params = [
334 'options' => [
016cf488 335 'limit' => 0,
336 'sort' => "name ASC",
be2fb01f 337 ],
b733747a 338 'is_tagset' => 0,
be2fb01f
CW
339 'return' => ['name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'],
340 ];
b733747a 341 if ($usedFor) {
be2fb01f 342 $params['used_for'] = ['LIKE' => "%$usedFor%"];
b733747a
CW
343 }
344 if ($exclude) {
be2fb01f 345 $params['id'] = ['!=' => $exclude];
b733747a 346 }
be2fb01f 347 $allTags = [];
b733747a 348 foreach (CRM_Utils_Array::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
be2fb01f 349 $allTags[$id] = [
b733747a
CW
350 'text' => $tag['name'],
351 'id' => $id,
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),
be2fb01f 356 ];
b733747a
CW
357 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
358 $allTags[$id]['disabled'] = TRUE;
359 }
360 }
361 return CRM_Utils_Array::buildTree($allTags);
362 }
363
6a488035 364 /**
fe482240 365 * Delete the tag.
6a488035 366 *
6a0b768e
TO
367 * @param int $id
368 * Tag id.
6a488035 369 *
5c766a0b 370 * @return bool
6a488035 371 */
00be9182 372 public static function del($id) {
6a488035 373 // since this is a destructive operation, lets make sure
b44e3f84 374 // id is a positive number
6a488035
TO
375 CRM_Utils_Type::validate($id, 'Positive');
376
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();
381
382 // delete from tag table
383 $tag = new CRM_Core_DAO_Tag();
384 $tag->id = $id;
385
386 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
387
388 if ($tag->delete()) {
389 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
6a488035
TO
390 return TRUE;
391 }
392 return FALSE;
393 }
394
395 /**
bd525987 396 * Takes an associative array and creates a tag object.
6a488035
TO
397 *
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
400 * pairs
401 *
6a0b768e
TO
402 * @param array $params
403 * (reference) an assoc array of name/value pairs.
404 * @param array $ids
405 * (optional) the array that holds all the db ids - we are moving away from this in bao.
d989d349 406 * signatures
6a488035 407 *
d3cbd0a5
CW
408 * @return CRM_Core_DAO_Tag|null
409 * object on success, otherwise null
6a488035 410 */
be2fb01f 411 public static function add(&$params, $ids = []) {
9b576df4
EM
412 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
413 if (!$id && !self::dataExists($params)) {
6a488035
TO
414 return NULL;
415 }
416
592dd7d8
CW
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.');
421 }
422 }
423
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.');
428 }
429 }
430
6a488035
TO
431 $tag = new CRM_Core_DAO_Tag();
432
433 // if parent id is set then inherit used for and is hidden properties
a7488080 434 if (!empty($params['parent_id'])) {
6a488035
TO
435 // get parent details
436 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
437 }
d3cbd0a5
CW
438 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
439 $params['used_for'] = implode(',', $params['used_for']);
440 }
441
442 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
443 $params['color'] = '';
444 }
6a488035
TO
445
446 $tag->copyValues($params);
9b576df4
EM
447 $tag->id = $id;
448 $hook = !$id ? 'create' : 'edit';
d989d349 449 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
6a488035
TO
450
451 // save creator id and time
452 if (!$tag->id) {
353ffa53
TO
453 $session = CRM_Core_Session::singleton();
454 $tag->created_id = $session->get('userID');
6a488035
TO
455 $tag->created_date = date('YmdHis');
456 }
457
458 $tag->save();
d989d349 459 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
6a488035
TO
460
461 // if we modify parent tag, then we need to update all children
d3cbd0a5
CW
462 $tag->find(TRUE);
463 if (!$tag->parent_id && $tag->used_for) {
6a488035 464 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
be2fb01f
CW
465 [
466 1 => [$tag->used_for, 'String'],
467 2 => [$tag->id, 'Integer'],
468 ]
6a488035
TO
469 );
470 }
471
472 return $tag;
473 }
474
475 /**
fe482240 476 * Check if there is data to create the object.
6a488035 477 *
6a0b768e
TO
478 * @param array $params
479 * (reference ) an assoc array of name/value pairs.
6a488035 480 *
5c766a0b 481 * @return bool
6a488035 482 */
00be9182 483 public static function dataExists(&$params) {
5ba3bfc8
CW
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') {
6a488035
TO
487 return TRUE;
488 }
489
490 return FALSE;
491 }
492
493 /**
fe482240 494 * Get the tag sets for a entity object.
6a488035 495 *
6a0b768e
TO
496 * @param string $entityTable
497 * Entity_table.
6a488035 498 *
a6c01b45
CW
499 * @return array
500 * array of tag sets
6a488035 501 */
00be9182 502 public static function getTagSet($entityTable) {
be2fb01f 503 $tagSets = [];
6a488035
TO
504 $query = "SELECT name, id FROM civicrm_tag
505 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
be2fb01f 506 $dao = CRM_Core_DAO::executeQuery($query, [
518fa0ee
SL
507 1 => [
508 '%' . $entityTable . '%',
509 'String',
510 ],
511 ], TRUE, NULL, FALSE, FALSE);
6a488035
TO
512 while ($dao->fetch()) {
513 $tagSets[$dao->id] = $dao->name;
514 }
6a488035
TO
515 return $tagSets;
516 }
517
518 /**
100fef9d 519 * Get the tags that are not children of a tagset.
6a488035 520 *
a6c01b45
CW
521 * @return array
522 * associated array of tag name and id
6a488035 523 */
00be9182 524 public static function getTagsNotInTagset() {
be2fb01f 525 $tags = $tagSets = [];
6a488035
TO
526 // first get all the tag sets
527 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
33621c4f 528 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
529 while ($dao->fetch()) {
530 $tagSets[] = $dao->id;
531 }
532
533 $parentClause = '';
534 if (!empty($tagSets)) {
535 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
536 }
537
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;
543 }
544
545 return $tags;
546 }
96025800 547
dfe61fcf 548 /**
549 * Get child tags IDs
550 *
6e80ee11 551 * @param string $searchString
552 *
518fa0ee 553 * @return array
dfe61fcf 554 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
555 */
6e80ee11 556 public static function getChildTags($searchString = NULL) {
be2fb01f 557 $childTagIDs = [];
dfe61fcf 558
be2fb01f 559 $whereClauses = ['parent.is_tagset <> 1'];
6e80ee11 560 if ($searchString) {
561 $whereClauses[] = " child.name LIKE '%$searchString%' ";
562 }
563
dfe61fcf 564 // only fetch those tags which has child tags
6e80ee11 565 $dao = CRM_Utils_SQL_Select::from('civicrm_tag parent')
518fa0ee
SL
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')
570 ->execute();
dfe61fcf 571 while ($dao->fetch()) {
572 $childTagIDs[$dao->parent_id] = (array) explode(',', $dao->child_id);
97dcf1d8 573 $parentID = $dao->parent_id;
574 if ($searchString) {
575 // recursively search for parent tag ID and it's child if any
576 while ($parentID) {
577 $newParentID = CRM_Core_DAO::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
578 if ($newParentID) {
be2fb01f 579 $childTagIDs[$newParentID] = [$parentID];
97dcf1d8 580 }
581 $parentID = $newParentID;
582 }
583 }
dfe61fcf 584 }
585
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]);
594 }
595 }
596 }
597
598 return $childTagIDs;
599 }
600
6a488035 601}