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