INFRA-132 - Comment grammar cleanup
[civicrm-core.git] / CRM / Core / BAO / EntityTag.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 * This class contains functions for managing Tag(tag) for a contact
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36 class CRM_Core_BAO_EntityTag extends CRM_Core_DAO_EntityTag {
37
38 /**
39 *
40 * Given a contact id, it returns an array of tag id's the
41 * contact belongs to.
42 *
43 * @param int $entityID
44 * Id of the entity usually the contactID.
45 * @param string $entityTable
46 * Name of the entity table usually 'civicrm_contact'.
47 *
48 * @return array(
49 ) reference $tag array of category id's the contact belongs to.
50 *
51 * @static
52 */
53 public static function &getTag($entityID, $entityTable = 'civicrm_contact') {
54 $tags = array();
55
56 $entityTag = new CRM_Core_BAO_EntityTag();
57 $entityTag->entity_id = $entityID;
58 $entityTag->entity_table = $entityTable;
59 $entityTag->find();
60
61 while ($entityTag->fetch()) {
62 $tags[$entityTag->tag_id] = $entityTag->tag_id;
63 }
64 return $tags;
65 }
66
67 /**
68 * Takes an associative array and creates a entityTag object
69 *
70 * the function extract all the params it needs to initialize the create a
71 * group object. the params array could contain additional unused name/value
72 * pairs
73 *
74 * @param array $params
75 * (reference ) an assoc array of name/value pairs.
76 *
77 * @return CRM_Core_BAO_EntityTag object
78 * @static
79 */
80 public static function add(&$params) {
81 $dataExists = self::dataExists($params);
82 if (!$dataExists) {
83 return NULL;
84 }
85
86 $entityTag = new CRM_Core_BAO_EntityTag();
87 $entityTag->copyValues($params);
88
89 // dont save the object if it already exists, CRM-1276
90 if (!$entityTag->find(TRUE)) {
91 $entityTag->save();
92
93 //invoke post hook on entityTag
94 // we are using this format to keep things consistent between the single and bulk operations
95 // so a bit different from other post hooks
96 $object = array(0 => array(0 => $params['entity_id']), 1 => $params['entity_table']);
97 CRM_Utils_Hook::post('create', 'EntityTag', $params['tag_id'], $object);
98 }
99 return $entityTag;
100 }
101
102 /**
103 * Check if there is data to create the object
104 *
105 * @param array $params
106 * An assoc array of name/value pairs.
107 *
108 * @return boolean
109 * @static
110 */
111 public static function dataExists($params) {
112 return !($params['tag_id'] == 0);
113 }
114
115 /**
116 * Delete the tag for a contact
117 *
118 * @param array $params
119 * (reference ) an assoc array of name/value pairs.
120 *
121 * @return CRM_Core_BAO_EntityTag object
122 * @static
123 *
124 */
125 public static function del(&$params) {
126 $entityTag = new CRM_Core_BAO_EntityTag();
127 $entityTag->copyValues($params);
128 $entityTag->delete();
129
130 //invoke post hook on entityTag
131 $object = array(0 => array(0 => $params['entity_id']), 1 => $params['entity_table']);
132 CRM_Utils_Hook::post('delete', 'EntityTag', $params['tag_id'], $object);
133 }
134
135 /**
136 * Given an array of entity ids and entity table, add all the entity to the tags
137 *
138 * @param array $entityIds
139 * (reference ) the array of entity ids to be added.
140 * @param int $tagId
141 * The id of the tag.
142 * @param string $entityTable
143 * Name of entity table default:civicrm_contact.
144 *
145 * @return array (total, added, notAdded) count of enities added to tag
146 * @static
147 */
148 public static function addEntitiesToTag(&$entityIds, $tagId, $entityTable = 'civicrm_contact') {
149 $numEntitiesAdded = 0;
150 $numEntitiesNotAdded = 0;
151 $entityIdsAdded = array();
152
153 foreach ($entityIds as $entityId) {
154 $tag = new CRM_Core_DAO_EntityTag();
155
156 $tag->entity_id = $entityId;
157 $tag->tag_id = $tagId;
158 $tag->entity_table = $entityTable;
159 if (!$tag->find()) {
160 $tag->save();
161 $entityIdsAdded[] = $entityId;
162 $numEntitiesAdded++;
163 }
164 else {
165 $numEntitiesNotAdded++;
166 }
167 }
168
169 //invoke post hook on entityTag
170 $object = array($entityIdsAdded, $entityTable);
171 CRM_Utils_Hook::post('create', 'EntityTag', $tagId, $object);
172
173 // reset the group contact cache for all groups
174 // if tags are being used in a smart group
175 CRM_Contact_BAO_GroupContactCache::remove();
176
177 return array(count($entityIds), $numEntitiesAdded, $numEntitiesNotAdded);
178 }
179
180 /**
181 * Given an array of entity ids and entity table, remove entity(s) tags
182 *
183 * @param array $entityIds
184 * (reference ) the array of entity ids to be removed.
185 * @param int $tagId
186 * The id of the tag.
187 * @param string $entityTable
188 * Name of entity table default:civicrm_contact.
189 *
190 * @return array (total, removed, notRemoved) count of entities removed from tags
191 * @static
192 */
193 public static function removeEntitiesFromTag(&$entityIds, $tagId, $entityTable = 'civicrm_contact') {
194 $numEntitiesRemoved = 0;
195 $numEntitiesNotRemoved = 0;
196 $entityIdsRemoved = array();
197
198 foreach ($entityIds as $entityId) {
199 $tag = new CRM_Core_DAO_EntityTag();
200
201 $tag->entity_id = $entityId;
202 $tag->tag_id = $tagId;
203 $tag->entity_table = $entityTable;
204 if ($tag->find()) {
205 $tag->delete();
206 $entityIdsRemoved[] = $entityId;
207 $numEntitiesRemoved++;
208 }
209 else {
210 $numEntitiesNotRemoved++;
211 }
212 }
213
214 //invoke post hook on entityTag
215 $object = array($entityIdsRemoved, $entityTable);
216 CRM_Utils_Hook::post('delete', 'EntityTag', $tagId, $object);
217
218 // reset the group contact cache for all groups
219 // if tags are being used in a smart group
220 CRM_Contact_BAO_GroupContactCache::remove();
221
222 return array(count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved);
223 }
224
225 /**
226 * Takes an associative array and creates tag entity record for all tag entities
227 *
228 * @param array $params
229 * (reference) an assoc array of name/value pairs.
230 * @param $entityTable
231 * @param int $entityID
232 *
233 * @return void
234 * @static
235 */
236 public static function create(&$params, $entityTable, $entityID) {
237 // get categories for the entity id
238 $entityTag = CRM_Core_BAO_EntityTag::getTag($entityID, $entityTable);
239
240 // get the list of all the categories
241 $allTag = CRM_Core_BAO_Tag::getTags($entityTable);
242
243 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
244 if (!is_array($params)) {
245 $params = array();
246 }
247
248 // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
249 if (!is_array($entityTag)) {
250 $entityTag = array();
251 }
252
253 // check which values has to be inserted/deleted for contact
254 foreach ($allTag as $key => $varValue) {
255 $tagParams['entity_table'] = $entityTable;
256 $tagParams['entity_id'] = $entityID;
257 $tagParams['tag_id'] = $key;
258
259 if (array_key_exists($key, $params) && !array_key_exists($key, $entityTag)) {
260 // insert a new record
261 CRM_Core_BAO_EntityTag::add($tagParams);
262 }
263 elseif (!array_key_exists($key, $params) && array_key_exists($key, $entityTag)) {
264 // delete a record for existing contact
265 CRM_Core_BAO_EntityTag::del($tagParams);
266 }
267 }
268 }
269
270 /**
271 * This function returns all entities assigned to a specific tag
272 *
273 * @param object $tag
274 * An object of a tag.
275 *
276 * @return array $entityIds array of entity ids
277 */
278 public function getEntitiesByTag($tag) {
279 $entityIds = array();
280 $entityTagDAO = new CRM_Core_DAO_EntityTag();
281 $entityTagDAO->tag_id = $tag->id;
282 $entityTagDAO->find();
283 while ($entityTagDAO->fetch()) {
284 $entityIds[] = $entityTagDAO->entity_id;
285 }
286 return $entityIds;
287 }
288
289 /**
290 * Get contact tags
291 */
292 public static function getContactTags($contactID, $count = FALSE) {
293 $contactTags = array();
294 if (!$count) {
295 $select = "SELECT name ";
296 }
297 else {
298 $select = "SELECT count(*) as cnt";
299 }
300
301 $query = "{$select}
302 FROM civicrm_tag ct
303 INNER JOIN civicrm_entity_tag et ON ( ct.id = et.tag_id AND
304 et.entity_id = {$contactID} AND
305 et.entity_table = 'civicrm_contact' AND
306 ct.is_tagset = 0 )";
307
308 $dao = CRM_Core_DAO::executeQuery($query);
309
310 if ($count) {
311 $dao->fetch();
312 return $dao->cnt;
313 }
314
315 while ($dao->fetch()) {
316 $contactTags[] = $dao->name;
317 }
318
319 return $contactTags;
320 }
321
322 /**
323 * Get child contact tags given parentId
324 */
325 public static function getChildEntityTags($parentId, $entityId, $entityTable = 'civicrm_contact') {
326 $entityTags = array();
327 $query = "SELECT ct.id as tag_id, name FROM civicrm_tag ct
328 INNER JOIN civicrm_entity_tag et ON ( et.entity_id = {$entityId} AND
329 et.entity_table = '{$entityTable}' AND et.tag_id = ct.id)
330 WHERE ct.parent_id = {$parentId}";
331
332 $dao = CRM_Core_DAO::executeQuery($query);
333
334 while ($dao->fetch()) {
335 $entityTags[$dao->tag_id] = array(
336 'id' => $dao->tag_id,
337 'name' => $dao->name,
338 );
339 }
340
341 return $entityTags;
342 }
343
344 /**
345 * Merge two tags: tag B into tag A.
346 */
347 public function mergeTags($tagAId, $tagBId) {
348 $queryParams = array(
349 1 => array($tagBId, 'Integer'),
350 2 => array($tagAId, 'Integer'),
351 );
352
353 // re-compute used_for field
354 $query = "SELECT id, name, used_for FROM civicrm_tag WHERE id IN (%1, %2)";
355 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
356 $tags = array();
357 while ($dao->fetch()) {
358 $label = ($dao->id == $tagAId) ? 'tagA' : 'tagB';
359 $tags[$label] = $dao->name;
360 $tags["{$label}_used_for"] = $dao->used_for ? explode(",", $dao->used_for) : array();
361 }
362 $usedFor = array_merge($tags["tagA_used_for"], $tags["tagB_used_for"]);
363 $usedFor = implode(',', array_unique($usedFor));
364 $tags["tagB_used_for"] = explode(",", $usedFor);
365
366 // get all merge queries together
367 $sqls = array(
368 // 1. update entity tag entries
369 "UPDATE IGNORE civicrm_entity_tag SET tag_id = %1 WHERE tag_id = %2",
370 // 2. update used_for info for tag B
371 "UPDATE civicrm_tag SET used_for = '{$usedFor}' WHERE id = %1",
372 // 3. remove tag A, if tag A is getting merged into B
373 "DELETE FROM civicrm_tag WHERE id = %2",
374 // 4. remove duplicate entity tag records
375 "DELETE et2.* from civicrm_entity_tag et1 INNER JOIN civicrm_entity_tag et2 ON et1.entity_table = et2.entity_table AND et1.entity_id = et2.entity_id AND et1.tag_id = et2.tag_id WHERE et1.id < et2.id",
376 // 5. remove orphaned entity_tags
377 "DELETE FROM civicrm_entity_tag WHERE tag_id = %2",
378 );
379 $tables = array('civicrm_entity_tag', 'civicrm_tag');
380
381 // Allow hook_civicrm_merge() to add SQL statements for the merge operation AND / OR
382 // perform any other actions like logging
383 CRM_Utils_Hook::merge('sqls', $sqls, $tagAId, $tagBId, $tables);
384
385 // call the SQL queries in one transaction
386 $transaction = new CRM_Core_Transaction();
387 foreach ($sqls as $sql) {
388 CRM_Core_DAO::executeQuery($sql, $queryParams, TRUE, NULL, TRUE);
389 }
390 $transaction->commit();
391
392 $tags['status'] = TRUE;
393 return $tags;
394 }
395
396 /**
397 * Get options for a given field.
398 * @see CRM_Core_DAO::buildOptions
399 *
400 * @param string $fieldName
401 * @param string $context
402 * : @see CRM_Core_DAO::buildOptionsContext.
403 * @param array $props
404 * : whatever is known about this dao object.
405 *
406 * @return Array|bool
407 */
408 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
409 $params = array();
410
411 $options = CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
412
413 // Output tag list as nested hierarchy
414 // TODO: This will only work when api.entity is "entity_tag". What about others?
415 if (($fieldName == 'tag' || $fieldName == 'tag_id') && ($context == 'search' || $context == 'create')) {
416 $options = CRM_Core_BAO_Tag::getTags('civicrm_contact', CRM_Core_DAO::$_nullArray, CRM_Utils_Array::value('parent_id', $params), '- ');
417 }
418
419 return $options;
420 }
421 }