CRM-19723 - Fix activity links
[civicrm-core.git] / CRM / Activity / BAO / Activity.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 *
30 * @package CRM
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33
34/**
7808aae6 35 * This class is for activity functions.
6a488035
TO
36 */
37class CRM_Activity_BAO_Activity extends CRM_Activity_DAO_Activity {
38
39 /**
fe482240 40 * Static field for all the activity information that we can potentially export.
6a488035
TO
41 *
42 * @var array
6a488035
TO
43 */
44 static $_exportableFields = NULL;
45
46 /**
fe482240 47 * Static field for all the activity information that we can potentially import.
6a488035
TO
48 *
49 * @var array
6a488035
TO
50 */
51 static $_importableFields = NULL;
52
53 /**
db7de9c1 54 * Check if there is absolute minimum of data to add the object.
6a488035 55 *
041ab3d1
TO
56 * @param array $params
57 * (reference ) an assoc array of name/value pairs.
6a488035 58 *
59f4c9ee 59 * @return bool
6a488035
TO
60 */
61 public static function dataExists(&$params) {
8cc574cf 62 if (!empty($params['source_contact_id']) || !empty($params['id'])) {
6a488035
TO
63 return TRUE;
64 }
65 return FALSE;
66 }
67
68 /**
d8689418 69 * Fetch object based on array of properties.
6a488035 70 *
041ab3d1
TO
71 * @param array $params
72 * (reference ) an assoc array of name/value pairs.
73 * @param array $defaults
74 * (reference ) an assoc array to hold the flattened values.
1cfa04c4 75 *
16b10e64 76 * @return CRM_Activity_DAO_Activity
6a488035
TO
77 */
78 public static function retrieve(&$params, &$defaults) {
79 $activity = new CRM_Activity_DAO_Activity();
80 $activity->copyValues($params);
81
82 if ($activity->find(TRUE)) {
e7e657f0 83 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
034500d4 84 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
85 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
86 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
87
6a488035 88 // TODO: at some stage we'll have to deal
7808aae6
SB
89 // with multiple values for assignees and targets, but
90 // for now, let's just fetch first row.
034500d4 91 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
92 $assignee_contact_names = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $assigneeID);
6a488035 93 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
eb873b6e 94 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
6a488035 95 if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name')) {
034500d4 96 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
97 $target_contact_names = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $targetID);
6a488035
TO
98 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
99 }
100 elseif (CRM_Core_Permission::check('access CiviMail') ||
101 (CRM_Mailing_Info::workflowEnabled() &&
102 CRM_Core_Permission::check('create mailings')
103 )
104 ) {
105 $defaults['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report',
eb873b6e 106 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
6a488035
TO
107 );
108 }
109 else {
110 $defaults['target_contact_value'] = ts('(recipients)');
111 }
b319d00a 112
65ebc887 113 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
ad674e50 114 $defaults['source_contact_id'] = $sourceContactId;
6a488035 115
65ebc887 116 if ($sourceContactId &&
6a488035 117 !CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
65ebc887 118 $sourceContactId,
6a488035
TO
119 'is_deleted'
120 )
121 ) {
122 $defaults['source_contact'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
65ebc887 123 $sourceContactId,
6a488035
TO
124 'sort_name'
125 );
126 }
127
7808aae6 128 // Get case subject.
6a488035
TO
129 $defaults['case_subject'] = CRM_Case_BAO_Case::getCaseSubject($activity->id);
130
131 CRM_Core_DAO::storeValues($activity, $defaults);
132
133 return $activity;
134 }
135 return NULL;
136 }
137
138 /**
d8689418 139 * Delete the activity.
6a488035 140 *
041ab3d1 141 * @param array $params
e63aff1c 142 * @param bool $moveToTrash
6a488035 143 *
d8689418 144 * @return mixed
6a488035
TO
145 */
146 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
147 // CRM-9137
a7488080 148 if (!empty($params['id']) && !is_array($params['id'])) {
6a488035
TO
149 CRM_Utils_Hook::pre('delete', 'Activity', $params['id'], $params);
150 }
151 else {
152 CRM_Utils_Hook::pre('delete', 'Activity', NULL, $params);
153 }
154
155 $transaction = new CRM_Core_Transaction();
156 if (is_array(CRM_Utils_Array::value('source_record_id', $params))) {
157 $sourceRecordIds = implode(',', $params['source_record_id']);
158 }
159 else {
160 $sourceRecordIds = CRM_Utils_Array::value('source_record_id', $params);
161 }
162
163 $result = NULL;
164 if (!$moveToTrash) {
165 if (!isset($params['id'])) {
166 if (is_array($params['activity_type_id'])) {
167 $activityTypes = implode(',', $params['activity_type_id']);
168 }
169 else {
170 $activityTypes = $params['activity_type_id'];
171 }
172
173 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
174 $dao = CRM_Core_DAO::executeQuery($query);
175 }
176 else {
177 $activity = new CRM_Activity_DAO_Activity();
178 $activity->copyValues($params);
179 $result = $activity->delete();
180
181 // CRM-8708
182 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
93bcc9e8
BS
183
184 // CRM-13994 delete activity entity_tag
185 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
186 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
187 }
188 }
189 else {
190 $activity = new CRM_Activity_DAO_Activity();
191 $activity->copyValues($params);
192
193 $activity->is_deleted = 1;
194 $result = $activity->save();
195
93bcc9e8
BS
196 // CRM-4525 log activity delete
197 $logMsg = 'Case Activity deleted for';
198 $msgs = array();
034500d4 199
e7e657f0 200 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
034500d4 201 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
202 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
203 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
204 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
6a488035
TO
205 if ($sourceContactId) {
206 $msgs[] = " source={$sourceContactId}";
207 }
034500d4 208
7808aae6 209 // get target contacts.
034500d4 210 $targetContactIds = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $targetID);
6a488035
TO
211 if (!empty($targetContactIds)) {
212 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
213 }
7808aae6 214 // get assignee contacts.
034500d4 215 $assigneeContactIds = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $assigneeID);
6a488035
TO
216 if (!empty($assigneeContactIds)) {
217 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
218 }
219
220 $logMsg .= implode(', ', $msgs);
221
222 self::logActivityAction($activity, $logMsg);
223 }
224
225 // delete the recently created Activity
226 if ($result) {
227 $activityRecent = array(
228 'id' => $activity->id,
229 'type' => 'Activity',
230 );
231 CRM_Utils_Recent::del($activityRecent);
232 }
233
234 $transaction->commit();
235 if (isset($activity)) {
236 // CRM-8708
237 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
238 CRM_Utils_Hook::post('delete', 'Activity', $activity->id, $activity);
239 }
240
241 return $result;
242 }
243
244 /**
d8689418 245 * Delete activity assignment record.
6a488035 246 *
c490a46a 247 * @param int $activityId
100fef9d 248 * @param int $recordTypeID
6a488035 249 */
a24b3694 250 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
1d85d241
DL
251 $activityContact = new CRM_Activity_BAO_ActivityContact();
252 $activityContact->activity_id = $activityId;
a24b3694 253 if ($recordTypeID) {
254 $activityContact->record_type_id = $recordTypeID;
6a488035 255 }
1ad799fa 256
7808aae6
SB
257 // Let's check if activity contact record exits and then delete.
258 // Looks like delete leads to deadlock when multiple simultaneous
259 // requests are done. CRM-15470
1ad799fa 260 if ($activityContact->find()) {
261 $activityContact->delete();
262 }
6a488035
TO
263 }
264
265 /**
d8689418 266 * Process the activities.
6a488035 267 *
041ab3d1
TO
268 * @param array $params
269 * Associated array of the submitted values.
1cfa04c4 270 *
e63aff1c 271 * @throws CRM_Core_Exception
6a488035 272 *
59f4c9ee 273 * @return CRM_Activity_BAO_Activity|null|object
6a488035
TO
274 */
275 public static function create(&$params) {
276 // check required params
277 if (!self::dataExists($params)) {
9af2925b 278 throw new CRM_Core_Exception('Not enough data to create activity object');
6a488035
TO
279 }
280
281 $activity = new CRM_Activity_DAO_Activity();
282
283 if (isset($params['id']) && empty($params['id'])) {
284 unset($params['id']);
285 }
286
8cc574cf 287 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
6a488035
TO
288 if (isset($params['activity_date_time']) &&
289 strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)
290 ) {
291 $params['status_id'] = 2;
292 }
293 else {
294 $params['status_id'] = 1;
295 }
296 }
297
7808aae6 298 // Set priority to Normal for Auto-populated activities (for Cases)
6a488035
TO
299 if (CRM_Utils_Array::value('priority_id', $params) === NULL &&
300 // if not set and not 0
301 !CRM_Utils_Array::value('id', $params)
302 ) {
cbf48754 303 $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
6a488035
TO
304 $params['priority_id'] = array_search('Normal', $priority);
305 }
306
307 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
308 $params['target_contact_id'] = array_unique($params['target_contact_id']);
309 }
310 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
311 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
312 }
313
314 // CRM-9137
a7488080 315 if (!empty($params['id'])) {
6a488035
TO
316 CRM_Utils_Hook::pre('edit', 'Activity', $activity->id, $params);
317 }
318 else {
319 CRM_Utils_Hook::pre('create', 'Activity', NULL, $params);
320 }
321
322 $activity->copyValues($params);
323 if (isset($params['case_id'])) {
324 // CRM-8708, preserve case ID even though it's not part of the SQL model
325 $activity->case_id = $params['case_id'];
326 }
327 elseif (is_numeric($activity->id)) {
328 // CRM-8708, preserve case ID even though it's not part of the SQL model
329 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
330 }
331
332 // start transaction
333 $transaction = new CRM_Core_Transaction();
334
335 $result = $activity->save();
336
337 if (is_a($result, 'CRM_Core_Error')) {
338 $transaction->rollback();
339 return $result;
340 }
341
342 $activityId = $activity->id;
e7e657f0 343 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 344 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
345 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
346 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
6a488035 347
1d85d241
DL
348 if (isset($params['source_contact_id'])) {
349 $acParams = array(
350 'activity_id' => $activityId,
9d5494f7 351 'contact_id' => $params['source_contact_id'],
21dfd5f5 352 'record_type_id' => $sourceID,
1d85d241 353 );
8ea7ce5d 354 self::deleteActivityContact($activityId, $sourceID);
1d85d241
DL
355 CRM_Activity_BAO_ActivityContact::create($acParams);
356 }
357
6a488035
TO
358 // check and attach and files as needed
359 CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
360
361 // attempt to save activity assignment
362 $resultAssignment = NULL;
a7488080 363 if (!empty($params['assignee_contact_id'])) {
6a488035
TO
364
365 $assignmentParams = array('activity_id' => $activityId);
366
367 if (is_array($params['assignee_contact_id'])) {
368 if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
369 // first delete existing assignments if any
a24b3694 370 self::deleteActivityContact($activityId, $assigneeID);
6a488035
TO
371 }
372
373 $values = array();
374 foreach ($params['assignee_contact_id'] as $acID) {
375 if ($acID) {
a24b3694 376 $values[] = "( $activityId, $acID, $assigneeID )";
6a488035
TO
377 }
378 }
379 while (!empty($values)) {
380 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
9d5494f7
TO
381 $str = implode(',', $input);
382 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
6a488035
TO
383 CRM_Core_DAO::executeQuery($sql);
384 }
385 }
386 else {
b319d00a 387 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
034500d4 388 $assignmentParams['record_type_id'] = $assigneeID;
a7488080 389 if (!empty($params['id'])) {
cc1c86e9 390 $assignment = new CRM_Activity_BAO_ActivityContact();
6a488035 391 $assignment->activity_id = $activityId;
034500d4 392 $assignment->record_type_id = $assigneeID;
6a488035
TO
393 $assignment->find(TRUE);
394
b319d00a 395 if ($assignment->contact_id != $params['assignee_contact_id']) {
6a488035 396 $assignmentParams['id'] = $assignment->id;
034500d4 397 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
6a488035
TO
398 }
399 }
400 else {
034500d4 401 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
6a488035
TO
402 }
403 }
404 }
405 else {
406 if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
a24b3694 407 self::deleteActivityContact($activityId, $assigneeID);
6a488035
TO
408 }
409 }
410
411 if (is_a($resultAssignment, 'CRM_Core_Error')) {
412 $transaction->rollback();
413 return $resultAssignment;
414 }
415
416 // attempt to save activity targets
417 $resultTarget = NULL;
a7488080 418 if (!empty($params['target_contact_id'])) {
6a488035
TO
419
420 $targetParams = array('activity_id' => $activityId);
421 $resultTarget = array();
422 if (is_array($params['target_contact_id'])) {
423 if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
424 // first delete existing targets if any
9d5494f7 425 self::deleteActivityContact($activityId, $targetID);
6a488035
TO
426 }
427
428 $values = array();
429 foreach ($params['target_contact_id'] as $tid) {
430 if ($tid) {
a24b3694 431 $values[] = "( $activityId, $tid, $targetID )";
6a488035
TO
432 }
433 }
434
435 while (!empty($values)) {
436 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
9d5494f7
TO
437 $str = implode(',', $input);
438 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
6a488035
TO
439 CRM_Core_DAO::executeQuery($sql);
440 }
441 }
442 else {
b319d00a 443 $targetParams['contact_id'] = $params['target_contact_id'];
034500d4 444 $targetParams['record_type_id'] = $targetID;
a7488080 445 if (!empty($params['id'])) {
034500d4 446 $target = new CRM_Activity_BAO_ActivityContact();
6a488035 447 $target->activity_id = $activityId;
034500d4 448 $target->record_type_id = $targetID;
6a488035
TO
449 $target->find(TRUE);
450
b319d00a 451 if ($target->contact_id != $params['target_contact_id']) {
6a488035 452 $targetParams['id'] = $target->id;
034500d4 453 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
6a488035
TO
454 }
455 }
456 else {
034500d4 457 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
6a488035
TO
458 }
459 }
460 }
461 else {
462 if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
9d5494f7 463 self::deleteActivityContact($activityId, $targetID);
6a488035
TO
464 }
465 }
466
0a9f61c4 467 // write to changelog before transaction is committed/rolled
6a488035 468 // back (and prepare status to display)
a7488080 469 if (!empty($params['id'])) {
6a488035
TO
470 $logMsg = "Activity (id: {$result->id} ) updated with ";
471 }
472 else {
473 $logMsg = "Activity created for ";
474 }
475
476 $msgs = array();
477 if (isset($params['source_contact_id'])) {
478 $msgs[] = "source={$params['source_contact_id']}";
479 }
480
a7488080 481 if (!empty($params['target_contact_id'])) {
35522279 482 if (is_array($params['target_contact_id']) && !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])) {
6a488035
TO
483 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
484 // take only first target
485 // will be used for recently viewed display
486 $t = array_slice($params['target_contact_id'], 0, 1);
487 $recentContactId = $t[0];
488 }
7808aae6 489 // Is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
9af2925b
EM
490 // as it may always be an array
491 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
6a488035
TO
492 $msgs[] = "target={$params['target_contact_id']}";
493 // will be used for recently viewed display
494 $recentContactId = $params['target_contact_id'];
495 }
496 }
497 else {
498 // at worst, take source for recently viewed display
9d5494f7 499 $recentContactId = CRM_Utils_Array::value('source_contact_id', $params);
6a488035
TO
500 }
501
502 if (isset($params['assignee_contact_id'])) {
503 if (is_array($params['assignee_contact_id'])) {
504 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
505 }
506 else {
507 $msgs[] = "assignee={$params['assignee_contact_id']}";
508 }
509 }
510 $logMsg .= implode(', ', $msgs);
511
512 self::logActivityAction($result, $logMsg);
513
a7488080 514 if (!empty($params['custom']) &&
6a488035
TO
515 is_array($params['custom'])
516 ) {
517 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
518 }
519
520 $transaction->commit();
a7488080 521 if (empty($params['skipRecentView'])) {
6a488035 522 $recentOther = array();
a7488080 523 if (!empty($params['case_id'])) {
6a488035
TO
524 $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
525 $url = CRM_Utils_System::url('civicrm/case/activity/view',
526 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
527 );
528 }
529 else {
7ad77be0 530 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home";
6a488035
TO
531 if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
532 $url = CRM_Utils_System::url('civicrm/activity', $q);
533 if ($activity->activity_type_id == CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name')) {
534 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/pdf/add',
eb873b6e 535 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
6a488035
TO
536 );
537 }
538 else {
539 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/add',
e63aff1c 540 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"
6a488035
TO
541 );
542 }
543
544 if (CRM_Core_Permission::check("delete activities")) {
545 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity',
e63aff1c 546 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"
6a488035
TO
547 );
548 }
549 }
550 else {
551 $url = CRM_Utils_System::url('civicrm/activity/view', $q);
552 if (CRM_Core_Permission::check('delete activities')) {
553 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity',
7ad77be0 554 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"
6a488035
TO
555 );
556 }
557 }
558 }
559
560 if (!isset($activity->parent_id)) {
561 $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
562 // add the recently created Activity
563 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
564 $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
565
566 $title = "";
567 if (isset($activitySubject)) {
568 $title = $activitySubject . ' - ';
569 }
570
571 $title = $title . $recentContactDisplay;
a7488080 572 if (!empty($activityTypes[$activity->activity_type_id])) {
6a488035
TO
573 $title .= ' (' . $activityTypes[$activity->activity_type_id] . ')';
574 }
575
576 CRM_Utils_Recent::add($title,
577 $url,
578 $activity->id,
579 'Activity',
580 $recentContactId,
581 $recentContactDisplay,
582 $recentOther
583 );
584 }
585 }
586
2b68a50c 587 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
6a488035 588
a7488080 589 if (!empty($params['id'])) {
6a488035
TO
590 CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
591 }
592 else {
593 CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
594 }
595
596 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
597 $matches = array();
598 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array::value('subject', $params), $matches)) {
9d5494f7
TO
599 $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
600 $hash = $matches[1];
601 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
6a488035
TO
602 $caseParams = array(
603 'activity_id' => $activity->id,
604 'case_id' => CRM_Core_DAO::singleValueQuery($query),
605 );
606 if ($caseParams['case_id']) {
607 CRM_Case_BAO_Case::processCaseActivity($caseParams);
608 }
609 else {
610 self::logActivityAction($activity, "unknown case hash encountered: $hash");
611 }
612 }
613
614 return $result;
615 }
616
ffd93213 617 /**
0965e988
EM
618 * Create an activity.
619 *
620 * @todo elaborate on what this does.
621 *
622 * @param CRM_Core_DAO_Activity $activity
623 * @param string $logMessage
ffd93213
EM
624 *
625 * @return bool
626 */
6a488035 627 public static function logActivityAction($activity, $logMessage = NULL) {
3bdcd4ec 628 $id = CRM_Core_Session::getLoggedInContactID();
6a488035 629 if (!$id) {
e7e657f0 630 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
8a6844b3 631 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
be89435d 632 $id = self::getActivityContact($activity->id, $sourceID);
6a488035
TO
633 }
634 $logParams = array(
635 'entity_table' => 'civicrm_activity',
636 'entity_id' => $activity->id,
637 'modified_id' => $id,
638 'modified_date' => date('YmdHis'),
639 'data' => $logMessage,
640 );
641 CRM_Core_BAO_Log::add($logParams);
642 return TRUE;
643 }
644
645 /**
0965e988 646 * Get the list Activities.
6a488035 647 *
041ab3d1
TO
648 * @param array $input
649 * Array of parameters.
6a488035 650 * Keys include
0a9f61c4 651 * - contact_id int contact_id whose activities we want to retrieve
6a488035
TO
652 * - offset int which row to start from ?
653 * - rowCount int how many rows to fetch
654 * - sort object|array object or array describing sort order for sql query.
655 * - admin boolean if contact is admin
656 * - caseId int case ID
657 * - context string page on which selector is build
658 * - activity_type_id int|string the activitiy types we want to restrict by
659 *
a6c01b45 660 * @return array
0965e988 661 * Relevant data object values of open activities
6a488035 662 */
00be9182 663 public static function &getActivities($input) {
7808aae6 664 // Step 1: Get the basic activity data.
2517d079
DL
665 $bulkActivityTypeID = CRM_Core_OptionGroup::getValue(
666 'activity_type',
6a488035
TO
667 'Bulk Email',
668 'name'
669 );
670
9d13e312
C
671 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
672 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
673 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
674 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
675
6a488035
TO
676 $config = CRM_Core_Config::singleton();
677
678 $randomNum = md5(uniqid());
679 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
680
681 $tableFields = array(
682 'activity_id' => 'int unsigned',
683 'activity_date_time' => 'datetime',
b8cab202 684 'source_record_id' => 'int unsigned',
6a488035
TO
685 'status_id' => 'int unsigned',
686 'subject' => 'varchar(255)',
cec82bce 687 'source_contact_name' => 'varchar(255)',
6a488035
TO
688 'activity_type_id' => 'int unsigned',
689 'activity_type' => 'varchar(128)',
690 'case_id' => 'int unsigned',
691 'case_subject' => 'varchar(255)',
692 'campaign_id' => 'int unsigned',
693 );
694
695 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
696 $insertValueSQL = array();
6da5bfce 697 // The activityTempTable contains the sorted rows
698 // so in order to maintain the sort order as-is we add an auto_increment
699 // field; we can sort by this later to ensure the sort order stays correct.
700 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
6a488035
TO
701 foreach ($tableFields as $name => $desc) {
702 $sql .= "$name $desc,\n";
703 $insertValueSQL[] = $name;
704 }
705
6da5bfce 706 // add unique key on activity_id just to be sure
707 // this cannot be primary key because we need that for the auto_increment
708 // fixed_sort_order field
6a488035 709 $sql .= "
c1d26519 710 UNIQUE KEY ( activity_id )
6a488035
TO
711 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
712 ";
713
714 CRM_Core_DAO::executeQuery($sql);
715
716 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
717
718 $order = $limit = $groupBy = '';
3636b520 719 $groupBy = " GROUP BY tbl.activity_id, tbl.activity_type, tbl.case_id, tbl.case_subject ";
6a488035
TO
720
721 if (!empty($input['sort'])) {
722 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
723 $orderBy = $input['sort']->orderBy();
724 if (!empty($orderBy)) {
725 $order = " ORDER BY $orderBy";
726 }
727 }
728 elseif (trim($input['sort'])) {
21d32567
DL
729 $sort = CRM_Utils_Type::escape($input['sort'], 'String');
730 $order = " ORDER BY $sort ";
6a488035
TO
731 }
732 }
733
734 if (empty($order)) {
6da5bfce 735 // context = 'activity' in Activities tab.
6a488035
TO
736 $order = (CRM_Utils_Array::value('context', $input) == 'activity') ? " ORDER BY tbl.activity_date_time desc " : " ORDER BY tbl.status_id asc, tbl.activity_date_time asc ";
737 }
738
739 if (!empty($input['rowCount']) &&
740 $input['rowCount'] > 0
741 ) {
742 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
743 }
744
745 $input['count'] = FALSE;
746 list($sqlClause, $params) = self::getActivitySQLClause($input);
747
748 $query = "{$insertSQL}
749 SELECT DISTINCT tbl.* from ( {$sqlClause} )
750as tbl ";
751
7808aae6 752 // Filter case activities - CRM-5761.
6a488035
TO
753 $components = self::activityComponents();
754 if (!in_array('CiviCase', $components)) {
755 $query .= "
756LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
757 WHERE civicrm_case_activity.id IS NULL";
758 }
759
760 $query = $query . $groupBy . $order . $limit;
761
762 $dao = CRM_Core_DAO::executeQuery($query, $params);
763
6a488035
TO
764 // step 2: Get target and assignee contacts for above activities
765 // create temp table for target contacts
91da6cd5
DL
766 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
767 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
d10f9247 768 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
9d13e312 769 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
f8967735 770 ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
6a488035
TO
771
772 CRM_Core_DAO::executeQuery($query);
773
774 // note that we ignore bulk email for targets, since we don't show it in selector
91da6cd5 775 $query = "
d8a22375 776INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
91da6cd5
DL
777SELECT ac.activity_id,
778 ac.contact_id,
5b5da1ef 779 ac.record_type_id,
d8a22375
BS
780 c.sort_name,
781 c.is_deleted
d10f9247 782FROM {$activityTempTable}
9254ec4e 783INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
d10f9247 784INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
5b5da1ef 785INNER JOIN civicrm_contact c ON c.id = ac.contact_id
9254ec4e 786WHERE ac.record_type_id != %1
91da6cd5 787";
9254ec4e
C
788 $params = array(1 => array($targetID, 'Integer'));
789 CRM_Core_DAO::executeQuery($query, $params);
6a488035 790
36d2f4d5 791 $activityFields = array("ac.activity_id", "ac.contact_id", "ac.record_type_id", "c.sort_name", "c.is_deleted");
792 $select = CRM_Contact_BAO_Query::appendAnyValueToSelect($activityFields, "ac.activity_id");
793
9d13e312 794 // for each activity insert one target contact
7808aae6 795 // if we load all target contacts the performance will suffer a lot for mass-activities.
3636b520 796 $query = "
797INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
36d2f4d5 798{$select}, count(ac.contact_id)
9d13e312 799FROM {$activityTempTable}
9254ec4e 800INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
9d13e312
C
801INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
802INNER JOIN civicrm_contact c ON c.id = ac.contact_id
803WHERE ac.record_type_id = %1
36d2f4d5 804GROUP BY ac.activity_id
9d13e312 805";
9254ec4e 806
9d13e312
C
807 CRM_Core_DAO::executeQuery($query, $params);
808
6a488035 809 // step 3: Combine all temp tables to get final query for activity selector
6da5bfce 810 // sort by the original sort order, stored in fixed_sort_order
6a488035 811 $query = "
91da6cd5
DL
812SELECT {$activityTempTable}.*,
813 {$activityContactTempTable}.contact_id,
a24b3694 814 {$activityContactTempTable}.record_type_id,
d8a22375 815 {$activityContactTempTable}.contact_name,
9d13e312 816 {$activityContactTempTable}.is_deleted,
97c7504f 817 {$activityContactTempTable}.counter,
818 re.parent_id as is_recurring_activity
91da6cd5
DL
819FROM {$activityTempTable}
820INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
97c7504f 821LEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id
6da5bfce 822ORDER BY fixed_sort_order
6a488035
TO
823 ";
824
6a488035
TO
825 $dao = CRM_Core_DAO::executeQuery($query);
826
7808aae6 827 // CRM-3553, need to check user has access to target groups.
6a488035
TO
828 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
829 $accessCiviMail = (
830 (CRM_Core_Permission::check('access CiviMail')) ||
831 (CRM_Mailing_Info::workflowEnabled() &&
832 CRM_Core_Permission::check('create mailings'))
833 );
834
7808aae6 835 // Get all campaigns.
6a488035 836 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
6a488035
TO
837 $values = array();
838 while ($dao->fetch()) {
839 $activityID = $dao->activity_id;
840 $values[$activityID]['activity_id'] = $dao->activity_id;
841 $values[$activityID]['source_record_id'] = $dao->source_record_id;
842 $values[$activityID]['activity_type_id'] = $dao->activity_type_id;
843 $values[$activityID]['activity_type'] = $dao->activity_type;
844 $values[$activityID]['activity_date_time'] = $dao->activity_date_time;
845 $values[$activityID]['status_id'] = $dao->status_id;
846 $values[$activityID]['subject'] = $dao->subject;
6a488035 847 $values[$activityID]['campaign_id'] = $dao->campaign_id;
97c7504f 848 $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity;
6a488035
TO
849
850 if ($dao->campaign_id) {
851 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id];
852 }
853
a7488080 854 if (empty($values[$activityID]['assignee_contact_name'])) {
6a488035
TO
855 $values[$activityID]['assignee_contact_name'] = array();
856 }
857
a7488080 858 if (empty($values[$activityID]['target_contact_name'])) {
6a488035 859 $values[$activityID]['target_contact_name'] = array();
9254ec4e 860 $values[$activityID]['target_contact_counter'] = $dao->counter;
6a488035
TO
861 }
862
d8a22375 863 // if deleted, wrap in <del>
9d5494f7 864 if ($dao->is_deleted) {
e7a282c5 865 $dao->contact_name = "<del>{$dao->contact_name}</del>";
d8a22375
BS
866 }
867
9d5494f7 868 if ($dao->record_type_id == $sourceID && $dao->contact_id) {
91da6cd5
DL
869 $values[$activityID]['source_contact_id'] = $dao->contact_id;
870 $values[$activityID]['source_contact_name'] = $dao->contact_name;
871 }
872
6a488035
TO
873 if (!$bulkActivityTypeID || ($bulkActivityTypeID != $dao->activity_type_id)) {
874 // build array of target / assignee names
a24b3694 875 if ($dao->record_type_id == $targetID && $dao->contact_id) {
91da6cd5 876 $values[$activityID]['target_contact_name'][$dao->contact_id] = $dao->contact_name;
6a488035 877 }
a24b3694 878 if ($dao->record_type_id == $assigneeID && $dao->contact_id) {
91da6cd5 879 $values[$activityID]['assignee_contact_name'][$dao->contact_id] = $dao->contact_name;
6a488035
TO
880 }
881
882 // case related fields
883 $values[$activityID]['case_id'] = $dao->case_id;
884 $values[$activityID]['case_subject'] = $dao->case_subject;
885 }
886 else {
9d5494f7
TO
887 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter));
888 $values[$activityID]['mailingId'] = FALSE;
6a488035
TO
889 if (
890 $accessCiviMail &&
891 ($mailingIDs === TRUE || in_array($dao->source_record_id, $mailingIDs))
892 ) {
9d5494f7 893 $values[$activityID]['mailingId'] = TRUE;
6a488035
TO
894 }
895 }
896 }
897
6a488035
TO
898 return $values;
899 }
900
901 /**
0965e988
EM
902 * Get the component id and name if those are enabled and allowed.
903 *
904 * Checks whether logged in user has permission.
905 * To decide whether we are going to include
906 * component related activities with core activity retrieve process.
907 * (what did that just mean?)
6a488035 908 *
a6c01b45 909 * @return array
16b10e64 910 * Array of component id and name.
59f4c9ee 911 */
00be9182 912 public static function activityComponents() {
6a488035
TO
913 $components = array();
914 $compInfo = CRM_Core_Component::getEnabledComponents();
915 foreach ($compInfo as $compObj) {
a7488080 916 if (!empty($compObj->info['showActivitiesInCore'])) {
6a488035
TO
917 if ($compObj->info['name'] == 'CiviCampaign') {
918 $componentPermission = "administer {$compObj->name}";
919 }
920 else {
921 $componentPermission = "access {$compObj->name}";
922 }
923 if ($compObj->info['name'] == 'CiviCase') {
924 if (CRM_Case_BAO_Case::accessCiviCase()) {
925 $components[$compObj->componentID] = $compObj->info['name'];
926 }
927 }
928 elseif (CRM_Core_Permission::check($componentPermission)) {
929 $components[$compObj->componentID] = $compObj->info['name'];
930 }
931 }
932 }
933
934 return $components;
935 }
936
937 /**
0965e988 938 * Get the activity Count.
6a488035 939 *
041ab3d1
TO
940 * @param array $input
941 * Array of parameters.
6a488035 942 * Keys include
0a9f61c4 943 * - contact_id int contact_id whose activities we want to retrieve
6a488035
TO
944 * - admin boolean if contact is admin
945 * - caseId int case ID
946 * - context string page on which selector is build
0a9f61c4 947 * - activity_type_id int|string the activity types we want to restrict by
6a488035 948 *
a6c01b45
CW
949 * @return int
950 * count of activities
6a488035 951 */
00be9182 952 public static function &getActivitiesCount($input) {
6a488035
TO
953 $input['count'] = TRUE;
954 list($sqlClause, $params) = self::getActivitySQLClause($input);
955
956 //filter case activities - CRM-5761
957 $components = self::activityComponents();
958 if (!in_array('CiviCase', $components)) {
959 $query = "
960 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
961 FROM ( {$sqlClause} ) as tbl
962LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
963 WHERE civicrm_case_activity.id IS NULL";
964 }
965 else {
966 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
967 }
968
969 return CRM_Core_DAO::singleValueQuery($query, $params);
970 }
971
972 /**
0965e988 973 * Get the activity sql clause to pick activities.
6a488035 974 *
041ab3d1
TO
975 * @param array $input
976 * Array of parameters.
6a488035 977 * Keys include
0a9f61c4 978 * - contact_id int contact_id whose activities we want to retrieve
6a488035
TO
979 * - admin boolean if contact is admin
980 * - caseId int case ID
981 * - context string page on which selector is build
982 * - count boolean are we interested in the count clause only?
0a9f61c4 983 * - activity_type_id int|string the activity types we want to restrict by
6a488035 984 *
a6c01b45
CW
985 * @return int
986 * count of activities
6a488035 987 */
00be9182 988 public static function getActivitySQLClause($input) {
6a488035
TO
989 $params = array();
990 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
991
992 $config = CRM_Core_Config::singleton();
993 if (!CRM_Utils_Array::value('admin', $input, FALSE)) {
9d5494f7
TO
994 $sourceWhere = ' ac.contact_id = %1 ';
995 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
6a488035
TO
996
997 $params = array(1 => array($input['contact_id'], 'Integer'));
998 }
999
1000 $commonClauses = array(
1001 "civicrm_option_group.name = 'activity_type'",
1002 "civicrm_activity.is_deleted = 0",
1003 "civicrm_activity.is_current_revision = 1",
2517d079 1004 "civicrm_activity.is_test= 0",
6a488035
TO
1005 );
1006
1007 if ($input['context'] != 'activity') {
1008 $commonClauses[] = "civicrm_activity.status_id = 1";
1009 }
1010
7808aae6 1011 // Filter on component IDs.
6a488035
TO
1012 $components = self::activityComponents();
1013 if (!empty($components)) {
1014 $componentsIn = implode(',', array_keys($components));
1015 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1016 }
1017 else {
1018 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1019 }
1020
1021 // activity type ID clause
1022 if (!empty($input['activity_type_id'])) {
1023 if (is_array($input['activity_type_id'])) {
1024 foreach ($input['activity_type_id'] as $idx => $value) {
1025 $input['activity_type_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1026 }
1027 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1028 }
1029 else {
1030 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_id'], 'Positive');
1031 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1032 }
1033 }
1034
1035 // exclude by activity type clause
1036 if (!empty($input['activity_type_exclude_id'])) {
1037 if (is_array($input['activity_type_exclude_id'])) {
1038 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1039 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1040 }
1041 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1042 }
1043 else {
1044 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_exclude_id'], 'Positive');
1045 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1046 }
1047 }
1048
1049 $commonClause = implode(' AND ', $commonClauses);
1050
1051 $includeCaseActivities = FALSE;
1052 if (in_array('CiviCase', $components)) {
1053 $includeCaseActivities = TRUE;
1054 }
1055
6a488035
TO
1056 // build main activity table select clause
1057 $sourceSelect = '';
cec82bce 1058
1059 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1060 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
a3696ce8 1061 $sourceJoin = "
b8cab202 1062INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
a3696ce8
DL
1063INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1064";
6a488035
TO
1065
1066 if (!$input['count']) {
1067 $sourceSelect = ',
1068 civicrm_activity.activity_date_time,
b8cab202 1069 civicrm_activity.source_record_id,
6a488035
TO
1070 civicrm_activity.status_id,
1071 civicrm_activity.subject,
cec82bce 1072 contact.sort_name as source_contact_name,
6a488035
TO
1073 civicrm_option_value.value as activity_type_id,
1074 civicrm_option_value.label as activity_type,
1075 null as case_id, null as case_subject,
5b5da1ef 1076 civicrm_activity.campaign_id as campaign_id
6a488035
TO
1077 ';
1078
b8cab202
PJ
1079 $sourceJoin .= "
1080LEFT JOIN civicrm_activity_contact src ON (src.activity_id = ac.activity_id AND src.record_type_id = {$sourceID} AND src.contact_id = contact.id)
1081";
6a488035
TO
1082 }
1083
1084 $sourceClause = "
1085 SELECT civicrm_activity.id as activity_id
1086 {$sourceSelect}
1087 from civicrm_activity
1088 left join civicrm_option_value on
1089 civicrm_activity.activity_type_id = civicrm_option_value.value
1090 left join civicrm_option_group on
1091 civicrm_option_group.id = civicrm_option_value.option_group_id
1092 {$sourceJoin}
1093 where
1094 {$sourceWhere}
1095 AND $commonClause
1096 ";
1097
6a488035
TO
1098 // Build case clause
1099 // or else exclude Inbound Emails that have been filed on a case.
1100 $caseClause = '';
1101
1102 if ($includeCaseActivities) {
1103 $caseSelect = '';
1104 if (!$input['count']) {
1105 $caseSelect = ',
1106 civicrm_activity.activity_date_time,
b8cab202 1107 civicrm_activity.source_record_id,
6a488035
TO
1108 civicrm_activity.status_id,
1109 civicrm_activity.subject,
cec82bce 1110 contact.sort_name as source_contact_name,
6a488035
TO
1111 civicrm_option_value.value as activity_type_id,
1112 civicrm_option_value.label as activity_type,
1113 null as case_id, null as case_subject,
1114 civicrm_activity.campaign_id as campaign_id';
1115 }
1116
1117 $caseClause = "
1118 union all
1119
1120 SELECT civicrm_activity.id as activity_id
1121 {$caseSelect}
1122 from civicrm_activity
1123 inner join civicrm_case_activity on
1124 civicrm_case_activity.activity_id = civicrm_activity.id
1125 inner join civicrm_case on
1126 civicrm_case_activity.case_id = civicrm_case.id
1127 inner join civicrm_case_contact on
1128 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1129 left join civicrm_option_value on
1130 civicrm_activity.activity_type_id = civicrm_option_value.value
1131 left join civicrm_option_group on
1132 civicrm_option_group.id = civicrm_option_value.option_group_id
1133 {$sourceJoin}
1134 where
1135 {$caseWhere}
1136 AND $commonClause
1137 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1138 ( civicrm_option_value.name <> 'Inbound Email' AND
1139 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1140 IS NOT NULL )
1141 )
1142 ";
1143 }
1144
a3696ce8 1145 $returnClause = " {$sourceClause} {$caseClause} ";
6a488035
TO
1146
1147 return array($returnClause, $params);
1148 }
1149
1150 /**
0965e988
EM
1151 * Send the message to all the contacts.
1152 *
1153 * Also insert a contact activity in each contacts record.
6a488035 1154 *
041ab3d1
TO
1155 * @param array $contactDetails
1156 * The array of contact details to send the email.
1157 * @param string $subject
1158 * The subject of the message.
fd31fa4c
EM
1159 * @param $text
1160 * @param $html
041ab3d1
TO
1161 * @param string $emailAddress
1162 * Use this 'to' email address instead of the default Primary address.
1163 * @param int $userID
1164 * Use this userID if set.
6a488035 1165 * @param string $from
041ab3d1
TO
1166 * @param array $attachments
1167 * The array of attachments if any.
1168 * @param string $cc
1169 * Cc recipient.
1170 * @param string $bcc
1171 * Bcc recipient.
1172 * @param array $contactIds
1173 * Contact ids.
1174 * @param string $additionalDetails
1175 * The additional information of CC and BCC appended to the activity Details.
6a488035 1176 *
a6c01b45
CW
1177 * @return array
1178 * ( sent, activityId) if any email is sent and activityId
6a488035 1179 */
59f4c9ee 1180 public static function sendEmail(
6a488035
TO
1181 &$contactDetails,
1182 &$subject,
1183 &$text,
1184 &$html,
1185 $emailAddress,
9d5494f7
TO
1186 $userID = NULL,
1187 $from = NULL,
6a488035 1188 $attachments = NULL,
9d5494f7
TO
1189 $cc = NULL,
1190 $bcc = NULL,
6c552737 1191 $contactIds = NULL,
c1d26519 1192 $additionalDetails = NULL
6a488035
TO
1193 ) {
1194 // get the contact details of logged in contact, which we set as from email
1195 if ($userID == NULL) {
3bdcd4ec 1196 $userID = CRM_Core_Session::getLoggedInContactID();
6a488035
TO
1197 }
1198
1199 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1200 if (!$fromEmail) {
1201 return array(count($contactDetails), 0, count($contactDetails));
1202 }
1203 if (!trim($fromDisplayName)) {
1204 $fromDisplayName = $fromEmail;
1205 }
1206
1207 // CRM-4575
1208 // token replacement of addressee/email/postal greetings
1209 // get the tokens added in subject and message
1210 $subjectToken = CRM_Utils_Token::getTokens($subject);
1211 $messageToken = CRM_Utils_Token::getTokens($text);
1212 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
c7436e9c 1213 $allTokens = array_merge($messageToken, $subjectToken);
6a488035
TO
1214
1215 if (!$from) {
1216 $from = "$fromDisplayName <$fromEmail>";
1217 }
1218
1219 //create the meta level record first ( email activity )
1220 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1221 'Email',
1222 'name'
1223 );
1224
1225 // CRM-6265: save both text and HTML parts in details (if present)
1226 if ($html and $text) {
c1d26519 1227 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
6a488035
TO
1228 }
1229 else {
1230 $details = $html ? $html : $text;
c1d26519 1231 $details .= $additionalDetails;
6a488035
TO
1232 }
1233
1234 $activityParams = array(
1235 'source_contact_id' => $userID,
1236 'activity_type_id' => $activityTypeID,
1237 'activity_date_time' => date('YmdHis'),
1238 'subject' => $subject,
1239 'details' => $details,
1240 // FIXME: check for name Completed and get ID from that lookup
1241 'status_id' => 2,
1242 );
1243
1244 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1245 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1246
1247 // add the attachments to activity params here
1248 if ($attachments) {
1249 // first process them
1250 $activityParams = array_merge($activityParams,
1251 $attachments
1252 );
1253 }
1254
1255 $activity = self::create($activityParams);
1256
1257 // get the set of attachments from where they are stored
1258 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity',
1259 $activity->id
1260 );
1261 $returnProperties = array();
1262 if (isset($messageToken['contact'])) {
1263 foreach ($messageToken['contact'] as $key => $value) {
1264 $returnProperties[$value] = 1;
1265 }
1266 }
1267
1268 if (isset($subjectToken['contact'])) {
1269 foreach ($subjectToken['contact'] as $key => $value) {
1270 if (!isset($returnProperties[$value])) {
1271 $returnProperties[$value] = 1;
1272 }
1273 }
1274 }
1275
6a488035
TO
1276 // get token details for contacts, call only if tokens are used
1277 $details = array();
db969160 1278 if (!empty($returnProperties) || !empty($tokens) || !empty($allTokens)) {
6a488035
TO
1279 list($details) = CRM_Utils_Token::getTokenDetails(
1280 $contactIds,
1281 $returnProperties,
1282 NULL, NULL, FALSE,
c7436e9c 1283 $allTokens,
6a488035
TO
1284 'CRM_Activity_BAO_Activity'
1285 );
1286 }
1287
1288 // call token hook
1289 $tokens = array();
1290 CRM_Utils_Hook::tokens($tokens);
1291 $categories = array_keys($tokens);
1292
1293 $escapeSmarty = FALSE;
1294 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1295 $smarty = CRM_Core_Smarty::singleton();
1296 $escapeSmarty = TRUE;
1297 }
1298
1299 $sent = $notSent = array();
1300 foreach ($contactDetails as $values) {
1301 $contactId = $values['contact_id'];
1302 $emailAddress = $values['email'];
1303
1304 if (!empty($details) && is_array($details["{$contactId}"])) {
1305 // unset email from details since it always returns primary email address
1306 unset($details["{$contactId}"]['email']);
1307 unset($details["{$contactId}"]['email_id']);
1308 $values = array_merge($values, $details["{$contactId}"]);
1309 }
1310
1311 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1312 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1313
7808aae6 1314 // CRM-4539
6a488035
TO
1315 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1316 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1317 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1318 }
1319 else {
1320 $tokenText = NULL;
1321 }
1322
1323 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1324 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1325 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1326 }
1327 else {
1328 $tokenHtml = NULL;
1329 }
1330
1331 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1332 // also add the contact tokens to the template
1333 $smarty->assign_by_ref('contact', $values);
1334
1335 $tokenSubject = $smarty->fetch("string:$tokenSubject");
9d5494f7
TO
1336 $tokenText = $smarty->fetch("string:$tokenText");
1337 $tokenHtml = $smarty->fetch("string:$tokenHtml");
6a488035
TO
1338 }
1339
1340 $sent = FALSE;
1341 if (self::sendMessage(
9d5494f7
TO
1342 $from,
1343 $userID,
1344 $contactId,
1345 $tokenSubject,
1346 $tokenText,
1347 $tokenHtml,
1348 $emailAddress,
1349 $activity->id,
1350 $attachments,
1351 $cc,
1352 $bcc
1353 )
1354 ) {
6a488035
TO
1355 $sent = TRUE;
1356 }
1357 }
1358
1359 return array($sent, $activity->id);
1360 }
1361
ffd93213 1362 /**
0965e988
EM
1363 * Send SMS.
1364 *
100fef9d
CW
1365 * @param array $contactDetails
1366 * @param array $activityParams
ffd93213
EM
1367 * @param array $smsParams
1368 * @param $contactIds
100fef9d 1369 * @param int $userID
ffd93213
EM
1370 *
1371 * @return array
1372 * @throws CRM_Core_Exception
1373 */
59f4c9ee 1374 public static function sendSMS(
9d5494f7 1375 &$contactDetails,
6a488035
TO
1376 &$activityParams,
1377 &$smsParams = array(),
1378 &$contactIds,
1379 $userID = NULL
1380 ) {
1381 if ($userID == NULL) {
3bdcd4ec 1382 $userID = CRM_Core_Session::getLoggedInContactID();
6a488035
TO
1383 }
1384
1b7a39f5 1385 $text = &$activityParams['sms_text_message'];
6a488035
TO
1386
1387 // CRM-4575
1388 // token replacement of addressee/email/postal greetings
1389 // get the tokens added in subject and message
1390 $messageToken = CRM_Utils_Token::getTokens($text);
6a488035 1391
7808aae6 1392 // Create the meta level record first ( sms activity )
6a488035
TO
1393 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1394 'SMS',
1395 'name'
1396 );
1397
1b7a39f5 1398 $details = $text;
6a488035
TO
1399
1400 $activitySubject = $activityParams['activity_subject'];
1401 $activityParams = array(
1402 'source_contact_id' => $userID,
1403 'activity_type_id' => $activityTypeID,
1404 'activity_date_time' => date('YmdHis'),
1405 'subject' => $activitySubject,
1406 'details' => $details,
1407 // FIXME: check for name Completed and get ID from that lookup
1408 'status_id' => 2,
1409 );
1410
1411 $activity = self::create($activityParams);
1412 $activityID = $activity->id;
1413
1414 $returnProperties = array();
1415
1416 if (isset($messageToken['contact'])) {
1417 foreach ($messageToken['contact'] as $key => $value) {
1418 $returnProperties[$value] = 1;
1419 }
1420 }
1421
1422 // call token hook
1423 $tokens = array();
1424 CRM_Utils_Hook::tokens($tokens);
1425 $categories = array_keys($tokens);
1426
1427 // get token details for contacts, call only if tokens are used
1428 $details = array();
1429 if (!empty($returnProperties) || !empty($tokens)) {
1430 list($details) = CRM_Utils_Token::getTokenDetails($contactIds,
1431 $returnProperties,
1432 NULL, NULL, FALSE,
1433 $messageToken,
1434 'CRM_Activity_BAO_Activity'
1435 );
1436 }
1437
f53ea1ce 1438 $success = 0;
c5a6413b
DS
1439 $escapeSmarty = FALSE;
1440 $errMsgs = array();
6a488035
TO
1441 foreach ($contactDetails as $values) {
1442 $contactId = $values['contact_id'];
1443
1444 if (!empty($details) && is_array($details["{$contactId}"])) {
c965c606
JM
1445 // unset phone from details since it always returns primary number
1446 unset($details["{$contactId}"]['phone']);
1447 unset($details["{$contactId}"]['phone_type_id']);
6a488035
TO
1448 $values = array_merge($values, $details["{$contactId}"]);
1449 }
1450
1451 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1452 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1453
d65e1a68 1454 // Only send if the phone is of type mobile
9357a775
DS
1455 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1456 if ($values['phone_type_id'] == CRM_Utils_Array::value('Mobile', $phoneTypes)) {
d65e1a68 1457 $smsParams['To'] = $values['phone'];
01aca362
DL
1458 }
1459 else {
d65e1a68
TW
1460 $smsParams['To'] = '';
1461 }
6a488035 1462
c5a6413b
DS
1463 $sendResult = self::sendSMSMessage(
1464 $contactId,
1465 $tokenText,
c5a6413b 1466 $smsParams,
e8cb3963
DS
1467 $activityID,
1468 $userID
c5a6413b
DS
1469 );
1470
1471 if (PEAR::isError($sendResult)) {
1472 // Collect all of the PEAR_Error objects
1473 $errMsgs[] = $sendResult;
9d5494f7
TO
1474 }
1475 else {
f53ea1ce 1476 $success++;
6a488035
TO
1477 }
1478 }
1479
c5a6413b
DS
1480 // If at least one message was sent and no errors
1481 // were generated then return a boolean value of TRUE.
1482 // Otherwise, return FALSE (no messages sent) or
1483 // and array of 1 or more PEAR_Error objects.
1484 $sent = FALSE;
1485 if ($success > 0 && count($errMsgs) == 0) {
1486 $sent = TRUE;
9d5494f7
TO
1487 }
1488 elseif (count($errMsgs) > 0) {
c5a6413b
DS
1489 $sent = $errMsgs;
1490 }
1491
f53ea1ce 1492 return array($sent, $activity->id, $success);
6a488035
TO
1493 }
1494
1495 /**
5c9ff055 1496 * Send the sms message to a specific contact.
6a488035 1497 *
041ab3d1
TO
1498 * @param int $toID
1499 * The contact id of the recipient.
77b97be7 1500 * @param $tokenText
041ab3d1
TO
1501 * @param array $smsParams
1502 * The params used for sending sms.
1503 * @param int $activityID
1504 * The activity ID that tracks the message.
100fef9d 1505 * @param int $userID
6a488035 1506 *
72b3a70c
CW
1507 * @return bool|PEAR_Error
1508 * true on success or PEAR_Error object
6a488035 1509 */
59f4c9ee 1510 public static function sendSMSMessage(
9d5494f7 1511 $toID,
6a488035 1512 &$tokenText,
6a488035 1513 $smsParams = array(),
e8cb3963 1514 $activityID,
9d5494f7 1515 $userID = NULL
6a488035
TO
1516 ) {
1517 $toDoNotSms = "";
1518 $toPhoneNumber = "";
1519
1520 if ($smsParams['To']) {
1521 $toPhoneNumber = trim($smsParams['To']);
1522 }
1523 elseif ($toID) {
1524 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1525 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
7808aae6 1526 // To get primary mobile phonenumber,if not get the first mobile phonenumber
6a488035
TO
1527 if (!empty($toPhoneNumbers)) {
1528 $toPhoneNumerDetails = reset($toPhoneNumbers);
1529 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumerDetails);
7808aae6 1530 // Contact allows to send sms
6a488035
TO
1531 $toDoNotSms = 0;
1532 }
1533 }
1534
1535 // make sure both phone are valid
1536 // and that the recipient wants to receive sms
1537 if (empty($toPhoneNumber) or $toDoNotSms) {
c5a6413b
DS
1538 return PEAR::raiseError(
1539 'Recipient phone number is invalid or recipient does not want to receive SMS',
9d5494f7 1540 NULL,
c5a6413b
DS
1541 PEAR_ERROR_RETURN
1542 );
6a488035
TO
1543 }
1544
6a488035
TO
1545 $recipient = $smsParams['To'];
1546 $smsParams['contact_id'] = $toID;
1547 $smsParams['parent_activity_id'] = $activityID;
1548
1549 $providerObj = CRM_SMS_Provider::singleton(array('provider_id' => $smsParams['provider_id']));
1b7a39f5 1550 $sendResult = $providerObj->send($recipient, $smsParams, $tokenText, NULL, $userID);
c5a6413b
DS
1551 if (PEAR::isError($sendResult)) {
1552 return $sendResult;
6a488035
TO
1553 }
1554
e7e657f0 1555 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 1556 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
b319d00a 1557
6a488035
TO
1558 // add activity target record for every sms that is send
1559 $activityTargetParams = array(
1560 'activity_id' => $activityID,
9d5494f7 1561 'contact_id' => $toID,
21dfd5f5 1562 'record_type_id' => $targetID,
6a488035 1563 );
1d85d241 1564 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
6a488035
TO
1565
1566 return TRUE;
1567 }
1568
1569 /**
5c9ff055 1570 * Send the message to a specific contact.
6a488035 1571 *
041ab3d1
TO
1572 * @param string $from
1573 * The name and email of the sender.
100fef9d 1574 * @param int $fromID
041ab3d1
TO
1575 * @param int $toID
1576 * The contact id of the recipient.
1577 * @param string $subject
1578 * The subject of the message.
77b97be7
EM
1579 * @param $text_message
1580 * @param $html_message
041ab3d1
TO
1581 * @param string $emailAddress
1582 * Use this 'to' email address instead of the default Primary address.
1583 * @param int $activityID
1584 * The activity ID that tracks the message.
77b97be7
EM
1585 * @param null $attachments
1586 * @param null $cc
1587 * @param null $bcc
6a488035 1588 *
59f4c9ee
TO
1589 * @return bool
1590 * TRUE if successful else FALSE.
6a488035 1591 */
59f4c9ee 1592 public static function sendMessage(
9d5494f7 1593 $from,
6a488035
TO
1594 $fromID,
1595 $toID,
1596 &$subject,
1597 &$text_message,
1598 &$html_message,
1599 $emailAddress,
1600 $activityID,
1601 $attachments = NULL,
9d5494f7
TO
1602 $cc = NULL,
1603 $bcc = NULL
6a488035
TO
1604 ) {
1605 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1606 if ($emailAddress) {
1607 $toEmail = trim($emailAddress);
1608 }
1609
1610 // make sure both email addresses are valid
1611 // and that the recipient wants to receive email
1612 if (empty($toEmail) or $toDoNotEmail) {
1613 return FALSE;
1614 }
1615 if (!trim($toDisplayName)) {
1616 $toDisplayName = $toEmail;
1617 }
1618
e7e657f0 1619 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 1620 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1621
6a488035
TO
1622 // create the params array
1623 $mailParams = array(
1624 'groupName' => 'Activity Email Sender',
1625 'from' => $from,
1626 'toName' => $toDisplayName,
1627 'toEmail' => $toEmail,
1628 'subject' => $subject,
1629 'cc' => $cc,
1630 'bcc' => $bcc,
1631 'text' => $text_message,
1632 'html' => $html_message,
1633 'attachments' => $attachments,
1634 );
1635
1636 if (!CRM_Utils_Mail::send($mailParams)) {
1637 return FALSE;
1638 }
1639
1640 // add activity target record for every mail that is send
1641 $activityTargetParams = array(
1642 'activity_id' => $activityID,
1d85d241 1643 'contact_id' => $toID,
21dfd5f5 1644 'record_type_id' => $targetID,
6a488035 1645 );
1d85d241 1646 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
6a488035
TO
1647 return TRUE;
1648 }
1649
1650 /**
db7de9c1 1651 * Combine all the importable fields from the lower levels object.
6a488035
TO
1652 *
1653 * The ordering is important, since currently we do not have a weight
1654 * scheme. Adding weight is super important and should be done in the
1655 * next week or so, before this can be called complete.
1656 *
dd244018
EM
1657 * @param bool $status
1658 *
a6c01b45
CW
1659 * @return array
1660 * array of importable Fields
6a488035 1661 */
00be9182 1662 public static function &importableFields($status = FALSE) {
6a488035
TO
1663 if (!self::$_importableFields) {
1664 if (!self::$_importableFields) {
1665 self::$_importableFields = array();
1666 }
1667 if (!$status) {
1668 $fields = array('' => array('title' => ts('- do not import -')));
1669 }
1670 else {
1671 $fields = array('' => array('title' => ts('- Activity Fields -')));
1672 }
1673
1674 $tmpFields = CRM_Activity_DAO_Activity::import();
1675 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1676
1677 // Using new Dedupe rule.
1678 $ruleParams = array(
1679 'contact_type' => 'Individual',
9d5494f7 1680 'used' => 'Unsupervised',
6a488035
TO
1681 );
1682 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1683
1684 $tmpConatctField = array();
1685 if (is_array($fieldsArray)) {
1686 foreach ($fieldsArray as $value) {
1687 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1688 $value,
1689 'id',
1690 'column_name'
1691 );
1692 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1693 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1694 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1695 }
1696 }
1697 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1698 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1699 $fields = array_merge($fields, $tmpConatctField);
1700 $fields = array_merge($fields, $tmpFields);
1701 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
1702 self::$_importableFields = $fields;
1703 }
1704 return self::$_importableFields;
1705 }
1706
1707 /**
57507ae6 1708 * Get the Activities of a target contact.
6a488035 1709 *
041ab3d1
TO
1710 * @param int $contactId
1711 * Id of the contact whose activities need to find.
6a488035 1712 *
a6c01b45
CW
1713 * @return array
1714 * array of activity fields
6a488035 1715 */
00be9182 1716 public static function getContactActivity($contactId) {
6a488035 1717 $activities = array();
e7e657f0 1718 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 1719 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1720 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1721 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
b319d00a 1722
6a488035 1723 // First look for activities where contactId is one of the targets
91da6cd5 1724 $query = "
a24b3694 1725SELECT activity_id, record_type_id
91da6cd5
DL
1726FROM civicrm_activity_contact
1727WHERE contact_id = $contactId
1728";
1729 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 1730 while ($dao->fetch()) {
9d5494f7 1731 if ($dao->record_type_id == $targetID) {
91da6cd5
DL
1732 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
1733 }
4c9b6178 1734 elseif ($dao->record_type_id == $assigneeID) {
91da6cd5
DL
1735 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1736 }
1737 else {
1738 // do source stuff here
42d30b83 1739 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
91da6cd5 1740 }
6a488035
TO
1741 }
1742
91da6cd5 1743 $activityIds = array_keys($activities);
6a488035
TO
1744 if (count($activityIds) < 1) {
1745 return array();
1746 }
91da6cd5 1747
6a488035 1748 $activityIds = implode(',', $activityIds);
91da6cd5
DL
1749 $query = "
1750SELECT activity.id as activity_id,
1751 activity_type_id,
1752 subject, location, activity_date_time, details, status_id
1753FROM civicrm_activity activity
1754WHERE activity.id IN ($activityIds)";
6a488035 1755
91da6cd5 1756 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1757
1758 $activityTypes = CRM_Core_OptionGroup::values('activity_type');
1759 $activityStatuses = CRM_Core_OptionGroup::values('activity_status');
1760
1761 while ($dao->fetch()) {
6a488035 1762 $activities[$dao->activity_id]['id'] = $dao->activity_id;
6a488035
TO
1763 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
1764 $activities[$dao->activity_id]['subject'] = $dao->subject;
1765 $activities[$dao->activity_id]['location'] = $dao->location;
1766 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
1767 $activities[$dao->activity_id]['details'] = $dao->details;
1768 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
1769 $activities[$dao->activity_id]['activity_name'] = $activityTypes[$dao->activity_type_id];
1770 $activities[$dao->activity_id]['status'] = $activityStatuses[$dao->status_id];
42d30b83
DL
1771
1772 // set to null if not set
1773 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
1774 $activities[$dao->activity_id]['source_contact_id'] = NULL;
1775 }
6a488035
TO
1776 }
1777 return $activities;
1778 }
1779
1780 /**
57507ae6 1781 * Add activity for Membership/Event/Contribution.
6a488035 1782 *
041ab3d1
TO
1783 * @param object $activity
1784 * (reference) particular component object.
1785 * @param string $activityType
1786 * For Membership Signup or Renewal.
c490a46a 1787 * @param int $targetContactID
6a488035 1788 *
59f4c9ee 1789 * @return bool|NULL
6a488035 1790 */
59f4c9ee 1791 public static function addActivity(
9d5494f7 1792 &$activity,
6a488035
TO
1793 $activityType = 'Membership Signup',
1794 $targetContactID = NULL
1795 ) {
1796 if ($activity->__table == 'civicrm_membership') {
1797 $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id);
1798
1799 if (!$membershipType) {
1800 $membershipType = ts('Membership');
1801 }
1802
1803 $subject = "{$membershipType}";
1804
1805 if (!empty($activity->source) && $activity->source != 'null') {
1806 $subject .= " - {$activity->source}";
1807 }
1808
1809 if ($activity->owner_membership_id) {
1810 $query = "
1811SELECT display_name
1812 FROM civicrm_contact, civicrm_membership
1813 WHERE civicrm_contact.id = civicrm_membership.contact_id
1814 AND civicrm_membership.id = $activity->owner_membership_id
1815";
1816 $displayName = CRM_Core_DAO::singleValueQuery($query);
1817 $subject .= " (by {$displayName})";
1818 }
1819
a573300e 1820 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id, 'label');
6a488035
TO
1821 // CRM-72097 changed from start date to today
1822 $date = date('YmdHis');
1823 $component = 'Membership';
1824 }
1825 elseif ($activity->__table == 'civicrm_participant') {
c2be40dc 1826 $event = CRM_Event_BAO_Event::getEvents(1, $activity->event_id, TRUE, FALSE);
6a488035
TO
1827
1828 $roles = CRM_Event_PseudoConstant::participantRole();
1829 $status = CRM_Event_PseudoConstant::participantStatus();
1830
1831 $subject = $event[$activity->event_id];
a7488080 1832 if (!empty($roles[$activity->role_id])) {
6a488035
TO
1833 $subject .= ' - ' . $roles[$activity->role_id];
1834 }
a7488080 1835 if (!empty($status[$activity->status_id])) {
6a488035
TO
1836 $subject .= ' - ' . $status[$activity->status_id];
1837 }
1838 $date = date('YmdHis');
1839 if ($activityType != 'Email') {
1840 $activityType = 'Event Registration';
1841 }
1842 $component = 'Event';
1843 }
1844 elseif ($activity->__table == 'civicrm_contribution') {
7808aae6 1845 // create activity record only for Completed Contributions
6a488035 1846 if ($activity->contribution_status_id != 1) {
59f4c9ee 1847 return NULL;
6a488035
TO
1848 }
1849
1850 $subject = NULL;
1851
1852 $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency);
1853 if (!empty($activity->source) && $activity->source != 'null') {
1854 $subject .= " - {$activity->source}";
1855 }
1856 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
1857 $activityType = $component = 'Contribution';
1858 }
1859 $activityParams = array(
1860 'source_contact_id' => $activity->contact_id,
1861 'source_record_id' => $activity->id,
1862 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1863 $activityType,
1864 'name'
1865 ),
1866 'subject' => $subject,
1867 'activity_date_time' => $date,
1868 'is_test' => $activity->is_test,
1869 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
1870 'Completed',
1871 'name'
1872 ),
1873 'skipRecentView' => TRUE,
1874 'campaign_id' => $activity->campaign_id,
1875 );
1876
6e143f06
WA
1877 if (!empty($activity->activity_id)) {
1878 $activityParams['id'] = $activity->activity_id;
1879 }
6a488035 1880 // create activity with target contacts
3bdcd4ec 1881 $id = CRM_Core_Session::getLoggedInContactID();
6a488035
TO
1882 if ($id) {
1883 $activityParams['source_contact_id'] = $id;
1884 $activityParams['target_contact_id'][] = $activity->contact_id;
1885 }
1886
b870f878 1887 // CRM-14945
1888 if (property_exists($activity, 'details')) {
1889 $activityParams['details'] = $activity->details;
1890 }
6a488035
TO
1891 //CRM-4027
1892 if ($targetContactID) {
1893 $activityParams['target_contact_id'][] = $targetContactID;
1894 }
1895 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
1896 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
1897 return FALSE;
1898 }
1899 }
1900
1901 /**
57507ae6 1902 * Get Parent activity for currently viewed activity.
6a488035 1903 *
041ab3d1
TO
1904 * @param int $activityId
1905 * Current activity id.
6a488035 1906 *
a6c01b45 1907 * @return int
57507ae6 1908 * Id of parent activity otherwise false.
6a488035 1909 */
00be9182 1910 public static function getParentActivity($activityId) {
6a488035
TO
1911 static $parentActivities = array();
1912
1913 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1914
1915 if (!array_key_exists($activityId, $parentActivities)) {
1916 $parentActivities[$activityId] = array();
1917
1918 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1919 $activityId,
1920 'parent_id'
1921 );
1922
1923 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1924 }
1925
1926 return $parentActivities[$activityId];
1927 }
1928
1929 /**
57507ae6 1930 * Get total count of prior revision of currently viewed activity.
77b97be7 1931 *
041ab3d1
TO
1932 * @param $activityID
1933 * Current activity id.
6a488035 1934 *
a6c01b45
CW
1935 * @return int
1936 * $params count of prior activities otherwise false.
6a488035 1937 */
00be9182 1938 public static function getPriorCount($activityID) {
6a488035
TO
1939 static $priorCounts = array();
1940
1941 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1942
1943 if (!array_key_exists($activityID, $priorCounts)) {
1944 $priorCounts[$activityID] = array();
1945 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1946 $activityID,
1947 'original_id'
1948 );
1949 $count = 0;
1950 if ($originalID) {
1951 $query = "
1952SELECT count( id ) AS cnt
1953FROM civicrm_activity
1954WHERE ( id = {$originalID} OR original_id = {$originalID} )
1955AND is_current_revision = 0
1956AND id < {$activityID}
1957";
1958 $params = array(1 => array($originalID, 'Integer'));
1959 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1960 }
1961 $priorCounts[$activityID] = $count ? $count : 0;
1962 }
1963
1964 return $priorCounts[$activityID];
1965 }
1966
1967 /**
db7de9c1 1968 * Get all prior activities of currently viewed activity.
6a488035 1969 *
041ab3d1
TO
1970 * @param $activityID
1971 * Current activity id.
77b97be7
EM
1972 * @param bool $onlyPriorRevisions
1973 *
a6c01b45
CW
1974 * @return array
1975 * prior activities info.
6a488035 1976 */
00be9182 1977 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
6a488035
TO
1978 static $priorActivities = array();
1979
1980 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1981 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1982
1983 if (!array_key_exists($index, $priorActivities)) {
1984 $priorActivities[$index] = array();
1985
1986 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1987 $activityID,
1988 'original_id'
1989 );
6ea979d9
CW
1990 if (!$originalID) {
1991 $originalID = $activityID;
1992 }
6a488035
TO
1993 if ($originalID) {
1994 $query = "
1995SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1996FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1997WHERE (ca.id = %1 OR ca.original_id = %1)
1998AND cl.entity_table = 'civicrm_activity'
1999AND cl.entity_id = ca.id
2000AND cl.modified_id = c.id
2001";
2002 if ($onlyPriorRevisions) {
2003 $query .= " AND ca.id < {$activityID}";
2004 }
2005 $query .= " ORDER BY ca.id DESC";
2006
2007 $params = array(1 => array($originalID, 'Integer'));
2008 $dao = CRM_Core_DAO::executeQuery($query, $params);
2009
2010 while ($dao->fetch()) {
2011 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
2012 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
2013 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
6a488035
TO
2014 }
2015 $dao->free();
2016 }
2017 }
2018 return $priorActivities[$index];
2019 }
2020
2021 /**
db7de9c1 2022 * Find the latest revision of a given activity.
6a488035 2023 *
041ab3d1
TO
2024 * @param int $activityID
2025 * Prior activity id.
6a488035 2026 *
a6c01b45
CW
2027 * @return int
2028 * current activity id.
6a488035 2029 */
00be9182 2030 public static function getLatestActivityId($activityID) {
6a488035
TO
2031 static $latestActivityIds = array();
2032
2033 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2034
2035 if (!array_key_exists($activityID, $latestActivityIds)) {
2036 $latestActivityIds[$activityID] = array();
2037
2038 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2039 $activityID,
2040 'original_id'
2041 );
2042 if ($originalID) {
2043 $activityID = $originalID;
2044 }
2045 $params = array(1 => array($activityID, 'Integer'));
2046 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2047
2048 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
2049 }
2050
2051 return $latestActivityIds[$activityID];
2052 }
2053
2054 /**
db7de9c1 2055 * Create a follow up a given activity.
6a488035 2056 *
5a4f6742
CW
2057 * @param int $activityId
2058 * activity id of parent activity.
c490a46a 2059 * @param array $params
77b97be7 2060 *
59f4c9ee 2061 * @return CRM_Activity_BAO_Activity|null|object
6a488035 2062 */
00be9182 2063 public static function createFollowupActivity($activityId, $params) {
6a488035 2064 if (!$activityId) {
59f4c9ee 2065 return NULL;
6a488035
TO
2066 }
2067
6a488035
TO
2068 $followupParams = array();
2069 $followupParams['parent_id'] = $activityId;
3bdcd4ec 2070 $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
6a488035
TO
2071 $followupParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
2072
2073 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2074 // Get Subject of Follow-up Activiity, CRM-4491
2075 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
90b05581 2076 $followupParams['assignee_contact_id'] = CRM_Utils_Array::value('followup_assignee_contact_id', $params);
6a488035 2077
7808aae6 2078 // Create target contact for followup.
a7488080 2079 if (!empty($params['target_contact_id'])) {
6a488035
TO
2080 $followupParams['target_contact_id'] = $params['target_contact_id'];
2081 }
2082
2083 $followupParams['activity_date_time'] = CRM_Utils_Date::processDate($params['followup_date'],
2084 $params['followup_date_time']
2085 );
2086 $followupActivity = self::create($followupParams);
2087
2088 return $followupActivity;
2089 }
2090
2091 /**
100fef9d 2092 * Get Activity specific File according activity type Id.
6a488035 2093 *
041ab3d1
TO
2094 * @param int $activityTypeId
2095 * Activity id.
77b97be7 2096 * @param string $crmDir
6a488035 2097 *
72b3a70c
CW
2098 * @return string|bool
2099 * if file exists returns $activityTypeFile activity filename otherwise false.
6a488035 2100 */
00be9182 2101 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
6a488035
TO
2102 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2103
2104 if ($activityTypes[$activityTypeId]['name']) {
2105 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2106 }
2107 else {
2108 return FALSE;
2109 }
2110
2111 global $civicrm_root;
2112 $config = CRM_Core_Config::singleton();
2113 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2114 if (empty($config->customPHPPathDir)) {
2115 return FALSE;
2116 }
2117 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2118 return FALSE;
2119 }
2120 }
2121
2122 return $activityTypeFile;
2123 }
2124
2125 /**
ee0ce2ef 2126 * Restore the activity.
6a488035 2127 *
041ab3d1 2128 * @param array $params
6a488035 2129 *
ee0ce2ef 2130 * @return CRM_Activity_DAO_Activity
6a488035
TO
2131 */
2132 public static function restoreActivity(&$params) {
2133 $activity = new CRM_Activity_DAO_Activity();
2134 $activity->copyValues($params);
2135
2136 $activity->is_deleted = 0;
2137 $result = $activity->save();
2138
2139 return $result;
2140 }
2141
2142 /**
db7de9c1 2143 * Get the exportable fields for Activities.
6a488035 2144 *
041ab3d1
TO
2145 * @param string $name
2146 * If it is called by case $name = Case else $name = Activity.
6a488035 2147 *
a6c01b45
CW
2148 * @return array
2149 * array of exportable Fields
6a488035 2150 */
00be9182 2151 public static function &exportableFields($name = 'Activity') {
6a488035
TO
2152 if (!isset(self::$_exportableFields[$name])) {
2153 self::$_exportableFields[$name] = array();
2154
7808aae6 2155 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
6a488035
TO
2156 // my case hence we have defined fields as case_*
2157 if ($name == 'Activity') {
2158 $exportableFields = CRM_Activity_DAO_Activity::export();
6a488035
TO
2159 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2160 $exportableFields['source_contact'] = array(
2161 'title' => ts('Source Contact'),
2162 'type' => CRM_Utils_Type::T_STRING,
2163 );
2164
6a488035 2165 $Activityfields = array(
567b2076
EM
2166 'activity_type' => array(
2167 'title' => ts('Activity Type'),
2168 'name' => 'activity_type',
2169 'type' => CRM_Utils_Type::T_STRING,
ed56d481 2170 'searchByLabel' => TRUE,
567b2076
EM
2171 ),
2172 'activity_status' => array(
2173 'title' => ts('Activity Status'),
2174 'name' => 'activity_status',
2175 'type' => CRM_Utils_Type::T_STRING,
ed56d481 2176 'searchByLabel' => TRUE,
567b2076 2177 ),
6a488035
TO
2178 );
2179 $fields = array_merge($Activityfields, $exportableFields);
2180 }
2181 else {
7808aae6 2182 // Set title to activity fields.
6a488035
TO
2183 $fields = array(
2184 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
2185 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
2186 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
9d5494f7
TO
2187 'case_scheduled_activity_date' => array(
2188 'title' => ts('Activity Scheduled Date'),
21dfd5f5 2189 'type' => CRM_Utils_Type::T_DATE,
9d5494f7 2190 ),
6a488035
TO
2191 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2192 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2193 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
2194 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
2195 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
9d5494f7
TO
2196 'case_activity_is_auto' => array(
2197 'title' => ts('Activity Auto-generated?'),
21dfd5f5 2198 'type' => CRM_Utils_Type::T_BOOLEAN,
9d5494f7 2199 ),
6a488035 2200 );
6a488035
TO
2201 }
2202
2203 // add custom data for case activities
2204 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2205
2206 self::$_exportableFields[$name] = $fields;
2207 }
2208 return self::$_exportableFields[$name];
2209 }
2210
2211 /**
63e9c3fd 2212 * Get the allowed profile fields for Activities.
6a488035 2213 *
a6c01b45
CW
2214 * @return array
2215 * array of activity profile Fields
6a488035 2216 */
00be9182 2217 public static function getProfileFields() {
6a488035 2218 $exportableFields = self::exportableFields('Activity');
4f79a2f5 2219 $skipFields = array(
2220 'activity_id',
2221 'activity_type',
2222 'source_contact_id',
2223 'source_contact',
2224 'activity_campaign',
2225 'activity_is_test',
2226 'is_current_revision',
2227 'activity_is_deleted',
2228 );
6a488035
TO
2229 $config = CRM_Core_Config::singleton();
2230 if (!in_array('CiviCampaign', $config->enableComponents)) {
2231 $skipFields[] = 'activity_engagement_level';
2232 }
2233
2234 foreach ($skipFields as $field) {
2235 if (isset($exportableFields[$field])) {
2236 unset($exportableFields[$field]);
2237 }
2238 }
2239
2240 // hack to use 'activity_type_id' instead of 'activity_type'
2241 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2242 unset($exportableFields['activity_status']);
2243
2244 return $exportableFields;
2245 }
2246
2247 /**
63e9c3fd
EM
2248 * This function deletes the activity record related to contact record.
2249 *
2250 * This is conditional on there being no target and assignee record
2251 * with other contacts.
6a488035 2252 *
041ab3d1
TO
2253 * @param int $contactId
2254 * ContactId.
6a488035
TO
2255 *
2256 * @return true/null
6a488035
TO
2257 */
2258 public static function cleanupActivity($contactId) {
2259 $result = NULL;
2260 if (!$contactId) {
2261 return $result;
2262 }
e7e657f0 2263 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2bf96211 2264 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
6a488035
TO
2265
2266 $transaction = new CRM_Core_Transaction();
2267
f1504541
DL
2268 // delete activity if there is no record in civicrm_activity_contact
2269 // pointing to any other contact record
2bf96211 2270 $activityContact = new CRM_Activity_DAO_ActivityContact();
2271 $activityContact->contact_id = $contactId;
2272 $activityContact->record_type_id = $sourceID;
2273 $activityContact->find();
6a488035 2274
2bf96211 2275 while ($activityContact->fetch()) {
f1504541 2276 // delete activity_contact record for the deleted contact
32ecf7bb
BS
2277 $activityContact->delete();
2278
2279 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2280 $activityContactOther->activity_id = $activityContact->activity_id;
32ecf7bb 2281
83e0a89c 2282 // delete activity only if no other contacts connected
9d5494f7 2283 if (!$activityContactOther->find(TRUE)) {
32ecf7bb
BS
2284 $activityParams = array('id' => $activityContact->activity_id);
2285 $result = self::deleteActivity($activityParams);
2286 }
2287
2288 $activityContactOther->free();
6a488035 2289 }
6a488035 2290
2bf96211 2291 $activityContact->free();
6a488035
TO
2292 $transaction->commit();
2293
2294 return $result;
2295 }
2296
2297 /**
567b2076 2298 * Does user has sufficient permission for view/edit activity record.
6a488035 2299 *
041ab3d1
TO
2300 * @param int $activityId
2301 * Activity record id.
2302 * @param int $action
2303 * Edit/view.
6a488035 2304 *
59f4c9ee 2305 * @return bool
6a488035
TO
2306 */
2307 public static function checkPermission($activityId, $action) {
2308 $allow = FALSE;
2309 if (!$activityId ||
2310 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2311 ) {
2312 return $allow;
2313 }
2314
2315 $activity = new CRM_Activity_DAO_Activity();
2316 $activity->id = $activityId;
2317 if (!$activity->find(TRUE)) {
2318 return $allow;
2319 }
2320
7808aae6 2321 // Component related permissions.
6a488035 2322 $compPermissions = array(
9d5494f7
TO
2323 'CiviCase' => array(
2324 'administer CiviCase',
6a488035
TO
2325 'access my cases and activities',
2326 'access all cases and activities',
2327 ),
2328 'CiviMail' => array('access CiviMail'),
2329 'CiviEvent' => array('access CiviEvent'),
2330 'CiviGrant' => array('access CiviGrant'),
2331 'CiviPledge' => array('access CiviPledge'),
2332 'CiviMember' => array('access CiviMember'),
2333 'CiviReport' => array('access CiviReport'),
2334 'CiviContribute' => array('access CiviContribute'),
2335 'CiviCampaign' => array('administer CiviCampaign'),
2336 );
2337
7808aae6 2338 // Return early when it is case activity.
6a488035 2339 $isCaseActivity = CRM_Case_BAO_Case::isCaseActivity($activityId);
7808aae6 2340 // Check for civicase related permission.
6a488035
TO
2341 if ($isCaseActivity) {
2342 $allow = FALSE;
2343 foreach ($compPermissions['CiviCase'] as $per) {
2344 if (CRM_Core_Permission::check($per)) {
2345 $allow = TRUE;
2346 break;
2347 }
2348 }
2349
7808aae6 2350 // Check for case specific permissions.
6a488035
TO
2351 if ($allow) {
2352 $oper = 'view';
2353 if ($action == CRM_Core_Action::UPDATE) {
2354 $oper = 'edit';
2355 }
2356 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2357 $oper,
2358 $activity->activity_type_id
2359 );
2360 }
2361
2362 return $allow;
2363 }
2364
7808aae6 2365 // First check the component permission.
6a488035
TO
2366 $sql = "
2367 SELECT component_id
2368 FROM civicrm_option_value val
2369INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2370 WHERE val.value = %2";
9d5494f7
TO
2371 $params = array(
2372 1 => array('activity_type', 'String'),
6a488035
TO
2373 2 => array($activity->activity_type_id, 'Integer'),
2374 );
2375 $componentId = CRM_Core_DAO::singleValueQuery($sql, $params);
2376
2377 if ($componentId) {
2378 $componentName = CRM_Core_Component::getComponentName($componentId);
2379 $compPermission = CRM_Utils_Array::value($componentName, $compPermissions);
2380
7808aae6 2381 // Here we are interesting in any single permission.
6a488035
TO
2382 if (is_array($compPermission)) {
2383 foreach ($compPermission as $per) {
2384 if (CRM_Core_Permission::check($per)) {
2385 $allow = TRUE;
2386 break;
2387 }
2388 }
2389 }
2390 }
2391
7808aae6 2392 // Check for this permission related to contact.
6a488035
TO
2393 $permission = CRM_Core_Permission::VIEW;
2394 if ($action == CRM_Core_Action::UPDATE) {
2395 $permission = CRM_Core_Permission::EDIT;
2396 }
2397
e7e657f0 2398 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
034500d4 2399 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2400 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2401 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2402
7808aae6 2403 // Check for source contact.
6a488035 2404 if (!$componentId || $allow) {
65ebc887 2405 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
7808aae6 2406 // Account for possibility of activity not having a source contact (as it may have been deleted).
bbd2743b 2407 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission) : TRUE;
6a488035
TO
2408 }
2409
7808aae6 2410 // Check for target and assignee contacts.
6a488035 2411 if ($allow) {
7808aae6 2412 // First check for supper permission.
6a488035
TO
2413 $supPermission = 'view all contacts';
2414 if ($action == CRM_Core_Action::UPDATE) {
2415 $supPermission = 'edit all contacts';
2416 }
2417 $allow = CRM_Core_Permission::check($supPermission);
2418
7808aae6 2419 // User might have sufficient permission, through acls.
6a488035
TO
2420 if (!$allow) {
2421 $allow = TRUE;
7808aae6 2422 // Get the target contacts.
034500d4 2423 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
6a488035
TO
2424 foreach ($targetContacts as $cnt => $contactId) {
2425 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2426 $allow = FALSE;
2427 break;
2428 }
2429 }
2430
7808aae6 2431 // Get the assignee contacts.
6a488035 2432 if ($allow) {
d7f083ac 2433 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
6a488035
TO
2434 foreach ($assigneeContacts as $cnt => $contactId) {
2435 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2436 $allow = FALSE;
2437 break;
2438 }
2439 }
2440 }
2441 }
2442 }
2443
2444 return $allow;
2445 }
2446
2447 /**
db7de9c1 2448 * Wrapper for ajax activity selector.
6a488035 2449 *
041ab3d1
TO
2450 * @param array $params
2451 * Associated array for params record id.
6a488035 2452 *
a6c01b45 2453 * @return array
db7de9c1 2454 * Associated array of contact activities
6a488035
TO
2455 */
2456 public static function getContactActivitySelector(&$params) {
7808aae6 2457 // Format the params.
9d5494f7 2458 $params['offset'] = ($params['page'] - 1) * $params['rp'];
6a488035 2459 $params['rowCount'] = $params['rp'];
9d5494f7
TO
2460 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2461 $params['caseId'] = NULL;
2462 $context = CRM_Utils_Array::value('context', $params);
e5dcfebc 2463 $showContactOverlay = !CRM_Utils_String::startsWith($context, "dashlet");
6a488035 2464
7808aae6 2465 // Get contact activities.
6a488035
TO
2466 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2467
7808aae6 2468 // Add total.
6a488035
TO
2469 $params['total'] = CRM_Activity_BAO_Activity::getActivitiesCount($params);
2470
7808aae6 2471 // Format params and add links.
6a488035
TO
2472 $contactActivities = array();
2473
2474 if (!empty($activities)) {
2475 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2476
7808aae6 2477 // Check logged in user for permission.
6a488035
TO
2478 $page = new CRM_Core_Page();
2479 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2480 $permissions = array($page->_permission);
2481 if (CRM_Core_Permission::check('delete activities')) {
2482 $permissions[] = CRM_Core_Permission::DELETE;
2483 }
2484
2485 $mask = CRM_Core_Action::mask($permissions);
2486
2487 foreach ($activities as $activityId => $values) {
7d12de7f 2488 $activity = array();
febb6506 2489 $activity['DT_RowId'] = $activityId;
7808aae6 2490 // Add class to this row if overdue.
7d12de7f
JL
2491 $activity['DT_RowClass'] = 'crm-entity';
2492 if (CRM_Utils_Date::overdue(CRM_Utils_Array::value('activity_date_time', $values))
2493 && CRM_Utils_Array::value('status_id', $values) == 1
2494 ) {
2495 $activity['DT_RowClass'] .= ' status-overdue';
2496 }
2497 else {
2498 $activity['DT_RowClass'] .= ' status-ontime';
2499 }
2500
febb6506
JL
2501 $activity['DT_RowAttr'] = array();
2502 $activity['DT_RowAttr']['data-entity'] = 'activity';
2503 $activity['DT_RowAttr']['data-id'] = $activityId;
7d12de7f
JL
2504
2505 $activity['activity_type'] = $values['activity_type'];
2506 $activity['subject'] = $values['subject'];
ad280fb6
JL
2507
2508 $activity['source_contact_name'] = '';
6a488035 2509 if ($params['contact_id'] == $values['source_contact_id']) {
7d12de7f 2510 $activity['source_contact_name'] = $values['source_contact_name'];
6a488035
TO
2511 }
2512 elseif ($values['source_contact_id']) {
e846bd8d 2513 $srcTypeImage = "";
2514 if ($showContactOverlay) {
2515 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2516 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2517 FALSE,
2518 $values['source_contact_id']);
2519 }
160db45f 2520 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System::href($values['source_contact_name'],
5a99d240 2521 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
6a488035
TO
2522 }
2523 else {
7d12de7f 2524 $activity['source_contact_name'] = '<em>n/a</em>';
6a488035
TO
2525 }
2526
ad280fb6 2527 $activity['target_contact_name'] = '';
6a488035 2528 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
7d12de7f 2529 $activity['target_contact'] = CRM_Utils_System::href($values['recipients'],
5a99d240
KJ
2530 'civicrm/mailing/report/event',
2531 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
6a488035 2532 }
a7488080 2533 elseif (!empty($values['recipients'])) {
7d12de7f 2534 $activity['target_contact_name'] = $values['recipients'];
6a488035 2535 }
9254ec4e 2536 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
7d12de7f 2537 $activity['target_contact_name'] = '';
6a488035 2538 foreach ($values['target_contact_name'] as $tcID => $tcName) {
e846bd8d 2539 $targetTypeImage = "";
ceb21ebb 2540 $targetLink = CRM_Utils_System::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
e846bd8d 2541 if ($showContactOverlay) {
2542 $targetTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2543 CRM_Contact_BAO_Contact::getContactType($tcID),
2544 FALSE,
2545 $tcID);
ceb21ebb 2546 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2547 }
2548 else {
2549 $activity['target_contact_name'] .= $targetLink;
e846bd8d 2550 }
9254ec4e 2551 }
6a488035 2552
9254ec4e 2553 if ($extraCount = $values['target_contact_counter'] - 1) {
ceb21ebb 2554 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2555 }
2556 if ($showContactOverlay) {
2557 $activity['target_contact_name'] .= "</div> ";
6a488035
TO
2558 }
2559 }
9254ec4e 2560 elseif (!$values['target_contact_name']) {
7d12de7f 2561 $activity['target_contact_name'] = '<em>n/a</em>';
9254ec4e 2562 }
6a488035 2563
ad280fb6 2564 $activity['assignee_contact_name'] = '';
6a488035 2565 if (empty($values['assignee_contact_name'])) {
7d12de7f 2566 $activity['assignee_contact_name'] = '<em>n/a</em>';
6a488035
TO
2567 }
2568 elseif (!empty($values['assignee_contact_name'])) {
2569 $count = 0;
7d12de7f 2570 $activity['assignee_contact_name'] = '';
6a488035
TO
2571 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2572 if ($acID && $count < 5) {
e846bd8d 2573 $assigneeTypeImage = "";
ceb21ebb 2574 $assigneeLink = CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
e846bd8d 2575 if ($showContactOverlay) {
2576 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2577 CRM_Contact_BAO_Contact::getContactType($acID),
2578 FALSE,
2579 $acID);
ceb21ebb 2580 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
e846bd8d 2581 }
ceb21ebb 2582 else {
2583 $activity['assignee_contact_name'] .= $assigneeLink;
2584 }
2585
6a488035
TO
2586 $count++;
2587 if ($count) {
ceb21ebb 2588 $activity['assignee_contact_name'] .= ";&nbsp;";
2589 }
2590 if ($showContactOverlay) {
2591 $activity['assignee_contact_name'] .= "</div> ";
6a488035
TO
2592 }
2593
2594 if ($count == 4) {
7d12de7f 2595 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
6a488035
TO
2596 break;
2597 }
2598 }
2599 }
2600 }
6a488035 2601
7d12de7f
JL
2602 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2603 $activity['status_id'] = $activityStatus[$values['status_id']];
6a488035
TO
2604
2605 // build links
7d12de7f 2606 $activity['links'] = '';
6a488035 2607 $accessMailingReport = FALSE;
a7488080 2608 if (!empty($values['mailingId'])) {
6a488035
TO
2609 $accessMailingReport = TRUE;
2610 }
2611
2612 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2613 CRM_Utils_Array::value('activity_type_id', $values),
2614 CRM_Utils_Array::value('source_record_id', $values),
2615 $accessMailingReport,
2616 CRM_Utils_Array::value('activity_id', $values)
2617 );
2618
2619 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2620
7d12de7f 2621 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
6a488035
TO
2622 $actionMask,
2623 array(
2624 'id' => $values['activity_id'],
2625 'cid' => $params['contact_id'],
2626 'cxt' => $context,
2627 'caseid' => CRM_Utils_Array::value('case_id', $values),
87dab4a4
AH
2628 ),
2629 ts('more'),
2630 FALSE,
2631 'activity.tab.row',
2632 'Activity',
2633 $values['activity_id']
6a488035 2634 );
97c7504f 2635
04374d9d 2636 if ($values['is_recurring_activity']) {
053eb755 2637 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
04374d9d 2638 }
7d12de7f
JL
2639
2640 array_push($contactActivities, $activity);
6a488035
TO
2641 }
2642 }
2643
7d12de7f
JL
2644 $activitiesDT = array();
2645 $activitiesDT['data'] = $contactActivities;
2646 $activitiesDT['recordsTotal'] = $params['total'];
2647 $activitiesDT['recordsFiltered'] = $params['total'];
2648
2649 return $activitiesDT;
6a488035
TO
2650 }
2651
ffd93213 2652 /**
63e9c3fd
EM
2653 * Copy custom fields and attachments from an existing activity to another.
2654 *
d3e86119 2655 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
c490a46a
CW
2656 *
2657 * @param array $params
ffd93213 2658 */
00be9182 2659 public static function copyExtendedActivityData($params) {
6a488035
TO
2660 // attach custom data to the new activity
2661 $customParams = $htmlType = array();
2662 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
2663
2664 if (!empty($customValues)) {
2665 $fieldIds = implode(', ', array_keys($customValues));
9d5494f7
TO
2666 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2667 $result = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
2668
2669 while ($result->fetch()) {
2670 $htmlType[] = $result->id;
2671 }
2672
2673 foreach ($customValues as $key => $value) {
59f4c9ee
TO
2674 if ($value !== NULL) {
2675 // CRM-10542
6a488035
TO
2676 if (in_array($key, $htmlType)) {
2677 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
2678 $customParams["custom_{$key}_-1"] = array(
2679 'name' => $fileValues[0],
2680 'path' => $fileValues[1],
2681 );
2682 }
2683 else {
2684 $customParams["custom_{$key}_-1"] = $value;
2685 }
2686 }
2687 }
5fc3ea24 2688 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
6a488035
TO
2689 $params['mainActivityId'], 'Activity'
2690 );
2691 }
2692
2693 // copy activity attachments ( if any )
2694 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2695 }
65ebc887 2696
ffd93213 2697 /**
63e9c3fd
EM
2698 * Get activity contact.
2699 *
100fef9d
CW
2700 * @param int $activityId
2701 * @param int $recordTypeID
ffd93213
EM
2702 * @param string $column
2703 *
2704 * @return null
2705 */
65ebc887 2706 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2707 $activityContact = new CRM_Activity_BAO_ActivityContact();
2708 $activityContact->activity_id = $activityId;
2709 if ($recordTypeID) {
2710 $activityContact->record_type_id = $recordTypeID;
2711 }
2712 if ($activityContact->find(TRUE)) {
b319d00a 2713 return $activityContact->$column;
65ebc887 2714 }
42d30b83
DL
2715 return NULL;
2716 }
2717
ffd93213 2718 /**
567b2076
EM
2719 * Get source contact id.
2720 *
100fef9d 2721 * @param int $activityId
ffd93213
EM
2722 *
2723 * @return null
2724 */
42d30b83
DL
2725 public static function getSourceContactID($activityId) {
2726 static $sourceID = NULL;
2727 if (!$sourceID) {
e7e657f0 2728 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
42d30b83
DL
2729 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2730 }
2731
2732 return self::getActivityContact($activityId, $sourceID);
65ebc887 2733 }
42d30b83 2734
ffd93213 2735 /**
63e9c3fd
EM
2736 * Set api filter.
2737 *
2738 * @todo Document what this is for.
2739 *
c490a46a 2740 * @param array $params
ffd93213 2741 */
00be9182 2742 public function setApiFilter(&$params) {
b53cbfbc 2743 if (!empty($params['target_contact_id'])) {
6e1bb60c
N
2744 $this->selectAdd();
2745 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2746 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2747 $obj = new CRM_Activity_BAO_ActivityContact();
2748 $params['return.target_contact_id'] = 1;
2749 $this->joinAdd($obj, 'LEFT');
2750 $this->selectAdd('civicrm_activity.*');
2751 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
2752 }
2753 }
2754
2bbb4a91 2755 /**
7808aae6 2756 * Send activity as attachment.
2bbb4a91 2757 *
2758 * @param object $activity
2759 * @param array $mailToContacts
fc110b68 2760 * @param array $params
2bbb4a91 2761 *
bc883279 2762 * @return bool
2bbb4a91 2763 */
fc110b68 2764 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
2765 if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
9f661777 2766 $clientID = CRM_Utils_Array::value('client_id', $params);
fc110b68 2767 $caseID = CRM_Utils_Array::value('case_id', $params);
2768
2bbb4a91 2769 $ics = new CRM_Activity_BAO_ICalendar($activity);
2770 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
2771 $ics->addAttachment($attachments, $mailToContacts);
2772
fc110b68 2773 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
2bbb4a91 2774 $ics->cleanup();
fc110b68 2775 return $result;
2bbb4a91 2776 }
2777 return FALSE;
2778 }
bc883279 2779
6a488035 2780}