Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-03-03-23-44-14
[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 */
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 while ($dao->fetch()) {
104 $thisref = &$refs[$dao->id];
105
106 $thisref['parent_id'] = $dao->parent_id;
107 $thisref['name'] = $dao->name;
108 $thisref['description'] = $dao->description;
109 $thisref['is_selectable'] = $dao->is_selectable;
110
111 if (!$dao->parent_id) {
112 $this->tree[$dao->id] = &$thisref;
113 }
114 else {
115 $refs[$dao->parent_id]['children'][$dao->id] = &$thisref;
116 }
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 }
176 }
177 $tag->free();
178 }
179
180 return $tags;
181 }
182
183 /**
184 * Function to retrieve tags.
185 *
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.
196 * tag, so they cannot be selected
197 *
198 * @return array
199 */
200 public static function getTags(
201 $usedFor = 'civicrm_contact',
202 &$tags = array(),
203 $parentId = NULL,
204 $separator = '&nbsp;&nbsp;',
205 $formatSelectable = FALSE
206 ) {
207 if (!is_array($tags)) {
208 $tags = array();
209 }
210 // We need to build a list of tags ordered by hierarchy and sorted by
211 // name. The heirarchy will be communicated by an accumulation of
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
214 // query and build the heirarchy with the algorithm below.
215 $args = array(1 => array('%' . $usedFor . '%', 'String'));
216 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
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()) {
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 }
243 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
244 $roots[] = array(
245 'id' => $dao->id,
246 'prefix' => '',
247 'name' => $dao->name,
248 'idPrefix' => $idPrefix,
249 );
250 }
251 else {
252 $rows[] = array(
253 'id' => $dao->id,
254 'prefix' => '',
255 'name' => $dao->name,
256 'parent_id' => $dao->parent_id,
257 'idPrefix' => $idPrefix,
258 );
259 }
260 }
261
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)) {
269 $new_roots = array();
270 $current_rows = $rows;
271 $root = array_shift($roots);
272 $tags[$root['id']] = array(
273 $root['prefix'],
274 $root['name'],
275 $root['idPrefix'],
276 );
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']) {
284 $new_roots[] = array(
285 'id' => $row['id'],
286 'prefix' => $tags[$root['id']][0] . $separator,
287 'name' => $row['name'],
288 'idPrefix' => $row['idPrefix'],
289 );
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.
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])) {
307 $key = $tag[2] . "-" . $key;
308 }
309 $formattedTags[$key] = $tag[0] . $tag[1];
310 }
311
312 $tags = $formattedTags;
313 return $tags;
314 }
315
316 /**
317 * Delete the tag.
318 *
319 * @param int $id
320 * Tag id.
321 *
322 * @return bool
323 */
324 public static function del($id) {
325 // since this is a destructive operation, lets make sure
326 // id is a postive number
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);
342 return TRUE;
343 }
344 return FALSE;
345 }
346
347 /**
348 * Takes an associative array and creates a contact object.
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 *
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.
358 * signatures
359 *
360 * @return object
361 * CRM_Core_DAO_Tag object on success, otherwise null
362 */
363 public static function add(&$params, $ids = array()) {
364 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
365 if (!$id && !self::dataExists($params)) {
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
372 if (!empty($params['parent_id'])) {
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);
378 $tag->id = $id;
379 $hook = !$id ? 'create' : 'edit';
380 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
381
382 // save creator id and time
383 if (!$tag->id) {
384 $session = CRM_Core_Session::singleton();
385 $tag->created_id = $session->get('userID');
386 $tag->created_date = date('YmdHis');
387 }
388
389 $tag->save();
390 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
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",
395 array(
396 1 => array($params['used_for'], 'String'),
397 2 => array($tag->id, 'Integer'),
398 )
399 );
400 }
401
402 return $tag;
403 }
404
405 /**
406 * Check if there is data to create the object.
407 *
408 * @param array $params
409 * (reference ) an assoc array of name/value pairs.
410 *
411 * @return bool
412 */
413 public static function dataExists(&$params) {
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') {
417 return TRUE;
418 }
419
420 return FALSE;
421 }
422
423 /**
424 * Get the tag sets for a entity object.
425 *
426 * @param string $entityTable
427 * Entity_table.
428 *
429 * @return array
430 * array of tag sets
431 */
432 public static function getTagSet($entityTable) {
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";
436 $dao = CRM_Core_DAO::executeQuery($query, array(
437 1 => array(
438 '%' . $entityTable . '%',
439 'String',
440 ),
441 ), TRUE, NULL, FALSE, FALSE);
442 while ($dao->fetch()) {
443 $tagSets[$dao->id] = $dao->name;
444 }
445 $dao->free();
446 return $tagSets;
447 }
448
449 /**
450 * Get the tags that are not children of a tagset.
451 *
452 * @return array
453 * associated array of tag name and id
454 */
455 public static function getTagsNotInTagset() {
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";
459 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
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 }
478
479 }