CRM-20621 : manage tags: the tag usage count is not accurate
[civicrm-core.git] / CRM / Core / BAO / Tag.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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
TO
92
93 $whereClause = array();
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
f47539f6 107 $dao = CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
6a488035 108
80257742 109 $refs = array();
54d33f28 110 $this->tree = array();
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
TO
138 public static function getTagsUsedFor(
139 $usedFor = array('civicrm_contact'),
140 $buildSelect = TRUE,
141 $all = FALSE,
142 $parentId = NULL
6a488035
TO
143 ) {
144 $tags = array();
145
146 if (empty($usedFor)) {
147 return $tags;
148 }
149 if (!is_array($usedFor)) {
150 $usedFor = array($usedFor);
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 }
188 $tag->free();
189 }
190
191 return $tags;
192 }
193
b5c2afd0 194 /**
fe482240 195 * Function to retrieve tags.
47358d92 196 *
6a0b768e
TO
197 * @param string $usedFor
198 * Which type of tag entity.
199 * @param array $tags
200 * Tags array.
201 * @param int $parentId
202 * Parent id if you want need only children.
203 * @param string $separator
204 * Separator to indicate children.
205 * @param bool $formatSelectable
206 * Add special property for non-selectable.
47358d92 207 * tag, so they cannot be selected
b5c2afd0
EM
208 *
209 * @return array
210 */
2da40d21 211 public static function getTags(
f9f40af3 212 $usedFor = 'civicrm_contact',
6a488035 213 &$tags = array(),
2aa397bc 214 $parentId = NULL,
47358d92 215 $separator = '&nbsp;&nbsp;',
216 $formatSelectable = FALSE
6a488035 217 ) {
dee5ccbb
CW
218 if (!is_array($tags)) {
219 $tags = array();
220 }
6a488035 221 // We need to build a list of tags ordered by hierarchy and sorted by
b44e3f84 222 // name. The hierarchy will be communicated by an accumulation of
6a488035
TO
223 // separators in front of the name to give it a visual offset.
224 // Instead of recursively making mysql queries, we'll make one big
b44e3f84 225 // query and build the hierarchy with the algorithm below.
6a488035 226 $args = array(1 => array('%' . $usedFor . '%', 'String'));
47358d92 227 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
6a488035
TO
228 FROM civicrm_tag
229 WHERE used_for LIKE %1";
230 if ($parentId) {
231 $query .= " AND parent_id = %2";
232 $args[2] = array($parentId, 'Integer');
233 }
234 $query .= " ORDER BY name";
235 $dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
236
237 // Sort the tags into the correct storage by the parent_id/is_tagset
238 // filter the filter was in place previously, we're just reusing it.
239 // $roots represents the current leaf nodes that need to be checked for
240 // children. $rows represents the unplaced nodes, not all of much
241 // are necessarily placed.
242 $roots = $rows = array();
243 while ($dao->fetch()) {
47358d92 244 // note that we are prepending id with "crm_disabled_opt" which identifies
245 // them as disabled so that they cannot be selected. We do some magic
246 // in crm-select2 js function that marks option values to "disabled"
247 // current QF version in CiviCRM does not support passing this attribute,
248 // so this is another ugly hack / workaround,
249 // also know one is too keen to upgrade QF :P
250 $idPrefix = '';
251 if ($formatSelectable && !$dao->is_selectable) {
252 $idPrefix = "crm_disabled_opt";
253 }
6a488035 254 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
47358d92 255 $roots[] = array(
256 'id' => $dao->id,
257 'prefix' => '',
258 'name' => $dao->name,
259 'idPrefix' => $idPrefix,
353ffa53 260 );
6a488035
TO
261 }
262 else {
47358d92 263 $rows[] = array(
264 'id' => $dao->id,
265 'prefix' => '',
266 'name' => $dao->name,
267 'parent_id' => $dao->parent_id,
268 'idPrefix' => $idPrefix,
353ffa53 269 );
6a488035
TO
270 }
271 }
47358d92 272
6a488035
TO
273 $dao->free();
274 // While we have nodes left to build, shift the first (alphabetically)
275 // node of the list, place it in our tags list and loop through the
276 // list of unplaced nodes to find its children. We make a copy to
277 // iterate through because we must modify the unplaced nodes list
278 // during the loop.
279 while (count($roots)) {
353ffa53
TO
280 $new_roots = array();
281 $current_rows = $rows;
282 $root = array_shift($roots);
47358d92 283 $tags[$root['id']] = array(
284 $root['prefix'],
285 $root['name'],
286 $root['idPrefix'],
353ffa53 287 );
6a488035
TO
288
289 // As you find the children, append them to the end of the new set
290 // of roots (maintain alphabetical ordering). Also remove the node
291 // from the set of unplaced nodes.
292 if (is_array($current_rows)) {
293 foreach ($current_rows as $key => $row) {
294 if ($row['parent_id'] == $root['id']) {
47358d92 295 $new_roots[] = array(
296 'id' => $row['id'],
297 'prefix' => $tags[$root['id']][0] . $separator,
298 'name' => $row['name'],
299 'idPrefix' => $row['idPrefix'],
353ffa53 300 );
6a488035
TO
301 unset($rows[$key]);
302 }
303 }
304 }
305
306 //As a group, insert the new roots into the beginning of the roots
307 //list. This maintains the hierarchical ordering of the tags.
308 $roots = array_merge($new_roots, $roots);
309 }
310
311 // Prefix each name with the calcuated spacing to give the visual
312 // appearance of ordering when transformed into HTML in the form layer.
47358d92 313 // here is the actual code that to prepends and set disabled attribute for
314 // non-selectable tags
315 $formattedTags = array();
316 foreach ($tags as $key => $tag) {
317 if (!empty($tag[2])) {
86bfa4f6 318 $key = $tag[2] . "-" . $key;
47358d92 319 }
320 $formattedTags[$key] = $tag[0] . $tag[1];
6a488035
TO
321 }
322
47358d92 323 $tags = $formattedTags;
6a488035
TO
324 return $tags;
325 }
326
b733747a
CW
327 /**
328 * @param string $usedFor
329 * @param bool $allowSelectingNonSelectable
330 * @param null $exclude
331 * @return array
332 * @throws \CiviCRM_API3_Exception
333 */
334 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
335 $params = array(
336 'options' => array('limit' => 0),
337 'is_tagset' => 0,
338 'return' => array('name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'),
339 );
340 if ($usedFor) {
341 $params['used_for'] = array('LIKE' => "%$usedFor%");
342 }
343 if ($exclude) {
344 $params['id'] = array('!=' => $exclude);
345 }
346 $allTags = array();
347 foreach (CRM_Utils_Array::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
348 $allTags[$id] = array(
349 'text' => $tag['name'],
350 'id' => $id,
351 'description' => CRM_Utils_Array::value('description', $tag),
352 'parent_id' => CRM_Utils_Array::value('parent_id', $tag),
353 'used_for' => CRM_Utils_Array::value('used_for', $tag),
354 'color' => CRM_Utils_Array::value('color', $tag),
355 );
356 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
357 $allTags[$id]['disabled'] = TRUE;
358 }
359 }
360 return CRM_Utils_Array::buildTree($allTags);
361 }
362
6a488035 363 /**
fe482240 364 * Delete the tag.
6a488035 365 *
6a0b768e
TO
366 * @param int $id
367 * Tag id.
6a488035 368 *
5c766a0b 369 * @return bool
6a488035 370 */
00be9182 371 public static function del($id) {
6a488035 372 // since this is a destructive operation, lets make sure
b44e3f84 373 // id is a positive number
6a488035
TO
374 CRM_Utils_Type::validate($id, 'Positive');
375
376 // delete all crm_entity_tag records with the selected tag id
377 $entityTag = new CRM_Core_DAO_EntityTag();
378 $entityTag->tag_id = $id;
379 $entityTag->delete();
380
381 // delete from tag table
382 $tag = new CRM_Core_DAO_Tag();
383 $tag->id = $id;
384
385 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
386
387 if ($tag->delete()) {
388 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
6a488035
TO
389 return TRUE;
390 }
391 return FALSE;
392 }
393
394 /**
bd525987 395 * Takes an associative array and creates a tag object.
6a488035
TO
396 *
397 * The function extract all the params it needs to initialize the create a
398 * contact object. the params array could contain additional unused name/value
399 * pairs
400 *
6a0b768e
TO
401 * @param array $params
402 * (reference) an assoc array of name/value pairs.
403 * @param array $ids
404 * (optional) the array that holds all the db ids - we are moving away from this in bao.
d989d349 405 * signatures
6a488035 406 *
d3cbd0a5
CW
407 * @return CRM_Core_DAO_Tag|null
408 * object on success, otherwise null
6a488035 409 */
00be9182 410 public static function add(&$params, $ids = array()) {
9b576df4
EM
411 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
412 if (!$id && !self::dataExists($params)) {
6a488035
TO
413 return NULL;
414 }
415
416 $tag = new CRM_Core_DAO_Tag();
417
418 // if parent id is set then inherit used for and is hidden properties
a7488080 419 if (!empty($params['parent_id'])) {
6a488035
TO
420 // get parent details
421 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
422 }
d3cbd0a5
CW
423 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
424 $params['used_for'] = implode(',', $params['used_for']);
425 }
426
427 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
428 $params['color'] = '';
429 }
6a488035
TO
430
431 $tag->copyValues($params);
9b576df4
EM
432 $tag->id = $id;
433 $hook = !$id ? 'create' : 'edit';
d989d349 434 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
6a488035
TO
435
436 // save creator id and time
437 if (!$tag->id) {
353ffa53
TO
438 $session = CRM_Core_Session::singleton();
439 $tag->created_id = $session->get('userID');
6a488035
TO
440 $tag->created_date = date('YmdHis');
441 }
442
443 $tag->save();
d989d349 444 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
6a488035
TO
445
446 // if we modify parent tag, then we need to update all children
d3cbd0a5
CW
447 $tag->find(TRUE);
448 if (!$tag->parent_id && $tag->used_for) {
6a488035 449 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
2aa397bc 450 array(
d3cbd0a5 451 1 => array($tag->used_for, 'String'),
6a488035
TO
452 2 => array($tag->id, 'Integer'),
453 )
454 );
455 }
456
457 return $tag;
458 }
459
460 /**
fe482240 461 * Check if there is data to create the object.
6a488035 462 *
6a0b768e
TO
463 * @param array $params
464 * (reference ) an assoc array of name/value pairs.
6a488035 465 *
5c766a0b 466 * @return bool
6a488035 467 */
00be9182 468 public static function dataExists(&$params) {
5ba3bfc8
CW
469 // Disallow empty values except for the number zero.
470 // TODO: create a utility for this since it's needed in many places
471 if (!empty($params['name']) || (string) $params['name'] === '0') {
6a488035
TO
472 return TRUE;
473 }
474
475 return FALSE;
476 }
477
478 /**
fe482240 479 * Get the tag sets for a entity object.
6a488035 480 *
6a0b768e
TO
481 * @param string $entityTable
482 * Entity_table.
6a488035 483 *
a6c01b45
CW
484 * @return array
485 * array of tag sets
6a488035 486 */
00be9182 487 public static function getTagSet($entityTable) {
6a488035
TO
488 $tagSets = array();
489 $query = "SELECT name, id FROM civicrm_tag
490 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
353ffa53
TO
491 $dao = CRM_Core_DAO::executeQuery($query, array(
492 1 => array(
493 '%' . $entityTable . '%',
af9b09df
TO
494 'String',
495 ),
353ffa53 496 ), TRUE, NULL, FALSE, FALSE);
6a488035
TO
497 while ($dao->fetch()) {
498 $tagSets[$dao->id] = $dao->name;
499 }
500 $dao->free();
501 return $tagSets;
502 }
503
504 /**
100fef9d 505 * Get the tags that are not children of a tagset.
6a488035 506 *
a6c01b45
CW
507 * @return array
508 * associated array of tag name and id
6a488035 509 */
00be9182 510 public static function getTagsNotInTagset() {
6a488035
TO
511 $tags = $tagSets = array();
512 // first get all the tag sets
513 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
33621c4f 514 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
515 while ($dao->fetch()) {
516 $tagSets[] = $dao->id;
517 }
518
519 $parentClause = '';
520 if (!empty($tagSets)) {
521 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
522 }
523
524 // get that tags that don't have tagset as parent
525 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
526 $dao = CRM_Core_DAO::executeQuery($query);
527 while ($dao->fetch()) {
528 $tags[$dao->id] = $dao->name;
529 }
530
531 return $tags;
532 }
96025800 533
dfe61fcf 534 /**
535 * Get child tags IDs
536 *
537 * @return array $childTagIDs
538 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
539 */
540 public static function getChildTags() {
541 $childTagIDs = array();
542
543 // only fetch those tags which has child tags
544 $getChildGroupSQL = "SELECT parent.id as parent_id, GROUP_CONCAT(child.id) as child_id
545 FROM civicrm_tag parent,
546 civicrm_tag child
547 WHERE parent.is_tagset <> 1 AND child.parent_id = parent.id
548 GROUP BY parent.id
549 ";
550 $dao = CRM_Core_DAO::executeQuery($getChildGroupSQL);
551 while ($dao->fetch()) {
552 $childTagIDs[$dao->parent_id] = (array) explode(',', $dao->child_id);
553 }
554
555 // check if child tag has any childs, if found then include those child tags inside parent tag
556 // i.e. format Array('parent_tag' => array('child_tag_1', ...), 'child_tag_1' => array(child_tag_1_1, ..), ..)
557 // to Array('parent_tag' => array('child_tag_1', 'child_tag_1_1'...), ..)
558 foreach ($childTagIDs as $parentTagID => $childTags) {
559 foreach ($childTags as $childTag) {
560 // if $childTag has any child tag of its own
561 if (array_key_exists($childTag, $childTagIDs)) {
562 $childTagIDs[$parentTagID] = array_merge($childTagIDs[$parentTagID], $childTagIDs[$childTag]);
563 }
564 }
565 }
566
567 return $childTagIDs;
568 }
569
6a488035 570}