CRM-19943 - New manage tags UI with jstree
[civicrm-core.git] / CRM / Core / BAO / Tag.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2017
32 * $Id$
33 *
34 */
35 class CRM_Core_BAO_Tag extends CRM_Core_DAO_Tag {
36
37 /**
38 * Class constructor.
39 */
40 public function __construct() {
41 parent::__construct();
42 }
43
44 /**
45 * Fetch object based on array of properties.
46 *
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param array $defaults
50 * (reference ) an assoc array to hold the flattened values.
51 *
52 * @return object
53 * CRM_Core_DAO_Tag object on success, otherwise null
54 */
55 public static function retrieve(&$params, &$defaults) {
56 $tag = new CRM_Core_DAO_Tag();
57 $tag->copyValues($params);
58 if ($tag->find(TRUE)) {
59 CRM_Core_DAO::storeValues($tag, $defaults);
60 return $tag;
61 }
62 return NULL;
63 }
64
65 /**
66 * @param null $usedFor
67 * @param bool $excludeHidden
68 *
69 * @return mixed
70 */
71 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
72 if (!isset($this->tree)) {
73 $this->buildTree($usedFor, $excludeHidden);
74 }
75 return $this->tree;
76 }
77
78 /**
79 * Build a nested array from hierarchical tags. Supports infinite levels of nesting.
80 * @param null $usedFor
81 * @param bool $excludeHidden
82 */
83 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
84 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
85
86 $whereClause = array();
87 if ($usedFor) {
88 $whereClause[] = "used_for like '%{$usedFor}%'";
89 }
90 if ($excludeHidden) {
91 $whereClause[] = "is_tagset = 0";
92 }
93
94 if (!empty($whereClause)) {
95 $sql .= " WHERE " . implode(' AND ', $whereClause);
96 }
97
98 $sql .= " ORDER BY parent_id,name";
99
100 $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
101
102 $refs = array();
103 $this->tree = array();
104 while ($dao->fetch()) {
105 $thisref = &$refs[$dao->id];
106
107 $thisref['parent_id'] = $dao->parent_id;
108 $thisref['name'] = $dao->name;
109 $thisref['description'] = $dao->description;
110 $thisref['is_selectable'] = $dao->is_selectable;
111
112 if (!$dao->parent_id) {
113 $this->tree[$dao->id] = &$thisref;
114 }
115 else {
116 $refs[$dao->parent_id]['children'][$dao->id] = &$thisref;
117 }
118 }
119 }
120
121 /**
122 * @param array $usedFor
123 * @param bool $buildSelect
124 * @param bool $all
125 * @param int $parentId
126 *
127 * @return array
128 */
129 public static function getTagsUsedFor(
130 $usedFor = array('civicrm_contact'),
131 $buildSelect = TRUE,
132 $all = FALSE,
133 $parentId = NULL
134 ) {
135 $tags = array();
136
137 if (empty($usedFor)) {
138 return $tags;
139 }
140 if (!is_array($usedFor)) {
141 $usedFor = array($usedFor);
142 }
143
144 if ($parentId === NULL) {
145 $parentClause = " parent_id IS NULL AND ";
146 }
147 else {
148 $parentClause = " parent_id = {$parentId} AND ";
149 }
150
151 foreach ($usedFor as $entityTable) {
152 $tag = new CRM_Core_DAO_Tag();
153 $tag->fields();
154 $tag->orderBy('parent_id');
155 if ($buildSelect) {
156 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
157 }
158 else {
159 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
160 }
161 if (!$all) {
162 $tag->is_tagset = 0;
163 }
164 $tag->find();
165
166 while ($tag->fetch()) {
167 if ($buildSelect) {
168 $tags[$tag->id] = $tag->name;
169 }
170 else {
171 $tags[$tag->id]['name'] = $tag->name;
172 $tags[$tag->id]['parent_id'] = $tag->parent_id;
173 $tags[$tag->id]['is_tagset'] = $tag->is_tagset;
174 $tags[$tag->id]['used_for'] = $tag->used_for;
175 $tags[$tag->id]['description'] = $tag->description;
176 $tags[$tag->id]['color'] = !empty($tag->color) ? $tag->color : NULL;
177 }
178 }
179 $tag->free();
180 }
181
182 return $tags;
183 }
184
185 /**
186 * Function to retrieve tags.
187 *
188 * @param string $usedFor
189 * Which type of tag entity.
190 * @param array $tags
191 * Tags array.
192 * @param int $parentId
193 * Parent id if you want need only children.
194 * @param string $separator
195 * Separator to indicate children.
196 * @param bool $formatSelectable
197 * Add special property for non-selectable.
198 * tag, so they cannot be selected
199 *
200 * @return array
201 */
202 public static function getTags(
203 $usedFor = 'civicrm_contact',
204 &$tags = array(),
205 $parentId = NULL,
206 $separator = '&nbsp;&nbsp;',
207 $formatSelectable = FALSE
208 ) {
209 if (!is_array($tags)) {
210 $tags = array();
211 }
212 // We need to build a list of tags ordered by hierarchy and sorted by
213 // name. The hierarchy will be communicated by an accumulation of
214 // separators in front of the name to give it a visual offset.
215 // Instead of recursively making mysql queries, we'll make one big
216 // query and build the hierarchy with the algorithm below.
217 $args = array(1 => array('%' . $usedFor . '%', 'String'));
218 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
219 FROM civicrm_tag
220 WHERE used_for LIKE %1";
221 if ($parentId) {
222 $query .= " AND parent_id = %2";
223 $args[2] = array($parentId, 'Integer');
224 }
225 $query .= " ORDER BY name";
226 $dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
227
228 // Sort the tags into the correct storage by the parent_id/is_tagset
229 // filter the filter was in place previously, we're just reusing it.
230 // $roots represents the current leaf nodes that need to be checked for
231 // children. $rows represents the unplaced nodes, not all of much
232 // are necessarily placed.
233 $roots = $rows = array();
234 while ($dao->fetch()) {
235 // note that we are prepending id with "crm_disabled_opt" which identifies
236 // them as disabled so that they cannot be selected. We do some magic
237 // in crm-select2 js function that marks option values to "disabled"
238 // current QF version in CiviCRM does not support passing this attribute,
239 // so this is another ugly hack / workaround,
240 // also know one is too keen to upgrade QF :P
241 $idPrefix = '';
242 if ($formatSelectable && !$dao->is_selectable) {
243 $idPrefix = "crm_disabled_opt";
244 }
245 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
246 $roots[] = array(
247 'id' => $dao->id,
248 'prefix' => '',
249 'name' => $dao->name,
250 'idPrefix' => $idPrefix,
251 );
252 }
253 else {
254 $rows[] = array(
255 'id' => $dao->id,
256 'prefix' => '',
257 'name' => $dao->name,
258 'parent_id' => $dao->parent_id,
259 'idPrefix' => $idPrefix,
260 );
261 }
262 }
263
264 $dao->free();
265 // While we have nodes left to build, shift the first (alphabetically)
266 // node of the list, place it in our tags list and loop through the
267 // list of unplaced nodes to find its children. We make a copy to
268 // iterate through because we must modify the unplaced nodes list
269 // during the loop.
270 while (count($roots)) {
271 $new_roots = array();
272 $current_rows = $rows;
273 $root = array_shift($roots);
274 $tags[$root['id']] = array(
275 $root['prefix'],
276 $root['name'],
277 $root['idPrefix'],
278 );
279
280 // As you find the children, append them to the end of the new set
281 // of roots (maintain alphabetical ordering). Also remove the node
282 // from the set of unplaced nodes.
283 if (is_array($current_rows)) {
284 foreach ($current_rows as $key => $row) {
285 if ($row['parent_id'] == $root['id']) {
286 $new_roots[] = array(
287 'id' => $row['id'],
288 'prefix' => $tags[$root['id']][0] . $separator,
289 'name' => $row['name'],
290 'idPrefix' => $row['idPrefix'],
291 );
292 unset($rows[$key]);
293 }
294 }
295 }
296
297 //As a group, insert the new roots into the beginning of the roots
298 //list. This maintains the hierarchical ordering of the tags.
299 $roots = array_merge($new_roots, $roots);
300 }
301
302 // Prefix each name with the calcuated spacing to give the visual
303 // appearance of ordering when transformed into HTML in the form layer.
304 // here is the actual code that to prepends and set disabled attribute for
305 // non-selectable tags
306 $formattedTags = array();
307 foreach ($tags as $key => $tag) {
308 if (!empty($tag[2])) {
309 $key = $tag[2] . "-" . $key;
310 }
311 $formattedTags[$key] = $tag[0] . $tag[1];
312 }
313
314 $tags = $formattedTags;
315 return $tags;
316 }
317
318 /**
319 * @param string $usedFor
320 * @param bool $allowSelectingNonSelectable
321 * @param null $exclude
322 * @return array
323 * @throws \CiviCRM_API3_Exception
324 */
325 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
326 $params = array(
327 'options' => array('limit' => 0),
328 'is_tagset' => 0,
329 'return' => array('name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'),
330 );
331 if ($usedFor) {
332 $params['used_for'] = array('LIKE' => "%$usedFor%");
333 }
334 if ($exclude) {
335 $params['id'] = array('!=' => $exclude);
336 }
337 $allTags = array();
338 foreach (CRM_Utils_Array::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
339 $allTags[$id] = array(
340 'text' => $tag['name'],
341 'id' => $id,
342 'description' => CRM_Utils_Array::value('description', $tag),
343 'parent_id' => CRM_Utils_Array::value('parent_id', $tag),
344 'used_for' => CRM_Utils_Array::value('used_for', $tag),
345 'color' => CRM_Utils_Array::value('color', $tag),
346 );
347 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
348 $allTags[$id]['disabled'] = TRUE;
349 }
350 }
351 return CRM_Utils_Array::buildTree($allTags);
352 }
353
354 /**
355 * Delete the tag.
356 *
357 * @param int $id
358 * Tag id.
359 *
360 * @return bool
361 */
362 public static function del($id) {
363 // since this is a destructive operation, lets make sure
364 // id is a positive number
365 CRM_Utils_Type::validate($id, 'Positive');
366
367 // delete all crm_entity_tag records with the selected tag id
368 $entityTag = new CRM_Core_DAO_EntityTag();
369 $entityTag->tag_id = $id;
370 $entityTag->delete();
371
372 // delete from tag table
373 $tag = new CRM_Core_DAO_Tag();
374 $tag->id = $id;
375
376 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
377
378 if ($tag->delete()) {
379 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
380 return TRUE;
381 }
382 return FALSE;
383 }
384
385 /**
386 * Takes an associative array and creates a tag object.
387 *
388 * The function extract all the params it needs to initialize the create a
389 * contact object. the params array could contain additional unused name/value
390 * pairs
391 *
392 * @param array $params
393 * (reference) an assoc array of name/value pairs.
394 * @param array $ids
395 * (optional) the array that holds all the db ids - we are moving away from this in bao.
396 * signatures
397 *
398 * @return CRM_Core_DAO_Tag|null
399 * object on success, otherwise null
400 */
401 public static function add(&$params, $ids = array()) {
402 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
403 if (!$id && !self::dataExists($params)) {
404 return NULL;
405 }
406
407 $tag = new CRM_Core_DAO_Tag();
408
409 // if parent id is set then inherit used for and is hidden properties
410 if (!empty($params['parent_id'])) {
411 // get parent details
412 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
413 }
414 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
415 $params['used_for'] = implode(',', $params['used_for']);
416 }
417
418 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
419 $params['color'] = '';
420 }
421
422 $tag->copyValues($params);
423 $tag->id = $id;
424 $hook = !$id ? 'create' : 'edit';
425 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
426
427 // save creator id and time
428 if (!$tag->id) {
429 $session = CRM_Core_Session::singleton();
430 $tag->created_id = $session->get('userID');
431 $tag->created_date = date('YmdHis');
432 }
433
434 $tag->save();
435 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
436
437 // if we modify parent tag, then we need to update all children
438 $tag->find(TRUE);
439 if (!$tag->parent_id && $tag->used_for) {
440 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
441 array(
442 1 => array($tag->used_for, 'String'),
443 2 => array($tag->id, 'Integer'),
444 )
445 );
446 }
447
448 return $tag;
449 }
450
451 /**
452 * Check if there is data to create the object.
453 *
454 * @param array $params
455 * (reference ) an assoc array of name/value pairs.
456 *
457 * @return bool
458 */
459 public static function dataExists(&$params) {
460 // Disallow empty values except for the number zero.
461 // TODO: create a utility for this since it's needed in many places
462 if (!empty($params['name']) || (string) $params['name'] === '0') {
463 return TRUE;
464 }
465
466 return FALSE;
467 }
468
469 /**
470 * Get the tag sets for a entity object.
471 *
472 * @param string $entityTable
473 * Entity_table.
474 *
475 * @return array
476 * array of tag sets
477 */
478 public static function getTagSet($entityTable) {
479 $tagSets = array();
480 $query = "SELECT name, id FROM civicrm_tag
481 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
482 $dao = CRM_Core_DAO::executeQuery($query, array(
483 1 => array(
484 '%' . $entityTable . '%',
485 'String',
486 ),
487 ), TRUE, NULL, FALSE, FALSE);
488 while ($dao->fetch()) {
489 $tagSets[$dao->id] = $dao->name;
490 }
491 $dao->free();
492 return $tagSets;
493 }
494
495 /**
496 * Get the tags that are not children of a tagset.
497 *
498 * @return array
499 * associated array of tag name and id
500 */
501 public static function getTagsNotInTagset() {
502 $tags = $tagSets = array();
503 // first get all the tag sets
504 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
505 $dao = CRM_Core_DAO::executeQuery($query);
506 while ($dao->fetch()) {
507 $tagSets[] = $dao->id;
508 }
509
510 $parentClause = '';
511 if (!empty($tagSets)) {
512 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
513 }
514
515 // get that tags that don't have tagset as parent
516 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
517 $dao = CRM_Core_DAO::executeQuery($query);
518 while ($dao->fetch()) {
519 $tags[$dao->id] = $dao->name;
520 }
521
522 return $tags;
523 }
524
525 }