Merge remote-tracking branch 'origin/abtest' into master-abtest
[civicrm-core.git] / CRM / Core / BAO / Tag.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 function __construct() {
41 parent::__construct();
42 }
43
44 /**
45 * Takes a bunch of params that are needed to match certain criteria and
46 * retrieves the relevant objects. Typically the valid params are only
47 * contact_id. We'll tweak this function to be more full featured over a period
48 * of time. This is the inverse function of create. It also stores all the retrieved
49 * values in the default array
50 *
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $defaults (reference ) an assoc array to hold the flattened values
53 *
54 * @return object CRM_Core_DAO_Tag object on success, otherwise null
55 * @access public
56 * @static
57 */
58 static function retrieve(&$params, &$defaults) {
59 $tag = new CRM_Core_DAO_Tag();
60 $tag->copyValues($params);
61 if ($tag->find(TRUE)) {
62 CRM_Core_DAO::storeValues($tag, $defaults);
63 return $tag;
64 }
65 return NULL;
66 }
67
68 /**
69 * @param null $usedFor
70 * @param bool $excludeHidden
71 *
72 * @return mixed
73 */
74 function getTree($usedFor = NULL, $excludeHidden = FALSE) {
75 if (!isset($this->tree)) {
76 $this->buildTree($usedFor, $excludeHidden);
77 }
78 return $this->tree;
79 }
80
81 /**
82 * Build a nested array from hierarchical tags. Supports infinite levels of nesting.
83 * @param null $usedFor
84 * @param bool $excludeHidden
85 */
86 function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
87 $sql = "SELECT id, parent_id, name, description FROM civicrm_tag";
88
89 $whereClause = array();
90 if ($usedFor) {
91 $whereClause[] = "used_for like '%{$usedFor}%'";
92 }
93 if ($excludeHidden) {
94 $whereClause[] = "is_tagset = 0";
95 }
96
97 if (!empty($whereClause)) {
98 $sql .= " WHERE " . implode(' AND ', $whereClause);
99 }
100
101 $sql .= " ORDER BY parent_id,name";
102
103 $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
104
105 $refs = array();
106 while ($dao->fetch()) {
107 $thisref = &$refs[$dao->id];
108
109 $thisref['parent_id'] = $dao->parent_id;
110 $thisref['name'] = $dao->name;
111 $thisref['description'] = $dao->description;
112
113 if (!$dao->parent_id) {
114 $this->tree[$dao->id] = &$thisref;
115 }
116 else {
117 $refs[$dao->parent_id]['children'][$dao->id] = &$thisref;
118 }
119 }
120
121 }
122
123 /**
124 * @param array $usedFor
125 * @param bool $buildSelect
126 * @param bool $all
127 * @param null $parentId
128 *
129 * @return array
130 */
131 static function getTagsUsedFor($usedFor = array('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 * @param string $usedFor
186 * @param array $tags
187 * @param null $parentId
188 * @param string $separator
189 *
190 * @return array
191 */
192 static function getTags($usedFor = 'civicrm_contact',
193 &$tags = array(),
194 $parentId = NULL,
195 $separator = '&nbsp;&nbsp;'
196 ) {
197 if (!is_array($tags)) {
198 $tags = array();
199 }
200 // We need to build a list of tags ordered by hierarchy and sorted by
201 // name. The heirarchy will be communicated by an accumulation of
202 // separators in front of the name to give it a visual offset.
203 // Instead of recursively making mysql queries, we'll make one big
204 // query and build the heirarchy with the algorithm below.
205 $args = array(1 => array('%' . $usedFor . '%', 'String'));
206 $query = "SELECT id, name, parent_id, is_tagset
207 FROM civicrm_tag
208 WHERE used_for LIKE %1";
209 if ($parentId) {
210 $query .= " AND parent_id = %2";
211 $args[2] = array($parentId, 'Integer');
212 }
213 $query .= " ORDER BY name";
214 $dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
215
216 // Sort the tags into the correct storage by the parent_id/is_tagset
217 // filter the filter was in place previously, we're just reusing it.
218 // $roots represents the current leaf nodes that need to be checked for
219 // children. $rows represents the unplaced nodes, not all of much
220 // are necessarily placed.
221 $roots = $rows = array();
222 while ($dao->fetch()) {
223 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
224 $roots[] = array('id' => $dao->id, 'prefix' => '', 'name' => $dao->name);
225 }
226 else {
227 $rows[] = array('id' => $dao->id, 'prefix' => '', 'name' => $dao->name, 'parent_id' => $dao->parent_id);
228 }
229 }
230 $dao->free();
231 // While we have nodes left to build, shift the first (alphabetically)
232 // node of the list, place it in our tags list and loop through the
233 // list of unplaced nodes to find its children. We make a copy to
234 // iterate through because we must modify the unplaced nodes list
235 // during the loop.
236 while (count($roots)) {
237 $new_roots = array();
238 $current_rows = $rows;
239 $root = array_shift($roots);
240 $tags[$root['id']] = array($root['prefix'], $root['name']);
241
242 // As you find the children, append them to the end of the new set
243 // of roots (maintain alphabetical ordering). Also remove the node
244 // from the set of unplaced nodes.
245 if (is_array($current_rows)) {
246 foreach ($current_rows as $key => $row) {
247 if ($row['parent_id'] == $root['id']) {
248 $new_roots[] = array('id' => $row['id'], 'prefix' => $tags[$root['id']][0] . $separator, 'name' => $row['name']);
249 unset($rows[$key]);
250 }
251 }
252 }
253
254 //As a group, insert the new roots into the beginning of the roots
255 //list. This maintains the hierarchical ordering of the tags.
256 $roots = array_merge($new_roots, $roots);
257 }
258
259 // Prefix each name with the calcuated spacing to give the visual
260 // appearance of ordering when transformed into HTML in the form layer.
261 foreach ($tags as & $tag) {
262 $tag = $tag[0] . $tag[1];
263 }
264
265 return $tags;
266 }
267
268 /**
269 * Function to delete the tag
270 *
271 * @param int $id tag id
272 *
273 * @return boolean
274 * @access public
275 * @static
276 *
277 */
278 static function del($id) {
279 // since this is a destructive operation, lets make sure
280 // id is a postive number
281 CRM_Utils_Type::validate($id, 'Positive');
282
283 // delete all crm_entity_tag records with the selected tag id
284 $entityTag = new CRM_Core_DAO_EntityTag();
285 $entityTag->tag_id = $id;
286 $entityTag->delete();
287
288 // delete from tag table
289 $tag = new CRM_Core_DAO_Tag();
290 $tag->id = $id;
291
292 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
293
294 if ($tag->delete()) {
295 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
296 return TRUE;
297 }
298 return FALSE;
299 }
300
301 /**
302 * takes an associative array and creates a contact object
303 *
304 * The function extract all the params it needs to initialize the create a
305 * contact object. the params array could contain additional unused name/value
306 * pairs
307 *
308 * @param array $params (reference) an assoc array of name/value pairs
309 * @param array $ids (optional) the array that holds all the db ids - we are moving away from this in bao
310 * signatures
311 *
312 * @return object CRM_Core_DAO_Tag object on success, otherwise null
313 * @access public
314 * @static
315 */
316 static function add(&$params, $ids = array()) {
317 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
318 if (!$id && !self::dataExists($params)) {
319 return NULL;
320 }
321
322 $tag = new CRM_Core_DAO_Tag();
323
324 // if parent id is set then inherit used for and is hidden properties
325 if (!empty($params['parent_id'])) {
326 // get parent details
327 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
328 }
329
330 $tag->copyValues($params);
331 $tag->id = $id;
332 $hook = !$id ? 'create' : 'edit';
333 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
334
335 // save creator id and time
336 if (!$tag->id) {
337 $session = CRM_Core_Session::singleton();
338 $tag->created_id = $session->get('userID');
339 $tag->created_date = date('YmdHis');
340 }
341
342 $tag->save();
343 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
344
345 // if we modify parent tag, then we need to update all children
346 if ($tag->parent_id === 'null') {
347 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
348 array(1 => array($params['used_for'], 'String'),
349 2 => array($tag->id, 'Integer'),
350 )
351 );
352 }
353
354 return $tag;
355 }
356
357 /**
358 * Check if there is data to create the object
359 *
360 * @param array $params (reference ) an assoc array of name/value pairs
361 *
362 * @return boolean
363 * @access public
364 * @static
365 */
366 static function dataExists(&$params) {
367 // Disallow empty values except for the number zero.
368 // TODO: create a utility for this since it's needed in many places
369 if (!empty($params['name']) || (string) $params['name'] === '0') {
370 return TRUE;
371 }
372
373 return FALSE;
374 }
375
376 /**
377 * Function to get the tag sets for a entity object
378 *
379 * @param string $entityTable entity_table
380 *
381 * @return array $tagSets array of tag sets
382 * @access public
383 * @static
384 */
385 static function getTagSet($entityTable) {
386 $tagSets = array();
387 $query = "SELECT name, id FROM civicrm_tag
388 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
389 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array('%' . $entityTable . '%', 'String')), TRUE, NULL, FALSE, FALSE);
390 while ($dao->fetch()) {
391 $tagSets[$dao->id] = $dao->name;
392 }
393 $dao->free();
394 return $tagSets;
395 }
396
397 /**
398 * Function to get the tags that are not children of a tagset.
399 *
400 * @return array $tags associated array of tag name and id@access public
401 * @static
402 */
403 static function getTagsNotInTagset() {
404 $tags = $tagSets = array();
405 // first get all the tag sets
406 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
407 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
408 while ($dao->fetch()) {
409 $tagSets[] = $dao->id;
410 }
411
412 $parentClause = '';
413 if (!empty($tagSets)) {
414 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
415 }
416
417 // get that tags that don't have tagset as parent
418 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
419 $dao = CRM_Core_DAO::executeQuery($query);
420 while ($dao->fetch()) {
421 $tags[$dao->id] = $dao->name;
422 }
423
424 return $tags;
425 }
426 }
427