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