CRM-19769 - Add color field to tag edit form
[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;
175 }
176 }
177 $tag->free();
178 }
179
180 return $tags;
181 }
182
b5c2afd0 183 /**
fe482240 184 * Function to retrieve tags.
47358d92 185 *
6a0b768e
TO
186 * @param string $usedFor
187 * Which type of tag entity.
188 * @param array $tags
189 * Tags array.
190 * @param int $parentId
191 * Parent id if you want need only children.
192 * @param string $separator
193 * Separator to indicate children.
194 * @param bool $formatSelectable
195 * Add special property for non-selectable.
47358d92 196 * tag, so they cannot be selected
b5c2afd0
EM
197 *
198 * @return array
199 */
2da40d21 200 public static function getTags(
f9f40af3 201 $usedFor = 'civicrm_contact',
6a488035 202 &$tags = array(),
2aa397bc 203 $parentId = NULL,
47358d92 204 $separator = '&nbsp;&nbsp;',
205 $formatSelectable = FALSE
6a488035 206 ) {
dee5ccbb
CW
207 if (!is_array($tags)) {
208 $tags = array();
209 }
6a488035 210 // We need to build a list of tags ordered by hierarchy and sorted by
b44e3f84 211 // name. The hierarchy will be communicated by an accumulation of
6a488035
TO
212 // separators in front of the name to give it a visual offset.
213 // Instead of recursively making mysql queries, we'll make one big
b44e3f84 214 // query and build the hierarchy with the algorithm below.
6a488035 215 $args = array(1 => array('%' . $usedFor . '%', 'String'));
47358d92 216 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
6a488035
TO
217 FROM civicrm_tag
218 WHERE used_for LIKE %1";
219 if ($parentId) {
220 $query .= " AND parent_id = %2";
221 $args[2] = array($parentId, 'Integer');
222 }
223 $query .= " ORDER BY name";
224 $dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
225
226 // Sort the tags into the correct storage by the parent_id/is_tagset
227 // filter the filter was in place previously, we're just reusing it.
228 // $roots represents the current leaf nodes that need to be checked for
229 // children. $rows represents the unplaced nodes, not all of much
230 // are necessarily placed.
231 $roots = $rows = array();
232 while ($dao->fetch()) {
47358d92 233 // note that we are prepending id with "crm_disabled_opt" which identifies
234 // them as disabled so that they cannot be selected. We do some magic
235 // in crm-select2 js function that marks option values to "disabled"
236 // current QF version in CiviCRM does not support passing this attribute,
237 // so this is another ugly hack / workaround,
238 // also know one is too keen to upgrade QF :P
239 $idPrefix = '';
240 if ($formatSelectable && !$dao->is_selectable) {
241 $idPrefix = "crm_disabled_opt";
242 }
6a488035 243 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
47358d92 244 $roots[] = array(
245 'id' => $dao->id,
246 'prefix' => '',
247 'name' => $dao->name,
248 'idPrefix' => $idPrefix,
353ffa53 249 );
6a488035
TO
250 }
251 else {
47358d92 252 $rows[] = array(
253 'id' => $dao->id,
254 'prefix' => '',
255 'name' => $dao->name,
256 'parent_id' => $dao->parent_id,
257 'idPrefix' => $idPrefix,
353ffa53 258 );
6a488035
TO
259 }
260 }
47358d92 261
6a488035
TO
262 $dao->free();
263 // While we have nodes left to build, shift the first (alphabetically)
264 // node of the list, place it in our tags list and loop through the
265 // list of unplaced nodes to find its children. We make a copy to
266 // iterate through because we must modify the unplaced nodes list
267 // during the loop.
268 while (count($roots)) {
353ffa53
TO
269 $new_roots = array();
270 $current_rows = $rows;
271 $root = array_shift($roots);
47358d92 272 $tags[$root['id']] = array(
273 $root['prefix'],
274 $root['name'],
275 $root['idPrefix'],
353ffa53 276 );
6a488035
TO
277
278 // As you find the children, append them to the end of the new set
279 // of roots (maintain alphabetical ordering). Also remove the node
280 // from the set of unplaced nodes.
281 if (is_array($current_rows)) {
282 foreach ($current_rows as $key => $row) {
283 if ($row['parent_id'] == $root['id']) {
47358d92 284 $new_roots[] = array(
285 'id' => $row['id'],
286 'prefix' => $tags[$root['id']][0] . $separator,
287 'name' => $row['name'],
288 'idPrefix' => $row['idPrefix'],
353ffa53 289 );
6a488035
TO
290 unset($rows[$key]);
291 }
292 }
293 }
294
295 //As a group, insert the new roots into the beginning of the roots
296 //list. This maintains the hierarchical ordering of the tags.
297 $roots = array_merge($new_roots, $roots);
298 }
299
300 // Prefix each name with the calcuated spacing to give the visual
301 // appearance of ordering when transformed into HTML in the form layer.
47358d92 302 // here is the actual code that to prepends and set disabled attribute for
303 // non-selectable tags
304 $formattedTags = array();
305 foreach ($tags as $key => $tag) {
306 if (!empty($tag[2])) {
86bfa4f6 307 $key = $tag[2] . "-" . $key;
47358d92 308 }
309 $formattedTags[$key] = $tag[0] . $tag[1];
6a488035
TO
310 }
311
47358d92 312 $tags = $formattedTags;
6a488035
TO
313 return $tags;
314 }
315
316 /**
fe482240 317 * Delete the tag.
6a488035 318 *
6a0b768e
TO
319 * @param int $id
320 * Tag id.
6a488035 321 *
5c766a0b 322 * @return bool
6a488035 323 */
00be9182 324 public static function del($id) {
6a488035 325 // since this is a destructive operation, lets make sure
b44e3f84 326 // id is a positive number
6a488035
TO
327 CRM_Utils_Type::validate($id, 'Positive');
328
329 // delete all crm_entity_tag records with the selected tag id
330 $entityTag = new CRM_Core_DAO_EntityTag();
331 $entityTag->tag_id = $id;
332 $entityTag->delete();
333
334 // delete from tag table
335 $tag = new CRM_Core_DAO_Tag();
336 $tag->id = $id;
337
338 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
339
340 if ($tag->delete()) {
341 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
6a488035
TO
342 return TRUE;
343 }
344 return FALSE;
345 }
346
347 /**
fe482240 348 * Takes an associative array and creates a contact object.
6a488035
TO
349 *
350 * The function extract all the params it needs to initialize the create a
351 * contact object. the params array could contain additional unused name/value
352 * pairs
353 *
6a0b768e
TO
354 * @param array $params
355 * (reference) an assoc array of name/value pairs.
356 * @param array $ids
357 * (optional) the array that holds all the db ids - we are moving away from this in bao.
d989d349 358 * signatures
6a488035 359 *
a6c01b45
CW
360 * @return object
361 * CRM_Core_DAO_Tag object on success, otherwise null
6a488035 362 */
00be9182 363 public static function add(&$params, $ids = array()) {
9b576df4
EM
364 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
365 if (!$id && !self::dataExists($params)) {
6a488035
TO
366 return NULL;
367 }
368
369 $tag = new CRM_Core_DAO_Tag();
370
371 // if parent id is set then inherit used for and is hidden properties
a7488080 372 if (!empty($params['parent_id'])) {
6a488035
TO
373 // get parent details
374 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
375 }
376
377 $tag->copyValues($params);
9b576df4
EM
378 $tag->id = $id;
379 $hook = !$id ? 'create' : 'edit';
d989d349 380 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
6a488035
TO
381
382 // save creator id and time
383 if (!$tag->id) {
353ffa53
TO
384 $session = CRM_Core_Session::singleton();
385 $tag->created_id = $session->get('userID');
6a488035
TO
386 $tag->created_date = date('YmdHis');
387 }
388
389 $tag->save();
d989d349 390 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
6a488035
TO
391
392 // if we modify parent tag, then we need to update all children
393 if ($tag->parent_id === 'null') {
394 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
2aa397bc 395 array(
353ffa53 396 1 => array($params['used_for'], 'String'),
6a488035
TO
397 2 => array($tag->id, 'Integer'),
398 )
399 );
400 }
401
402 return $tag;
403 }
404
405 /**
fe482240 406 * Check if there is data to create the object.
6a488035 407 *
6a0b768e
TO
408 * @param array $params
409 * (reference ) an assoc array of name/value pairs.
6a488035 410 *
5c766a0b 411 * @return bool
6a488035 412 */
00be9182 413 public static function dataExists(&$params) {
5ba3bfc8
CW
414 // Disallow empty values except for the number zero.
415 // TODO: create a utility for this since it's needed in many places
416 if (!empty($params['name']) || (string) $params['name'] === '0') {
6a488035
TO
417 return TRUE;
418 }
419
420 return FALSE;
421 }
422
423 /**
fe482240 424 * Get the tag sets for a entity object.
6a488035 425 *
6a0b768e
TO
426 * @param string $entityTable
427 * Entity_table.
6a488035 428 *
a6c01b45
CW
429 * @return array
430 * array of tag sets
6a488035 431 */
00be9182 432 public static function getTagSet($entityTable) {
6a488035
TO
433 $tagSets = array();
434 $query = "SELECT name, id FROM civicrm_tag
435 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
353ffa53
TO
436 $dao = CRM_Core_DAO::executeQuery($query, array(
437 1 => array(
438 '%' . $entityTable . '%',
af9b09df
TO
439 'String',
440 ),
353ffa53 441 ), TRUE, NULL, FALSE, FALSE);
6a488035
TO
442 while ($dao->fetch()) {
443 $tagSets[$dao->id] = $dao->name;
444 }
445 $dao->free();
446 return $tagSets;
447 }
448
449 /**
100fef9d 450 * Get the tags that are not children of a tagset.
6a488035 451 *
a6c01b45
CW
452 * @return array
453 * associated array of tag name and id
6a488035 454 */
00be9182 455 public static function getTagsNotInTagset() {
6a488035
TO
456 $tags = $tagSets = array();
457 // first get all the tag sets
458 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
33621c4f 459 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
460 while ($dao->fetch()) {
461 $tagSets[] = $dao->id;
462 }
463
464 $parentClause = '';
465 if (!empty($tagSets)) {
466 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
467 }
468
469 // get that tags that don't have tagset as parent
470 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
471 $dao = CRM_Core_DAO::executeQuery($query);
472 while ($dao->fetch()) {
473 $tags[$dao->id] = $dao->name;
474 }
475
476 return $tags;
477 }
96025800 478
6a488035 479}