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