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