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