INFRA-132 - Comment grammar cleanup
[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 CRM_Core_DAO_Tag object on success, otherwise null
53 * @static
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($usedFor = array(
130 '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 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 boolean
323 * @static
324 *
325 */
326 public static function del($id) {
327 // since this is a destructive operation, lets make sure
328 // id is a postive number
329 CRM_Utils_Type::validate($id, 'Positive');
330
331 // delete all crm_entity_tag records with the selected tag id
332 $entityTag = new CRM_Core_DAO_EntityTag();
333 $entityTag->tag_id = $id;
334 $entityTag->delete();
335
336 // delete from tag table
337 $tag = new CRM_Core_DAO_Tag();
338 $tag->id = $id;
339
340 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
341
342 if ($tag->delete()) {
343 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
344 return TRUE;
345 }
346 return FALSE;
347 }
348
349 /**
350 * Takes an associative array and creates a contact object
351 *
352 * The function extract all the params it needs to initialize the create a
353 * contact object. the params array could contain additional unused name/value
354 * pairs
355 *
356 * @param array $params
357 * (reference) an assoc array of name/value pairs.
358 * @param array $ids
359 * (optional) the array that holds all the db ids - we are moving away from this in bao.
360 * signatures
361 *
362 * @return object CRM_Core_DAO_Tag object on success, otherwise null
363 * @static
364 */
365 public static function add(&$params, $ids = array()) {
366 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
367 if (!$id && !self::dataExists($params)) {
368 return NULL;
369 }
370
371 $tag = new CRM_Core_DAO_Tag();
372
373 // if parent id is set then inherit used for and is hidden properties
374 if (!empty($params['parent_id'])) {
375 // get parent details
376 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
377 }
378
379 $tag->copyValues($params);
380 $tag->id = $id;
381 $hook = !$id ? 'create' : 'edit';
382 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
383
384 // save creator id and time
385 if (!$tag->id) {
386 $session = CRM_Core_Session::singleton();
387 $tag->created_id = $session->get('userID');
388 $tag->created_date = date('YmdHis');
389 }
390
391 $tag->save();
392 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
393
394 // if we modify parent tag, then we need to update all children
395 if ($tag->parent_id === 'null') {
396 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
397 array(
398 1 => array($params['used_for'], 'String'),
399 2 => array($tag->id, 'Integer'),
400 )
401 );
402 }
403
404 return $tag;
405 }
406
407 /**
408 * Check if there is data to create the object
409 *
410 * @param array $params
411 * (reference ) an assoc array of name/value pairs.
412 *
413 * @return boolean
414 * @static
415 */
416 public static function dataExists(&$params) {
417 // Disallow empty values except for the number zero.
418 // TODO: create a utility for this since it's needed in many places
419 if (!empty($params['name']) || (string) $params['name'] === '0') {
420 return TRUE;
421 }
422
423 return FALSE;
424 }
425
426 /**
427 * Get the tag sets for a entity object
428 *
429 * @param string $entityTable
430 * Entity_table.
431 *
432 * @return array $tagSets array of tag sets
433 * @static
434 */
435 public static function getTagSet($entityTable) {
436 $tagSets = array();
437 $query = "SELECT name, id FROM civicrm_tag
438 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
439 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array('%' . $entityTable . '%', 'String')), TRUE, NULL, FALSE, FALSE);
440 while ($dao->fetch()) {
441 $tagSets[$dao->id] = $dao->name;
442 }
443 $dao->free();
444 return $tagSets;
445 }
446
447 /**
448 * Get the tags that are not children of a tagset.
449 *
450 * @return array $tags associated array of tag name and id
451 * @access public
452 * @static
453 */
454 public static function getTagsNotInTagset() {
455 $tags = $tagSets = array();
456 // first get all the tag sets
457 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
458 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
459 while ($dao->fetch()) {
460 $tagSets[] = $dao->id;
461 }
462
463 $parentClause = '';
464 if (!empty($tagSets)) {
465 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
466 }
467
468 // get that tags that don't have tagset as parent
469 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
470 $dao = CRM_Core_DAO::executeQuery($query);
471 while ($dao->fetch()) {
472 $tags[$dao->id] = $dao->name;
473 }
474
475 return $tags;
476 }
477 }