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