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