e6d1efdf7d15a7219d22b7925866d2cb2e38279e
[civicrm-core.git] / CRM / Core / BAO / Tag.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * @static
55 */
56 public static function retrieve(&$params, &$defaults) {
57 $tag = new CRM_Core_DAO_Tag();
58 $tag->copyValues($params);
59 if ($tag->find(TRUE)) {
60 CRM_Core_DAO::storeValues($tag, $defaults);
61 return $tag;
62 }
63 return NULL;
64 }
65
66 /**
67 * @param null $usedFor
68 * @param bool $excludeHidden
69 *
70 * @return mixed
71 */
72 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
73 if (!isset($this->tree)) {
74 $this->buildTree($usedFor, $excludeHidden);
75 }
76 return $this->tree;
77 }
78
79 /**
80 * Build a nested array from hierarchical tags. Supports infinite levels of nesting.
81 * @param null $usedFor
82 * @param bool $excludeHidden
83 */
84 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
85 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
86
87 $whereClause = array();
88 if ($usedFor) {
89 $whereClause[] = "used_for like '%{$usedFor}%'";
90 }
91 if ($excludeHidden) {
92 $whereClause[] = "is_tagset = 0";
93 }
94
95 if (!empty($whereClause)) {
96 $sql .= " WHERE " . implode(' AND ', $whereClause);
97 }
98
99 $sql .= " ORDER BY parent_id,name";
100
101 $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
102
103 $refs = 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 /**
123 * @param array $usedFor
124 * @param bool $buildSelect
125 * @param bool $all
126 * @param int $parentId
127 *
128 * @return array
129 */
130 public static function getTagsUsedFor($usedFor = array(
131 'civicrm_contact'),
132 $buildSelect = TRUE,
133 $all = FALSE,
134 $parentId = NULL
135 ) {
136 $tags = array();
137
138 if (empty($usedFor)) {
139 return $tags;
140 }
141 if (!is_array($usedFor)) {
142 $usedFor = array($usedFor);
143 }
144
145 if ($parentId === NULL) {
146 $parentClause = " parent_id IS NULL AND ";
147 }
148 else {
149 $parentClause = " parent_id = {$parentId} AND ";
150 }
151
152 foreach ($usedFor as $entityTable) {
153 $tag = new CRM_Core_DAO_Tag();
154 $tag->fields();
155 $tag->orderBy('parent_id');
156 if ($buildSelect) {
157 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
158 }
159 else {
160 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
161 }
162 if (!$all) {
163 $tag->is_tagset = 0;
164 }
165 $tag->find();
166
167 while ($tag->fetch()) {
168 if ($buildSelect) {
169 $tags[$tag->id] = $tag->name;
170 }
171 else {
172 $tags[$tag->id]['name'] = $tag->name;
173 $tags[$tag->id]['parent_id'] = $tag->parent_id;
174 $tags[$tag->id]['is_tagset'] = $tag->is_tagset;
175 $tags[$tag->id]['used_for'] = $tag->used_for;
176 }
177 }
178 $tag->free();
179 }
180
181 return $tags;
182 }
183
184 /**
185 * Function to retrieve tags
186 *
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.
197 * tag, so they cannot be selected
198 *
199 * @return array
200 */
201 static function getTags(
202 $usedFor = 'civicrm_contact',
203 &$tags = array(),
204 $parentId = NULL,
205 $separator = '&nbsp;&nbsp;',
206 $formatSelectable = FALSE
207 ) {
208 if (!is_array($tags)) {
209 $tags = array();
210 }
211 // We need to build a list of tags ordered by hierarchy and sorted by
212 // name. The heirarchy will be communicated by an accumulation of
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
215 // query and build the heirarchy with the algorithm below.
216 $args = array(1 => array('%' . $usedFor . '%', 'String'));
217 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
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()) {
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 }
244 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
245 $roots[] = array(
246 'id' => $dao->id,
247 'prefix' => '',
248 'name' => $dao->name,
249 'idPrefix' => $idPrefix,
250 );
251 }
252 else {
253 $rows[] = array(
254 'id' => $dao->id,
255 'prefix' => '',
256 'name' => $dao->name,
257 'parent_id' => $dao->parent_id,
258 'idPrefix' => $idPrefix,
259 );
260 }
261 }
262
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)) {
270 $new_roots = array();
271 $current_rows = $rows;
272 $root = array_shift($roots);
273 $tags[$root['id']] = array(
274 $root['prefix'],
275 $root['name'],
276 $root['idPrefix'],
277 );
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']) {
285 $new_roots[] = array(
286 'id' => $row['id'],
287 'prefix' => $tags[$root['id']][0] . $separator,
288 'name' => $row['name'],
289 'idPrefix' => $row['idPrefix'],
290 );
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.
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])) {
308 $key = $tag[2] . "-" . $key;
309 }
310 $formattedTags[$key] = $tag[0] . $tag[1];
311 }
312
313 $tags = $formattedTags;
314 return $tags;
315 }
316
317 /**
318 * Delete the tag
319 *
320 * @param int $id
321 * Tag id.
322 *
323 * @return boolean
324 * @static
325 *
326 */
327 public static function del($id) {
328 // since this is a destructive operation, lets make sure
329 // id is a postive number
330 CRM_Utils_Type::validate($id, 'Positive');
331
332 // delete all crm_entity_tag records with the selected tag id
333 $entityTag = new CRM_Core_DAO_EntityTag();
334 $entityTag->tag_id = $id;
335 $entityTag->delete();
336
337 // delete from tag table
338 $tag = new CRM_Core_DAO_Tag();
339 $tag->id = $id;
340
341 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
342
343 if ($tag->delete()) {
344 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
345 return TRUE;
346 }
347 return FALSE;
348 }
349
350 /**
351 * Takes an associative array and creates a contact object
352 *
353 * The function extract all the params it needs to initialize the create a
354 * contact object. the params array could contain additional unused name/value
355 * pairs
356 *
357 * @param array $params
358 * (reference) an assoc array of name/value pairs.
359 * @param array $ids
360 * (optional) the array that holds all the db ids - we are moving away from this in bao.
361 * signatures
362 *
363 * @return object
364 * CRM_Core_DAO_Tag object on success, otherwise null
365 * @static
366 */
367 public static function add(&$params, $ids = array()) {
368 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
369 if (!$id && !self::dataExists($params)) {
370 return NULL;
371 }
372
373 $tag = new CRM_Core_DAO_Tag();
374
375 // if parent id is set then inherit used for and is hidden properties
376 if (!empty($params['parent_id'])) {
377 // get parent details
378 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
379 }
380
381 $tag->copyValues($params);
382 $tag->id = $id;
383 $hook = !$id ? 'create' : 'edit';
384 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
385
386 // save creator id and time
387 if (!$tag->id) {
388 $session = CRM_Core_Session::singleton();
389 $tag->created_id = $session->get('userID');
390 $tag->created_date = date('YmdHis');
391 }
392
393 $tag->save();
394 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
395
396 // if we modify parent tag, then we need to update all children
397 if ($tag->parent_id === 'null') {
398 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
399 array(
400 1 => array($params['used_for'], 'String'),
401 2 => array($tag->id, 'Integer'),
402 )
403 );
404 }
405
406 return $tag;
407 }
408
409 /**
410 * Check if there is data to create the object
411 *
412 * @param array $params
413 * (reference ) an assoc array of name/value pairs.
414 *
415 * @return boolean
416 * @static
417 */
418 public static function dataExists(&$params) {
419 // Disallow empty values except for the number zero.
420 // TODO: create a utility for this since it's needed in many places
421 if (!empty($params['name']) || (string) $params['name'] === '0') {
422 return TRUE;
423 }
424
425 return FALSE;
426 }
427
428 /**
429 * Get the tag sets for a entity object
430 *
431 * @param string $entityTable
432 * Entity_table.
433 *
434 * @return array
435 * array of tag sets
436 * @static
437 */
438 public static function getTagSet($entityTable) {
439 $tagSets = array();
440 $query = "SELECT name, id FROM civicrm_tag
441 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
442 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array('%' . $entityTable . '%', 'String')), TRUE, NULL, FALSE, FALSE);
443 while ($dao->fetch()) {
444 $tagSets[$dao->id] = $dao->name;
445 }
446 $dao->free();
447 return $tagSets;
448 }
449
450 /**
451 * Get the tags that are not children of a tagset.
452 *
453 * @return array
454 * associated array of tag name and id
455 * @access public
456 * @static
457 */
458 public static function getTagsNotInTagset() {
459 $tags = $tagSets = array();
460 // first get all the tag sets
461 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
462 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
463 while ($dao->fetch()) {
464 $tagSets[] = $dao->id;
465 }
466
467 $parentClause = '';
468 if (!empty($tagSets)) {
469 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
470 }
471
472 // get that tags that don't have tagset as parent
473 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
474 $dao = CRM_Core_DAO::executeQuery($query);
475 while ($dao->fetch()) {
476 $tags[$dao->id] = $dao->name;
477 }
478
479 return $tags;
480 }
481 }