Merge pull request #13480 from pradpnayak/AdvanceSearch
[civicrm-core.git] / CRM / Activity / BAO / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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 *
675 * @return array
676 * Relevant data object values of open activities
677 * @throws \CiviCRM_API3_Exception
678 */
679 public static function getActivities($params) {
680 $activities = array();
681
682 // Activity.Get API params
683 $activityParams = self::getActivityParamsForDashboardFunctions($params);
684
685 if (!empty($params['rowCount']) &&
686 $params['rowCount'] > 0
687 ) {
688 $activityParams['options']['limit'] = $params['rowCount'];
689 }
690
691 if (!empty($params['sort'])) {
692 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
693 $order = $params['sort']->orderBy();
694 }
695 elseif (trim($params['sort'])) {
696 $order = CRM_Utils_Type::escape($params['sort'], 'String');
697 }
698 }
699
700 $activityParams['options']['sort'] = empty($order) ? "activity_date_time DESC" : str_replace('activity_type ', 'activity_type_id.label ', $order);
701
702 $activityParams['return'] = [
703 'activity_date_time',
704 'source_record_id',
705 'source_contact_id',
706 'source_contact_name',
707 'assignee_contact_id',
708 'target_contact_id',
709 'target_contact_name',
710 'assignee_contact_name',
711 'status_id',
712 'subject',
713 'activity_type_id',
714 'activity_type',
715 'case_id',
716 'campaign_id',
717 ];
718 foreach (['case_id' => 'CiviCase', 'campaign_id' => 'CiviCampaign'] as $attr => $component) {
719 if (in_array($component, self::activityComponents())) {
720 $activityParams['return'][] = $attr;
721 }
722 }
723 $result = civicrm_api3('Activity', 'Get', $activityParams);
724
725 $bulkActivityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
726 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
727
728 // CRM-3553, need to check user has access to target groups.
729 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
730 $accessCiviMail = ((CRM_Core_Permission::check('access CiviMail')) ||
731 (CRM_Mailing_Info::workflowEnabled() && CRM_Core_Permission::check('create mailings'))
732 );
733
734 $mappingParams = array(
735 'id' => 'activity_id',
736 'source_record_id' => 'source_record_id',
737 'activity_type_id' => 'activity_type_id',
738 'activity_date_time' => 'activity_date_time',
739 'status_id' => 'status_id',
740 'subject' => 'subject',
741 'campaign_id' => 'campaign_id',
742 'assignee_contact_name' => 'assignee_contact_name',
743 'target_contact_name' => 'target_contact_name',
744 'source_contact_id' => 'source_contact_id',
745 'source_contact_name' => 'source_contact_name',
746 'case_id' => 'case_id',
747 );
748
749 foreach ($result['values'] as $id => $activity) {
750
751 $activities[$id] = array();
752
753 $isBulkActivity = (!$bulkActivityTypeID || ($bulkActivityTypeID === $activity['activity_type_id']));
754
755 foreach ($mappingParams as $apiKey => $expectedName) {
756 if (in_array($apiKey, array('assignee_contact_name', 'target_contact_name'))) {
757 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity, array());
758 if ($apiKey == 'target_contact_name' && count($activity['target_contact_name'])) {
759 $activities[$id]['target_contact_counter'] = count($activity['target_contact_name']);
760 }
761
762 if ($isBulkActivity) {
763 $activities[$id]['recipients'] = ts('(%1 recipients)', array(1 => count($activity['target_contact_name'])));
764 $activities[$id]['mailingId'] = FALSE;
765 if ($accessCiviMail &&
766 ($mailingIDs === TRUE || in_array($activity['source_record_id'], $mailingIDs))
767 ) {
768 $activities[$id]['mailingId'] = TRUE;
769 }
770 }
771 }
772 // case related fields
773 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
774 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity);
775
776 // fetch case subject for case ID found
777 if (!empty($activity['case_id'])) {
778 $activities[$id]['case_subject'] = CRM_Core_DAO::executeQuery('CRM_Case_DAO_Case', $activity['case_id'], 'subject');
779 }
780 }
781 else {
782 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity);
783 if ($apiKey == 'activity_type_id') {
784 $activities[$id]['activity_type'] = CRM_Core_PseudoConstant::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $activities[$id][$expectedName]);
785 }
786 elseif ($apiKey == 'campaign_id') {
787 $activities[$id]['campaign'] = CRM_Utils_Array::value($activities[$id][$expectedName], $allCampaigns);
788 }
789 }
790 }
791 // if deleted, wrap in <del>
792 if (!empty($activity['source_contact_id']) &&
793 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
794 ) {
795 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
796 }
797 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getParentFor($id, 'civicrm_activity');
798 }
799
800 return $activities;
801 }
802
803 /**
804 * Filter the activity types to only return the ones we actually asked for
805 * Uses params['activity_type_id'] and params['activity_type_exclude_id']
806 *
807 * @param $params
808 * @return array|null (Use in Activity.get API activity_type_id)
809 */
810 public static function filterActivityTypes($params) {
811 $activityTypes = array();
812
813 // If no activity types are specified, get all the active ones
814 if (empty($params['activity_type_id'])) {
815 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'get');
816 }
817
818 // If no activity types are specified or excluded, return the list of all active ones
819 if (empty($params['activity_type_id']) && empty($params['activity_type_exclude_id'])) {
820 if (!empty($activityTypes)) {
821 return array('IN' => array_keys($activityTypes));
822 }
823 return NULL;
824 }
825
826 // If we have specified activity types, build a list to return, excluding the ones we don't want.
827 if (!empty($params['activity_type_id'])) {
828 if (!is_array($params['activity_type_id'])) {
829 // Turn it into array if only one specified, so we don't duplicate processing below
830 $params['activity_type_id'] = array($params['activity_type_id'] => $params['activity_type_id']);
831 }
832 foreach ($params['activity_type_id'] as $value) {
833 // Add each activity type that was specified to list
834 $value = CRM_Utils_Type::escape($value, 'Positive');
835 $activityTypes[$value] = $value;
836 }
837 }
838
839 // Build the list of activity types to exclude (from $params['activity_type_exclude_id'])
840 if (!empty($params['activity_type_exclude_id'])) {
841 if (!is_array($params['activity_type_exclude_id'])) {
842 // Turn it into array if only one specified, so we don't duplicate processing below
843 $params['activity_type_exclude_id'] = array($params['activity_type_exclude_id'] => $params['activity_type_exclude_id']);
844 }
845 foreach ($params['activity_type_exclude_id'] as $value) {
846 // Remove each activity type from list if it should be excluded
847 $value = CRM_Utils_Type::escape($value, 'Positive');
848 if (array_key_exists($value, $activityTypes)) {
849 unset($activityTypes[$value]);
850 }
851 }
852 }
853
854 return array('IN' => array_keys($activityTypes));
855 }
856
857 /**
858 * Get the list Activities.
859 *
860 * @deprecated
861 *
862 * @todo - use the api for this - this is working but have temporarily backed out
863 * due to performance issue to be resolved - CRM-20481.
864 *
865 * @param array $input
866 * Array of parameters.
867 * Keys include
868 * - contact_id int contact_id whose activities we want to retrieve
869 * - offset int which row to start from ?
870 * - rowCount int how many rows to fetch
871 * - sort object|array object or array describing sort order for sql query.
872 * - admin boolean if contact is admin
873 * - caseId int case ID
874 * - context string page on which selector is build
875 * - activity_type_id int|string the activitiy types we want to restrict by
876 *
877 * @return array
878 * Relevant data object values of open activities
879 */
880 public static function deprecatedGetActivities($input) {
881 // Step 1: Get the basic activity data.
882 $bulkActivityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
883 'activity_type_id',
884 'Bulk Email'
885 );
886
887 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
888 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
889 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
890 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
891
892 $config = CRM_Core_Config::singleton();
893
894 $activityTempTable = CRM_Utils_SQL_TempTable::build()->setCategory('actdetail')->getName();
895
896 $tableFields = array(
897 'activity_id' => 'int unsigned',
898 'activity_date_time' => 'datetime',
899 'source_record_id' => 'int unsigned',
900 'status_id' => 'int unsigned',
901 'subject' => 'varchar(255)',
902 'source_contact_name' => 'varchar(255)',
903 'activity_type_id' => 'int unsigned',
904 'activity_type' => 'varchar(128)',
905 'case_id' => 'int unsigned',
906 'case_subject' => 'varchar(255)',
907 'campaign_id' => 'int unsigned',
908 );
909
910 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
911 $insertValueSQL = $selectColumns = array();
912 // The activityTempTable contains the sorted rows
913 // so in order to maintain the sort order as-is we add an auto_increment
914 // field; we can sort by this later to ensure the sort order stays correct.
915 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
916 foreach ($tableFields as $name => $desc) {
917 $sql .= "$name $desc,\n";
918 $insertValueSQL[] = $name;
919 if ($name == 'source_contact_name' && CRM_Utils_SQL::supportsFullGroupBy()) {
920 $selectColumns[] = "ANY_VALUE(tbl.$name)";
921 }
922 else {
923 $selectColumns[] = "tbl.$name";
924 }
925 }
926
927 // add unique key on activity_id just to be sure
928 // this cannot be primary key because we need that for the auto_increment
929 // fixed_sort_order field
930 $sql .= "
931 UNIQUE KEY ( activity_id )
932 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
933 ";
934
935 CRM_Core_DAO::executeQuery($sql);
936
937 $insertSQL = "INSERT IGNORE INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
938
939 $order = $limit = $groupBy = '';
940 $groupBy = " GROUP BY tbl.activity_id, tbl.activity_type, tbl.case_id, tbl.case_subject ";
941
942 if (!empty($input['sort'])) {
943 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
944 $orderBy = $input['sort']->orderBy();
945 if (!empty($orderBy)) {
946 $order = " ORDER BY $orderBy";
947 }
948 }
949 elseif (trim($input['sort'])) {
950 $sort = CRM_Utils_Type::escape($input['sort'], 'String');
951 $order = " ORDER BY $sort ";
952 }
953 }
954
955 if (empty($order)) {
956 // context = 'activity' in Activities tab.
957 $order = " ORDER BY tbl.activity_date_time desc ";
958 }
959
960 if (!empty($input['rowCount']) &&
961 $input['rowCount'] > 0
962 ) {
963 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
964 }
965
966 $input['count'] = FALSE;
967 list($sqlClause, $params) = self::deprecatedGetActivitySQLClause($input);
968
969 $query = sprintf("{$insertSQL} \n SELECT DISTINCT %s from ( %s ) \n as tbl ", implode(', ', $selectColumns), $sqlClause);
970
971 // Filter case activities - CRM-5761.
972 $components = self::activityComponents();
973 if (!in_array('CiviCase', $components)) {
974 $query .= "
975 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
976 WHERE civicrm_case_activity.id IS NULL";
977 }
978
979 $query = $query . $groupBy . $order . $limit;
980
981 $dao = CRM_Core_DAO::executeQuery($query, $params);
982
983 // step 2: Get target and assignee contacts for above activities
984 // create temp table for target contacts
985 $activityContactTempTable = CRM_Utils_SQL_TempTable::build()->setCategory('actcontact')->getName();
986 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
987 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
988 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
989 ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
990
991 CRM_Core_DAO::executeQuery($query);
992
993 // note that we ignore bulk email for targets, since we don't show it in selector
994 $query = "
995 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
996 SELECT ac.activity_id,
997 ac.contact_id,
998 ac.record_type_id,
999 c.sort_name,
1000 c.is_deleted
1001 FROM {$activityTempTable}
1002 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1003 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1004 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1005 WHERE ac.record_type_id != %1
1006 ";
1007 $params = array(1 => array($targetID, 'Integer'));
1008 CRM_Core_DAO::executeQuery($query, $params);
1009
1010 $activityFields = array("ac.activity_id", "ac.contact_id", "ac.record_type_id", "c.sort_name", "c.is_deleted");
1011 $select = CRM_Contact_BAO_Query::appendAnyValueToSelect($activityFields, "ac.activity_id");
1012
1013 // for each activity insert one target contact
1014 // if we load all target contacts the performance will suffer a lot for mass-activities.
1015 $query = "
1016 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
1017 {$select}, count(ac.contact_id)
1018 FROM {$activityTempTable}
1019 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1020 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1021 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1022 WHERE ac.record_type_id = %1
1023 GROUP BY ac.activity_id
1024 ";
1025
1026 CRM_Core_DAO::executeQuery($query, $params);
1027
1028 // step 3: Combine all temp tables to get final query for activity selector
1029 // sort by the original sort order, stored in fixed_sort_order
1030 $query = "
1031 SELECT {$activityTempTable}.*,
1032 {$activityContactTempTable}.contact_id,
1033 {$activityContactTempTable}.record_type_id,
1034 {$activityContactTempTable}.contact_name,
1035 {$activityContactTempTable}.is_deleted,
1036 {$activityContactTempTable}.counter,
1037 re.parent_id as is_recurring_activity
1038 FROM {$activityTempTable}
1039 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
1040 LEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id
1041 ORDER BY fixed_sort_order
1042 ";
1043
1044 $dao = CRM_Core_DAO::executeQuery($query);
1045
1046 // CRM-3553, need to check user has access to target groups.
1047 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
1048 $accessCiviMail = (
1049 (CRM_Core_Permission::check('access CiviMail')) ||
1050 (CRM_Mailing_Info::workflowEnabled() &&
1051 CRM_Core_Permission::check('create mailings'))
1052 );
1053
1054 // Get all campaigns.
1055 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
1056 $values = array();
1057 while ($dao->fetch()) {
1058 $activityID = $dao->activity_id;
1059 $values[$activityID]['activity_id'] = $dao->activity_id;
1060 $values[$activityID]['source_record_id'] = $dao->source_record_id;
1061 $values[$activityID]['activity_type_id'] = $dao->activity_type_id;
1062 $values[$activityID]['activity_type'] = $dao->activity_type;
1063 $values[$activityID]['activity_date_time'] = $dao->activity_date_time;
1064 $values[$activityID]['status_id'] = $dao->status_id;
1065 $values[$activityID]['subject'] = $dao->subject;
1066 $values[$activityID]['campaign_id'] = $dao->campaign_id;
1067 $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity;
1068
1069 if ($dao->campaign_id) {
1070 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id];
1071 }
1072
1073 if (empty($values[$activityID]['assignee_contact_name'])) {
1074 $values[$activityID]['assignee_contact_name'] = array();
1075 }
1076
1077 if (empty($values[$activityID]['target_contact_name'])) {
1078 $values[$activityID]['target_contact_name'] = array();
1079 $values[$activityID]['target_contact_counter'] = $dao->counter;
1080 }
1081
1082 // if deleted, wrap in <del>
1083 if ($dao->is_deleted) {
1084 $dao->contact_name = "<del>{$dao->contact_name}</del>";
1085 }
1086
1087 if ($dao->record_type_id == $sourceID && $dao->contact_id) {
1088 $values[$activityID]['source_contact_id'] = $dao->contact_id;
1089 $values[$activityID]['source_contact_name'] = $dao->contact_name;
1090 }
1091
1092 if (!$bulkActivityTypeID || ($bulkActivityTypeID != $dao->activity_type_id)) {
1093 // build array of target / assignee names
1094 if ($dao->record_type_id == $targetID && $dao->contact_id) {
1095 $values[$activityID]['target_contact_name'][$dao->contact_id] = $dao->contact_name;
1096 }
1097 if ($dao->record_type_id == $assigneeID && $dao->contact_id) {
1098 $values[$activityID]['assignee_contact_name'][$dao->contact_id] = $dao->contact_name;
1099 }
1100
1101 // case related fields
1102 $values[$activityID]['case_id'] = $dao->case_id;
1103 $values[$activityID]['case_subject'] = $dao->case_subject;
1104 }
1105 else {
1106 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter));
1107 $values[$activityID]['mailingId'] = FALSE;
1108 if (
1109 $accessCiviMail &&
1110 ($mailingIDs === TRUE || in_array($dao->source_record_id, $mailingIDs))
1111 ) {
1112 $values[$activityID]['mailingId'] = TRUE;
1113 }
1114 }
1115 }
1116
1117 return $values;
1118 }
1119
1120 /**
1121 * @inheritDoc
1122 */
1123 public function addSelectWhereClause() {
1124 $clauses = parent::addSelectWhereClause();
1125 if (!CRM_Core_Permission::check('view all activities')) {
1126 $permittedActivityTypeIDs = self::getPermittedActivityTypes();
1127 if (empty($permittedActivityTypeIDs)) {
1128 // This just prevents a mysql fail if they have no access - should be extremely edge case.
1129 $permittedActivityTypeIDs = [0];
1130 }
1131 $clauses['activity_type_id'] = ('IN (' . implode(', ', $permittedActivityTypeIDs) . ')');
1132 }
1133 return $clauses;
1134 }
1135
1136 /**
1137 * Get an array of components that are accessible by the currenct user.
1138 *
1139 * This means checking if they are enabled and if the user has appropriate permission.
1140 *
1141 * For most components the permission is access component (e.g 'access CiviContribute').
1142 * Exceptions as CiviCampaign (administer CiviCampaign) and CiviCase
1143 * (accesses a case function which enforces edit all cases or edit my cases. Case
1144 * permissions are also handled on a per activity basis).
1145 *
1146 * Checks whether logged in user has permission to the component.
1147 *
1148 * @param bool $excludeComponentHandledActivities
1149 * Should we exclude components whose display is handled in the components.
1150 * In practice this means should we include CiviCase in the results. Presumbaly
1151 * at the time it was decided case activities should be shown in the case framework and
1152 * that this concept might be extended later. In practice most places that
1153 * call this then re-add CiviCase in some way so it's all a bit... odd.
1154 *
1155 * @return array Array of component id and name.
1156 * Array of component id and name.
1157 */
1158 public static function activityComponents($excludeComponentHandledActivities = TRUE) {
1159 $components = array();
1160 $compInfo = CRM_Core_Component::getEnabledComponents();
1161 foreach ($compInfo as $compObj) {
1162 $includeComponent = !$excludeComponentHandledActivities || !empty($compObj->info['showActivitiesInCore']);
1163 if ($includeComponent) {
1164 if ($compObj->info['name'] == 'CiviCampaign') {
1165 $componentPermission = "administer {$compObj->name}";
1166 }
1167 else {
1168 $componentPermission = "access {$compObj->name}";
1169 }
1170 if ($compObj->info['name'] == 'CiviCase') {
1171 if (CRM_Case_BAO_Case::accessCiviCase()) {
1172 $components[$compObj->componentID] = $compObj->info['name'];
1173 }
1174 }
1175 elseif (CRM_Core_Permission::check($componentPermission)) {
1176 $components[$compObj->componentID] = $compObj->info['name'];
1177 }
1178 }
1179 }
1180
1181 return $components;
1182 }
1183
1184 /**
1185 * Get the activity Count.
1186 *
1187 * @param array $input
1188 * Array of parameters.
1189 * Keys include
1190 * - contact_id int contact_id whose activities we want to retrieve
1191 * - admin boolean if contact is admin
1192 * - caseId int case ID
1193 * - context string page on which selector is build
1194 * - activity_type_id int|string the activity types we want to restrict by
1195 *
1196 * @return int
1197 * count of activities
1198 */
1199 public static function getActivitiesCount($input) {
1200 $activityParams = self::getActivityParamsForDashboardFunctions($input);
1201 return civicrm_api3('Activity', 'getcount', $activityParams);
1202 }
1203
1204 /**
1205 * Get the activity Count.
1206 *
1207 * @deprecated
1208 *
1209 * @param array $input
1210 * Array of parameters.
1211 * Keys include
1212 * - contact_id int contact_id whose activities we want to retrieve
1213 * - admin boolean if contact is admin
1214 * - caseId int case ID
1215 * - context string page on which selector is build
1216 * - activity_type_id int|string the activity types we want to restrict by
1217 *
1218 * @return int
1219 * count of activities
1220 */
1221 public static function deprecatedGetActivitiesCount($input) {
1222 $input['count'] = TRUE;
1223 list($sqlClause, $params) = self::deprecatedGetActivitySQLClause($input);
1224
1225 //filter case activities - CRM-5761
1226 $components = self::activityComponents();
1227 if (!in_array('CiviCase', $components)) {
1228 $query = "
1229 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
1230 FROM ( {$sqlClause} ) as tbl
1231 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
1232 WHERE civicrm_case_activity.id IS NULL";
1233 }
1234 else {
1235 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
1236 }
1237
1238 return CRM_Core_DAO::singleValueQuery($query, $params);
1239 }
1240
1241 /**
1242 * Get the activity sql clause to pick activities.
1243 *
1244 * @deprecated
1245 *
1246 * @param array $input
1247 * Array of parameters.
1248 * Keys include
1249 * - contact_id int contact_id whose activities we want to retrieve
1250 * - admin boolean if contact is admin
1251 * - caseId int case ID
1252 * - context string page on which selector is build
1253 * - count boolean are we interested in the count clause only?
1254 * - activity_type_id int|string the activity types we want to restrict by
1255 *
1256 * @return int
1257 * count of activities
1258 */
1259 public static function deprecatedGetActivitySQLClause($input) {
1260 $params = array();
1261 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1262
1263 $config = CRM_Core_Config::singleton();
1264 if (!CRM_Utils_Array::value('admin', $input, FALSE)) {
1265 $sourceWhere = ' ac.contact_id = %1 ';
1266 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1267
1268 $params = array(1 => array($input['contact_id'], 'Integer'));
1269 }
1270
1271 $commonClauses = array(
1272 "civicrm_option_group.name = 'activity_type'",
1273 "civicrm_activity.is_deleted = 0",
1274 "civicrm_activity.is_current_revision = 1",
1275 "civicrm_activity.is_test= 0",
1276 );
1277
1278 if (isset($input['activity_date_relative']) ||
1279 (!empty($input['activity_date_low']) || !empty($input['activity_date_high']))
1280 ) {
1281 list($from, $to) = CRM_Utils_Date::getFromTo(
1282 CRM_Utils_Array::value('activity_date_relative', $input, 0),
1283 CRM_Utils_Array::value('activity_date_low', $input),
1284 CRM_Utils_Array::value('activity_date_high', $input)
1285 );
1286 $commonClauses[] = sprintf('civicrm_activity.activity_date_time BETWEEN "%s" AND "%s" ', $from, $to);
1287 }
1288
1289 if (!empty($input['activity_status_id'])) {
1290 $commonClauses[] = sprintf("civicrm_activity.status_id IN (%s)", $input['activity_status_id']);
1291 }
1292
1293 // Filter on component IDs.
1294 $components = self::activityComponents();
1295 if (!empty($components)) {
1296 $componentsIn = implode(',', array_keys($components));
1297 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1298 }
1299 else {
1300 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1301 }
1302
1303 // activity type ID clause
1304 if (!empty($input['activity_type_id'])) {
1305 if (is_array($input['activity_type_id'])) {
1306 foreach ($input['activity_type_id'] as $idx => $value) {
1307 $input['activity_type_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1308 }
1309 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1310 }
1311 else {
1312 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_id'], 'Positive');
1313 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1314 }
1315 }
1316
1317 // exclude by activity type clause
1318 if (!empty($input['activity_type_exclude_id'])) {
1319 if (is_array($input['activity_type_exclude_id'])) {
1320 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1321 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1322 }
1323 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1324 }
1325 else {
1326 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_exclude_id'], 'Positive');
1327 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1328 }
1329 }
1330
1331 $commonClause = implode(' AND ', $commonClauses);
1332
1333 $includeCaseActivities = FALSE;
1334 if (in_array('CiviCase', $components)) {
1335 $includeCaseActivities = TRUE;
1336 }
1337
1338 // build main activity table select clause
1339 $sourceSelect = '';
1340
1341 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1342 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1343 $sourceJoin = "
1344 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1345 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1346 ";
1347
1348 if (!$input['count']) {
1349 $sourceSelect = ',
1350 civicrm_activity.activity_date_time,
1351 civicrm_activity.source_record_id,
1352 civicrm_activity.status_id,
1353 civicrm_activity.subject,
1354 contact.sort_name as source_contact_name,
1355 civicrm_option_value.value as activity_type_id,
1356 civicrm_option_value.label as activity_type,
1357 null as case_id, null as case_subject,
1358 civicrm_activity.campaign_id as campaign_id
1359 ';
1360
1361 $sourceJoin .= "
1362 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)
1363 ";
1364 }
1365
1366 $sourceClause = "
1367 SELECT civicrm_activity.id as activity_id
1368 {$sourceSelect}
1369 from civicrm_activity
1370 left join civicrm_option_value on
1371 civicrm_activity.activity_type_id = civicrm_option_value.value
1372 left join civicrm_option_group on
1373 civicrm_option_group.id = civicrm_option_value.option_group_id
1374 {$sourceJoin}
1375 where
1376 {$sourceWhere}
1377 AND $commonClause
1378 ";
1379
1380 // Build case clause
1381 // or else exclude Inbound Emails that have been filed on a case.
1382 $caseClause = '';
1383
1384 if ($includeCaseActivities) {
1385 $caseSelect = '';
1386 if (!$input['count']) {
1387 $caseSelect = ',
1388 civicrm_activity.activity_date_time,
1389 civicrm_activity.source_record_id,
1390 civicrm_activity.status_id,
1391 civicrm_activity.subject,
1392 contact.sort_name as source_contact_name,
1393 civicrm_option_value.value as activity_type_id,
1394 civicrm_option_value.label as activity_type,
1395 null as case_id, null as case_subject,
1396 civicrm_activity.campaign_id as campaign_id';
1397 }
1398
1399 $caseClause = "
1400 union all
1401
1402 SELECT civicrm_activity.id as activity_id
1403 {$caseSelect}
1404 from civicrm_activity
1405 inner join civicrm_case_activity on
1406 civicrm_case_activity.activity_id = civicrm_activity.id
1407 inner join civicrm_case on
1408 civicrm_case_activity.case_id = civicrm_case.id
1409 inner join civicrm_case_contact on
1410 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1411 left join civicrm_option_value on
1412 civicrm_activity.activity_type_id = civicrm_option_value.value
1413 left join civicrm_option_group on
1414 civicrm_option_group.id = civicrm_option_value.option_group_id
1415 {$sourceJoin}
1416 where
1417 {$caseWhere}
1418 AND $commonClause
1419 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1420 ( civicrm_option_value.name <> 'Inbound Email' AND
1421 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1422 IS NOT NULL )
1423 )
1424 ";
1425 }
1426
1427 $returnClause = " {$sourceClause} {$caseClause} ";
1428
1429 return array($returnClause, $params);
1430 }
1431
1432 /**
1433 * Send the message to all the contacts.
1434 *
1435 * Also insert a contact activity in each contacts record.
1436 *
1437 * @param array $contactDetails
1438 * The array of contact details to send the email.
1439 * @param string $subject
1440 * The subject of the message.
1441 * @param $text
1442 * @param $html
1443 * @param string $emailAddress
1444 * Use this 'to' email address instead of the default Primary address.
1445 * @param int $userID
1446 * Use this userID if set.
1447 * @param string $from
1448 * @param array $attachments
1449 * The array of attachments if any.
1450 * @param string $cc
1451 * Cc recipient.
1452 * @param string $bcc
1453 * Bcc recipient.
1454 * @param array $contactIds
1455 * Contact ids.
1456 * @param string $additionalDetails
1457 * The additional information of CC and BCC appended to the activity Details.
1458 * @param array $contributionIds
1459 * @param int $campaignId
1460 *
1461 * @return array
1462 * ( sent, activityId) if any email is sent and activityId
1463 */
1464 public static function sendEmail(
1465 &$contactDetails,
1466 &$subject,
1467 &$text,
1468 &$html,
1469 $emailAddress,
1470 $userID = NULL,
1471 $from = NULL,
1472 $attachments = NULL,
1473 $cc = NULL,
1474 $bcc = NULL,
1475 $contactIds = NULL,
1476 $additionalDetails = NULL,
1477 $contributionIds = NULL,
1478 $campaignId = NULL
1479 ) {
1480 // get the contact details of logged in contact, which we set as from email
1481 if ($userID == NULL) {
1482 $userID = CRM_Core_Session::getLoggedInContactID();
1483 }
1484
1485 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1486 if (!$fromEmail) {
1487 return array(count($contactDetails), 0, count($contactDetails));
1488 }
1489 if (!trim($fromDisplayName)) {
1490 $fromDisplayName = $fromEmail;
1491 }
1492
1493 // CRM-4575
1494 // token replacement of addressee/email/postal greetings
1495 // get the tokens added in subject and message
1496 $subjectToken = CRM_Utils_Token::getTokens($subject);
1497 $messageToken = CRM_Utils_Token::getTokens($text);
1498 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1499 $allTokens = array_merge($messageToken, $subjectToken);
1500
1501 if (!$from) {
1502 $from = "$fromDisplayName <$fromEmail>";
1503 }
1504
1505 //create the meta level record first ( email activity )
1506 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email');
1507
1508 // CRM-6265: save both text and HTML parts in details (if present)
1509 if ($html and $text) {
1510 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1511 }
1512 else {
1513 $details = $html ? $html : $text;
1514 $details .= $additionalDetails;
1515 }
1516
1517 $activityParams = array(
1518 'source_contact_id' => $userID,
1519 'activity_type_id' => $activityTypeID,
1520 'activity_date_time' => date('YmdHis'),
1521 'subject' => $subject,
1522 'details' => $details,
1523 // FIXME: check for name Completed and get ID from that lookup
1524 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1525 'campaign_id' => $campaignId,
1526 );
1527
1528 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1529 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1530
1531 // add the attachments to activity params here
1532 if ($attachments) {
1533 // first process them
1534 $activityParams = array_merge($activityParams,
1535 $attachments
1536 );
1537 }
1538
1539 $activity = self::create($activityParams);
1540
1541 // get the set of attachments from where they are stored
1542 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity',
1543 $activity->id
1544 );
1545 $returnProperties = array();
1546 if (isset($messageToken['contact'])) {
1547 foreach ($messageToken['contact'] as $key => $value) {
1548 $returnProperties[$value] = 1;
1549 }
1550 }
1551
1552 if (isset($subjectToken['contact'])) {
1553 foreach ($subjectToken['contact'] as $key => $value) {
1554 if (!isset($returnProperties[$value])) {
1555 $returnProperties[$value] = 1;
1556 }
1557 }
1558 }
1559
1560 // get token details for contacts, call only if tokens are used
1561 $details = array();
1562 if (!empty($returnProperties) || !empty($tokens) || !empty($allTokens)) {
1563 list($details) = CRM_Utils_Token::getTokenDetails(
1564 $contactIds,
1565 $returnProperties,
1566 NULL, NULL, FALSE,
1567 $allTokens,
1568 'CRM_Activity_BAO_Activity'
1569 );
1570 }
1571
1572 // call token hook
1573 $tokens = array();
1574 CRM_Utils_Hook::tokens($tokens);
1575 $categories = array_keys($tokens);
1576
1577 $escapeSmarty = FALSE;
1578 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1579 $smarty = CRM_Core_Smarty::singleton();
1580 $escapeSmarty = TRUE;
1581 }
1582
1583 $contributionDetails = array();
1584 if (!empty($contributionIds)) {
1585 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1586 $contributionIds,
1587 $subject,
1588 $subjectToken,
1589 $text,
1590 $html,
1591 $messageToken,
1592 $escapeSmarty
1593 );
1594 }
1595
1596 $sent = $notSent = array();
1597 foreach ($contactDetails as $values) {
1598 $contactId = $values['contact_id'];
1599 $emailAddress = $values['email'];
1600
1601 if (!empty($contributionDetails)) {
1602 $subject = $contributionDetails[$contactId]['subject'];
1603 $text = $contributionDetails[$contactId]['text'];
1604 $html = $contributionDetails[$contactId]['html'];
1605 }
1606
1607 if (!empty($details) && is_array($details["{$contactId}"])) {
1608 // unset email from details since it always returns primary email address
1609 unset($details["{$contactId}"]['email']);
1610 unset($details["{$contactId}"]['email_id']);
1611 $values = array_merge($values, $details["{$contactId}"]);
1612 }
1613
1614 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1615 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1616
1617 // CRM-4539
1618 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1619 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1620 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1621 }
1622 else {
1623 $tokenText = NULL;
1624 }
1625
1626 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1627 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1628 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1629 }
1630 else {
1631 $tokenHtml = NULL;
1632 }
1633
1634 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1635 // also add the contact tokens to the template
1636 $smarty->assign_by_ref('contact', $values);
1637
1638 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1639 $tokenText = $smarty->fetch("string:$tokenText");
1640 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1641 }
1642
1643 $sent = FALSE;
1644 if (self::sendMessage(
1645 $from,
1646 $userID,
1647 $contactId,
1648 $tokenSubject,
1649 $tokenText,
1650 $tokenHtml,
1651 $emailAddress,
1652 $activity->id,
1653 $attachments,
1654 $cc,
1655 $bcc
1656 )
1657 ) {
1658 $sent = TRUE;
1659 }
1660 }
1661
1662 return array($sent, $activity->id);
1663 }
1664
1665 /**
1666 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
1667 *
1668 * @param array $contactDetails
1669 * @param array $activityParams
1670 * @param array $smsProviderParams
1671 * @param array $contactIds
1672 * @param int $sourceContactId This is the source contact Id
1673 *
1674 * @return array(bool $sent, int $activityId, int $success)
1675 * @throws CRM_Core_Exception
1676 */
1677 public static function sendSMS(
1678 &$contactDetails = NULL,
1679 &$activityParams,
1680 &$smsProviderParams = array(),
1681 &$contactIds = NULL,
1682 $sourceContactId = NULL
1683 ) {
1684 if (!CRM_Core_Permission::check('send SMS')) {
1685 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1686 }
1687
1688 if (!isset($contactDetails) && !isset($contactIds)) {
1689 Throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1690 }
1691 // Populate $contactDetails and $contactIds if only one is set
1692 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1693 foreach ($contactIds as $id) {
1694 try {
1695 $contactDetails[] = civicrm_api3('Contact', 'getsingle', array('contact_id' => $id));
1696 }
1697 catch (Exception $e) {
1698 // Contact Id doesn't exist
1699 }
1700 }
1701 }
1702 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1703 foreach ($contactDetails as $contact) {
1704 $contactIds[] = $contact['contact_id'];
1705 }
1706 }
1707
1708 // Get logged in User Id
1709 if (empty($sourceContactId)) {
1710 $sourceContactId = CRM_Core_Session::getLoggedInContactID();
1711 }
1712
1713 $text = &$activityParams['sms_text_message'];
1714
1715 // Create the meta level record first ( sms activity )
1716 $activityParams = array(
1717 'source_contact_id' => $sourceContactId,
1718 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS'),
1719 'activity_date_time' => date('YmdHis'),
1720 'subject' => $activityParams['activity_subject'],
1721 'details' => $text,
1722 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1723 );
1724 $activity = self::create($activityParams);
1725 $activityID = $activity->id;
1726
1727 // Process Tokens
1728 // token replacement of addressee/email/postal greetings
1729 // get the tokens added in subject and message
1730 $messageToken = CRM_Utils_Token::getTokens($text);
1731 $returnProperties = array();
1732 if (isset($messageToken['contact'])) {
1733 foreach ($messageToken['contact'] as $key => $value) {
1734 $returnProperties[$value] = 1;
1735 }
1736 }
1737 // Call tokens hook
1738 $tokens = array();
1739 CRM_Utils_Hook::tokens($tokens);
1740 $categories = array_keys($tokens);
1741 // get token details for contacts, call only if tokens are used
1742 $tokenDetails = array();
1743 if (!empty($returnProperties) || !empty($tokens)) {
1744 list($tokenDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
1745 $returnProperties,
1746 NULL, NULL, FALSE,
1747 $messageToken,
1748 'CRM_Activity_BAO_Activity'
1749 );
1750 }
1751
1752 $success = 0;
1753 $errMsgs = array();
1754 foreach ($contactDetails as $contact) {
1755 $contactId = $contact['contact_id'];
1756
1757 // Replace tokens
1758 if (!empty($tokenDetails) && is_array($tokenDetails["{$contactId}"])) {
1759 // unset phone from details since it always returns primary number
1760 unset($tokenDetails["{$contactId}"]['phone']);
1761 unset($tokenDetails["{$contactId}"]['phone_type_id']);
1762 $contact = array_merge($contact, $tokenDetails["{$contactId}"]);
1763 }
1764 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1765 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
1766
1767 // Only send if the phone is of type mobile
1768 if ($contact['phone_type_id'] == CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1769 $smsProviderParams['To'] = $contact['phone'];
1770 }
1771 else {
1772 $smsProviderParams['To'] = '';
1773 }
1774
1775 $doNotSms = CRM_Utils_Array::value('do_not_sms', $contact, 0);
1776
1777 if ($doNotSms) {
1778 $errMsgs[] = PEAR::raiseError('Contact Does not accept SMS', NULL, PEAR_ERROR_RETURN);
1779 }
1780 else {
1781 $sendResult = self::sendSMSMessage(
1782 $contactId,
1783 $tokenText,
1784 $smsProviderParams,
1785 $activityID,
1786 $sourceContactId
1787 );
1788
1789 if (PEAR::isError($sendResult)) {
1790 // Collect all of the PEAR_Error objects
1791 $errMsgs[] = $sendResult;
1792 }
1793 else {
1794 $success++;
1795 }
1796 }
1797 }
1798
1799 // If at least one message was sent and no errors
1800 // were generated then return a boolean value of TRUE.
1801 // Otherwise, return FALSE (no messages sent) or
1802 // and array of 1 or more PEAR_Error objects.
1803 $sent = FALSE;
1804 if ($success > 0 && count($errMsgs) == 0) {
1805 $sent = TRUE;
1806 }
1807 elseif (count($errMsgs) > 0) {
1808 $sent = $errMsgs;
1809 }
1810
1811 return array($sent, $activity->id, $success);
1812 }
1813
1814 /**
1815 * Send the sms message to a specific contact.
1816 *
1817 * @param int $toID
1818 * The contact id of the recipient.
1819 * @param $tokenText
1820 * @param array $smsProviderParams
1821 * The params used for sending sms.
1822 * @param int $activityID
1823 * The activity ID that tracks the message.
1824 * @param int $sourceContactID
1825 *
1826 * @return bool|PEAR_Error
1827 * true on success or PEAR_Error object
1828 */
1829 public static function sendSMSMessage(
1830 $toID,
1831 &$tokenText,
1832 $smsProviderParams = array(),
1833 $activityID,
1834 $sourceContactID = NULL
1835 ) {
1836 $toPhoneNumber = NULL;
1837 if ($smsProviderParams['To']) {
1838 // If phone number is specified use it
1839 $toPhoneNumber = trim($smsProviderParams['To']);
1840 }
1841 elseif ($toID) {
1842 // No phone number specified, so find a suitable one for the contact
1843 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1844 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
1845 // To get primary mobile phonenumber, if not get the first mobile phonenumber
1846 if (!empty($toPhoneNumbers)) {
1847 $toPhoneNumberDetails = reset($toPhoneNumbers);
1848 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
1849 // Contact allows to send sms
1850 }
1851 }
1852
1853 // make sure both phone are valid
1854 // and that the recipient wants to receive sms
1855 if (empty($toPhoneNumber)) {
1856 return PEAR::raiseError(
1857 'Recipient phone number is invalid or recipient does not want to receive SMS',
1858 NULL,
1859 PEAR_ERROR_RETURN
1860 );
1861 }
1862
1863 $recipient = $toPhoneNumber;
1864 $smsProviderParams['contact_id'] = $toID;
1865 $smsProviderParams['parent_activity_id'] = $activityID;
1866
1867 $providerObj = CRM_SMS_Provider::singleton(array('provider_id' => $smsProviderParams['provider_id']));
1868 $sendResult = $providerObj->send($recipient, $smsProviderParams, $tokenText, NULL, $sourceContactID);
1869 if (PEAR::isError($sendResult)) {
1870 return $sendResult;
1871 }
1872
1873 // add activity target record for every sms that is sent
1874 $targetID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
1875 $activityTargetParams = array(
1876 'activity_id' => $activityID,
1877 'contact_id' => $toID,
1878 'record_type_id' => $targetID,
1879 );
1880 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1881
1882 return TRUE;
1883 }
1884
1885 /**
1886 * Send the message to a specific contact.
1887 *
1888 * @param string $from
1889 * The name and email of the sender.
1890 * @param int $fromID
1891 * @param int $toID
1892 * The contact id of the recipient.
1893 * @param string $subject
1894 * The subject of the message.
1895 * @param $text_message
1896 * @param $html_message
1897 * @param string $emailAddress
1898 * Use this 'to' email address instead of the default Primary address.
1899 * @param int $activityID
1900 * The activity ID that tracks the message.
1901 * @param null $attachments
1902 * @param null $cc
1903 * @param null $bcc
1904 *
1905 * @return bool
1906 * TRUE if successful else FALSE.
1907 */
1908 public static function sendMessage(
1909 $from,
1910 $fromID,
1911 $toID,
1912 &$subject,
1913 &$text_message,
1914 &$html_message,
1915 $emailAddress,
1916 $activityID,
1917 $attachments = NULL,
1918 $cc = NULL,
1919 $bcc = NULL
1920 ) {
1921 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1922 if ($emailAddress) {
1923 $toEmail = trim($emailAddress);
1924 }
1925
1926 // make sure both email addresses are valid
1927 // and that the recipient wants to receive email
1928 if (empty($toEmail) or $toDoNotEmail) {
1929 return FALSE;
1930 }
1931 if (!trim($toDisplayName)) {
1932 $toDisplayName = $toEmail;
1933 }
1934
1935 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1936 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1937
1938 // create the params array
1939 $mailParams = array(
1940 'groupName' => 'Activity Email Sender',
1941 'from' => $from,
1942 'toName' => $toDisplayName,
1943 'toEmail' => $toEmail,
1944 'subject' => $subject,
1945 'cc' => $cc,
1946 'bcc' => $bcc,
1947 'text' => $text_message,
1948 'html' => $html_message,
1949 'attachments' => $attachments,
1950 );
1951
1952 if (!CRM_Utils_Mail::send($mailParams)) {
1953 return FALSE;
1954 }
1955
1956 // add activity target record for every mail that is send
1957 $activityTargetParams = array(
1958 'activity_id' => $activityID,
1959 'contact_id' => $toID,
1960 'record_type_id' => $targetID,
1961 );
1962 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1963 return TRUE;
1964 }
1965
1966 /**
1967 * Combine all the importable fields from the lower levels object.
1968 *
1969 * The ordering is important, since currently we do not have a weight
1970 * scheme. Adding weight is super important and should be done in the
1971 * next week or so, before this can be called complete.
1972 *
1973 * @param bool $status
1974 *
1975 * @return array
1976 * array of importable Fields
1977 */
1978 public static function &importableFields($status = FALSE) {
1979 if (!self::$_importableFields) {
1980 if (!self::$_importableFields) {
1981 self::$_importableFields = array();
1982 }
1983 if (!$status) {
1984 $fields = array('' => array('title' => ts('- do not import -')));
1985 }
1986 else {
1987 $fields = array('' => array('title' => ts('- Activity Fields -')));
1988 }
1989
1990 $tmpFields = CRM_Activity_DAO_Activity::import();
1991 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1992
1993 // Using new Dedupe rule.
1994 $ruleParams = array(
1995 'contact_type' => 'Individual',
1996 'used' => 'Unsupervised',
1997 );
1998 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1999
2000 $tmpConatctField = array();
2001 if (is_array($fieldsArray)) {
2002 foreach ($fieldsArray as $value) {
2003 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2004 $value,
2005 'id',
2006 'column_name'
2007 );
2008 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
2009 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
2010 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
2011 }
2012 }
2013 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
2014 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
2015 $fields = array_merge($fields, $tmpConatctField);
2016 $fields = array_merge($fields, $tmpFields);
2017 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2018 self::$_importableFields = $fields;
2019 }
2020 return self::$_importableFields;
2021 }
2022
2023 /**
2024 * @deprecated - use the api instead.
2025 *
2026 * Get the Activities of a target contact.
2027 *
2028 * @param int $contactId
2029 * Id of the contact whose activities need to find.
2030 *
2031 * @return array
2032 * array of activity fields
2033 */
2034 public static function getContactActivity($contactId) {
2035 // @todo remove this function entirely.
2036 $activities = array();
2037 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2038 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2039 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2040 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2041
2042 // First look for activities where contactId is one of the targets
2043 $query = "
2044 SELECT activity_id, record_type_id
2045 FROM civicrm_activity_contact
2046 WHERE contact_id = $contactId
2047 ";
2048 $dao = CRM_Core_DAO::executeQuery($query);
2049 while ($dao->fetch()) {
2050 if ($dao->record_type_id == $targetID) {
2051 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
2052 }
2053 elseif ($dao->record_type_id == $assigneeID) {
2054 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
2055 }
2056 else {
2057 // do source stuff here
2058 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
2059 }
2060 }
2061
2062 $activityIds = array_keys($activities);
2063 if (count($activityIds) < 1) {
2064 return array();
2065 }
2066
2067 $activityIds = implode(',', $activityIds);
2068 $query = "
2069 SELECT activity.id as activity_id,
2070 activity_type_id,
2071 subject, location, activity_date_time, details, status_id
2072 FROM civicrm_activity activity
2073 WHERE activity.id IN ($activityIds)";
2074
2075 $dao = CRM_Core_DAO::executeQuery($query);
2076
2077 while ($dao->fetch()) {
2078 $activities[$dao->activity_id]['id'] = $dao->activity_id;
2079 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
2080 $activities[$dao->activity_id]['subject'] = $dao->subject;
2081 $activities[$dao->activity_id]['location'] = $dao->location;
2082 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
2083 $activities[$dao->activity_id]['details'] = $dao->details;
2084 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
2085 $activities[$dao->activity_id]['activity_name'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id);
2086 $activities[$dao->activity_id]['status'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id);
2087
2088 // set to null if not set
2089 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
2090 $activities[$dao->activity_id]['source_contact_id'] = NULL;
2091 }
2092 }
2093 return $activities;
2094 }
2095
2096 /**
2097 * Add activity for Membership/Event/Contribution.
2098 *
2099 * @param object $activity
2100 * (reference) particular component object.
2101 * @param string $activityType
2102 * For Membership Signup or Renewal.
2103 * @param int $targetContactID
2104 * @param array $params
2105 * Activity params to override.
2106 *
2107 * @return bool|NULL
2108 */
2109 public static function addActivity(
2110 &$activity,
2111 $activityType = 'Membership Signup',
2112 $targetContactID = NULL,
2113 $params = array()
2114 ) {
2115 $date = date('YmdHis');
2116 if ($activity->__table == 'civicrm_membership') {
2117 $component = 'Membership';
2118 }
2119 elseif ($activity->__table == 'civicrm_participant') {
2120 if ($activityType != 'Email') {
2121 $activityType = 'Event Registration';
2122 }
2123 $component = 'Event';
2124 }
2125 elseif ($activity->__table == 'civicrm_contribution') {
2126 // create activity record only for Completed Contributions
2127 $contributionCompletedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
2128 if ($activity->contribution_status_id != $contributionCompletedStatusId) {
2129 return NULL;
2130 }
2131 $activityType = $component = 'Contribution';
2132
2133 // retrieve existing activity based on source_record_id and activity_type
2134 if (empty($params['id'])) {
2135 $params['id'] = CRM_Utils_Array::value('id', civicrm_api3('Activity', 'Get', array(
2136 'source_record_id' => $activity->id,
2137 'activity_type_id' => $activityType,
2138 )));
2139 }
2140 if (!empty($params['id'])) {
2141 // CRM-13237 : if activity record found, update it with campaign id of contribution
2142 $params['campaign_id'] = $activity->campaign_id;
2143 }
2144
2145 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
2146 }
2147
2148 $activityParams = array(
2149 'source_contact_id' => $activity->contact_id,
2150 'source_record_id' => $activity->id,
2151 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
2152 'activity_date_time' => $date,
2153 'is_test' => $activity->is_test,
2154 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
2155 'skipRecentView' => TRUE,
2156 'campaign_id' => $activity->campaign_id,
2157 );
2158 $activityParams = array_merge($activityParams, $params);
2159
2160 if (empty($activityParams['subject'])) {
2161 $activityParams['subject'] = self::getActivitySubject($activity);
2162 }
2163
2164 if (!empty($activity->activity_id)) {
2165 $activityParams['id'] = $activity->activity_id;
2166 }
2167 // create activity with target contacts
2168 $id = CRM_Core_Session::getLoggedInContactID();
2169 if ($id) {
2170 $activityParams['source_contact_id'] = $id;
2171 $activityParams['target_contact_id'][] = $activity->contact_id;
2172 }
2173
2174 // CRM-14945
2175 if (property_exists($activity, 'details')) {
2176 $activityParams['details'] = $activity->details;
2177 }
2178 //CRM-4027
2179 if ($targetContactID) {
2180 $activityParams['target_contact_id'][] = $targetContactID;
2181 }
2182 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
2183 // deal with any exceptions.
2184 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
2185 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
2186 return FALSE;
2187 }
2188 }
2189
2190 /**
2191 * Get activity subject on basis of component object.
2192 *
2193 * @param object $entityObj
2194 * particular component object.
2195 *
2196 * @return string
2197 */
2198 public static function getActivitySubject($entityObj) {
2199 switch ($entityObj->__table) {
2200 case 'civicrm_membership':
2201 $membershipType = CRM_Member_PseudoConstant::membershipType($entityObj->membership_type_id);
2202 $subject = $membershipType ? $membershipType : ts('Membership');
2203
2204 if (is_array($subject)) {
2205 $subject = implode(", ", $subject);
2206 }
2207
2208 if (!CRM_Utils_System::isNull($entityObj->source)) {
2209 $subject .= " - {$entityObj->source}";
2210 }
2211
2212 if ($entityObj->owner_membership_id) {
2213 list($displayName) = CRM_Contact_BAO_Contact::getDisplayAndImage(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id, 'contact_id'));
2214 $subject .= sprintf(' (by %s)', $displayName);
2215 }
2216
2217 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $entityObj->status_id, 'label');
2218 return $subject;
2219
2220 case 'civicrm_participant':
2221 $event = CRM_Event_BAO_Event::getEvents(1, $entityObj->event_id, TRUE, FALSE);
2222 $roles = CRM_Event_PseudoConstant::participantRole();
2223 $status = CRM_Event_PseudoConstant::participantStatus();
2224 $subject = $event[$entityObj->event_id];
2225
2226 if (!empty($roles[$entityObj->role_id])) {
2227 $subject .= ' - ' . $roles[$entityObj->role_id];
2228 }
2229 if (!empty($status[$entityObj->status_id])) {
2230 $subject .= ' - ' . $status[$entityObj->status_id];
2231 }
2232
2233 return $subject;
2234
2235 case 'civicrm_contribution':
2236 $subject = CRM_Utils_Money::format($entityObj->total_amount, $entityObj->currency);
2237 if (!CRM_Utils_System::isNull($entityObj->source)) {
2238 $subject .= " - {$entityObj->source}";
2239 }
2240
2241 // Amount and source could exceed max length of subject column.
2242 return CRM_Utils_String::ellipsify($subject, 255);
2243 }
2244 }
2245
2246 /**
2247 * Get Parent activity for currently viewed activity.
2248 *
2249 * @param int $activityId
2250 * Current activity id.
2251 *
2252 * @return int
2253 * Id of parent activity otherwise false.
2254 */
2255 public static function getParentActivity($activityId) {
2256 static $parentActivities = array();
2257
2258 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
2259
2260 if (!array_key_exists($activityId, $parentActivities)) {
2261 $parentActivities[$activityId] = array();
2262
2263 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2264 $activityId,
2265 'parent_id'
2266 );
2267
2268 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
2269 }
2270
2271 return $parentActivities[$activityId];
2272 }
2273
2274 /**
2275 * Get total count of prior revision of currently viewed activity.
2276 *
2277 * @param $activityID
2278 * Current activity id.
2279 *
2280 * @return int
2281 * $params count of prior activities otherwise false.
2282 */
2283 public static function getPriorCount($activityID) {
2284 static $priorCounts = array();
2285
2286 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2287
2288 if (!array_key_exists($activityID, $priorCounts)) {
2289 $priorCounts[$activityID] = array();
2290 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2291 $activityID,
2292 'original_id'
2293 );
2294 $count = 0;
2295 if ($originalID) {
2296 $query = "
2297 SELECT count( id ) AS cnt
2298 FROM civicrm_activity
2299 WHERE ( id = {$originalID} OR original_id = {$originalID} )
2300 AND is_current_revision = 0
2301 AND id < {$activityID}
2302 ";
2303 $params = array(1 => array($originalID, 'Integer'));
2304 $count = CRM_Core_DAO::singleValueQuery($query, $params);
2305 }
2306 $priorCounts[$activityID] = $count ? $count : 0;
2307 }
2308
2309 return $priorCounts[$activityID];
2310 }
2311
2312 /**
2313 * Get all prior activities of currently viewed activity.
2314 *
2315 * @param $activityID
2316 * Current activity id.
2317 * @param bool $onlyPriorRevisions
2318 *
2319 * @return array
2320 * prior activities info.
2321 */
2322 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
2323 static $priorActivities = array();
2324
2325 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2326 $index = $activityID . '_' . (int) $onlyPriorRevisions;
2327
2328 if (!array_key_exists($index, $priorActivities)) {
2329 $priorActivities[$index] = array();
2330
2331 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2332 $activityID,
2333 'original_id'
2334 );
2335 if (!$originalID) {
2336 $originalID = $activityID;
2337 }
2338 if ($originalID) {
2339 $query = "
2340 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2341 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2342 WHERE (ca.id = %1 OR ca.original_id = %1)
2343 AND cl.entity_table = 'civicrm_activity'
2344 AND cl.entity_id = ca.id
2345 AND cl.modified_id = c.id
2346 ";
2347 if ($onlyPriorRevisions) {
2348 $query .= " AND ca.id < {$activityID}";
2349 }
2350 $query .= " ORDER BY ca.id DESC";
2351
2352 $params = array(1 => array($originalID, 'Integer'));
2353 $dao = CRM_Core_DAO::executeQuery($query, $params);
2354
2355 while ($dao->fetch()) {
2356 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
2357 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
2358 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
2359 }
2360 $dao->free();
2361 }
2362 }
2363 return $priorActivities[$index];
2364 }
2365
2366 /**
2367 * Find the latest revision of a given activity.
2368 *
2369 * @param int $activityID
2370 * Prior activity id.
2371 *
2372 * @return int
2373 * current activity id.
2374 */
2375 public static function getLatestActivityId($activityID) {
2376 static $latestActivityIds = array();
2377
2378 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2379
2380 if (!array_key_exists($activityID, $latestActivityIds)) {
2381 $latestActivityIds[$activityID] = array();
2382
2383 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2384 $activityID,
2385 'original_id'
2386 );
2387 if ($originalID) {
2388 $activityID = $originalID;
2389 }
2390 $params = array(1 => array($activityID, 'Integer'));
2391 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2392
2393 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
2394 }
2395
2396 return $latestActivityIds[$activityID];
2397 }
2398
2399 /**
2400 * Create a follow up a given activity.
2401 *
2402 * @param int $activityId
2403 * activity id of parent activity.
2404 * @param array $params
2405 *
2406 * @return CRM_Activity_BAO_Activity|null|object
2407 */
2408 public static function createFollowupActivity($activityId, $params) {
2409 if (!$activityId) {
2410 return NULL;
2411 }
2412
2413 $followupParams = array();
2414 $followupParams['parent_id'] = $activityId;
2415 $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
2416 $followupParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2417
2418 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2419 // Get Subject of Follow-up Activiity, CRM-4491
2420 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
2421 $followupParams['assignee_contact_id'] = CRM_Utils_Array::value('followup_assignee_contact_id', $params);
2422
2423 // Create target contact for followup.
2424 if (!empty($params['target_contact_id'])) {
2425 $followupParams['target_contact_id'] = $params['target_contact_id'];
2426 }
2427
2428 $followupParams['activity_date_time'] = $params['followup_date'];
2429 $followupActivity = self::create($followupParams);
2430
2431 return $followupActivity;
2432 }
2433
2434 /**
2435 * Get Activity specific File according activity type Id.
2436 *
2437 * @param int $activityTypeId
2438 * Activity id.
2439 * @param string $crmDir
2440 *
2441 * @return string|bool
2442 * if file exists returns $activityTypeFile activity filename otherwise false.
2443 */
2444 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2445 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2446
2447 if ($activityTypes[$activityTypeId]['name']) {
2448 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2449 }
2450 else {
2451 return FALSE;
2452 }
2453
2454 global $civicrm_root;
2455 $config = CRM_Core_Config::singleton();
2456 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2457 if (empty($config->customPHPPathDir)) {
2458 return FALSE;
2459 }
2460 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2461 return FALSE;
2462 }
2463 }
2464
2465 return $activityTypeFile;
2466 }
2467
2468 /**
2469 * Restore the activity.
2470 *
2471 * @param array $params
2472 *
2473 * @return CRM_Activity_DAO_Activity
2474 */
2475 public static function restoreActivity(&$params) {
2476 $activity = new CRM_Activity_DAO_Activity();
2477 $activity->copyValues($params);
2478
2479 $activity->is_deleted = 0;
2480 $result = $activity->save();
2481
2482 return $result;
2483 }
2484
2485 /**
2486 * Return list of activity statuses of a given type.
2487 *
2488 * Note: activity status options use the "grouping" field to distinguish status types.
2489 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2490 *
2491 * @param int $type
2492 *
2493 * @return array
2494 */
2495 public static function getStatusesByType($type) {
2496 if (!isset(Civi::$statics[__CLASS__][__FUNCTION__])) {
2497 $statuses = civicrm_api3('OptionValue', 'get', array(
2498 'option_group_id' => 'activity_status',
2499 'return' => array('value', 'name', 'filter'),
2500 'options' => array('limit' => 0),
2501 ));
2502 Civi::$statics[__CLASS__][__FUNCTION__] = $statuses['values'];
2503 }
2504 $ret = array();
2505 foreach (Civi::$statics[__CLASS__][__FUNCTION__] as $status) {
2506 if ($status['filter'] == $type) {
2507 $ret[$status['value']] = $status['name'];
2508 }
2509 }
2510 return $ret;
2511 }
2512
2513 /**
2514 * Check if activity is overdue.
2515 *
2516 * @param array $activity
2517 *
2518 * @return bool
2519 */
2520 public static function isOverdue($activity) {
2521 return array_key_exists($activity['status_id'], self::getStatusesByType(self::INCOMPLETE)) && CRM_Utils_Date::overdue($activity['activity_date_time']);
2522 }
2523
2524 /**
2525 * Get the exportable fields for Activities.
2526 *
2527 * @param string $name
2528 * If it is called by case $name = Case else $name = Activity.
2529 *
2530 * @return array
2531 * array of exportable Fields
2532 */
2533 public static function exportableFields($name = 'Activity') {
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'] = [
2541 'title' => ts('Source Contact ID'),
2542 'type' => CRM_Utils_Type::T_INT,
2543 ];
2544 $exportableFields['source_contact'] = array(
2545 'title' => ts('Source Contact'),
2546 'type' => CRM_Utils_Type::T_STRING,
2547 );
2548
2549 $Activityfields = array(
2550 'activity_type' => array(
2551 'title' => ts('Activity Type'),
2552 'name' => 'activity_type',
2553 'type' => CRM_Utils_Type::T_STRING,
2554 'searchByLabel' => TRUE,
2555 ),
2556 'activity_status' => array(
2557 'title' => ts('Activity Status'),
2558 'name' => 'activity_status',
2559 'type' => CRM_Utils_Type::T_STRING,
2560 'searchByLabel' => TRUE,
2561 ),
2562 'activity_priority' => array(
2563 'title' => ts('Activity Priority'),
2564 'name' => 'activity_priority',
2565 'type' => CRM_Utils_Type::T_STRING,
2566 'searchByLabel' => TRUE,
2567 ),
2568 );
2569 $fields = array_merge($Activityfields, $exportableFields);
2570 }
2571 else {
2572 // Set title to activity fields.
2573 $fields = array(
2574 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
2575 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
2576 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
2577 'case_scheduled_activity_date' => array(
2578 'title' => ts('Activity Scheduled Date'),
2579 'type' => CRM_Utils_Type::T_DATE,
2580 ),
2581 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2582 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2583 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
2584 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
2585 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
2586 'case_activity_is_auto' => array(
2587 'title' => ts('Activity Auto-generated?'),
2588 'type' => CRM_Utils_Type::T_BOOLEAN,
2589 ),
2590 );
2591 }
2592
2593 // add custom data for case activities
2594 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2595
2596 self::$_exportableFields[$name] = $fields;
2597 return self::$_exportableFields[$name];
2598 }
2599
2600 /**
2601 * Get the allowed profile fields for Activities.
2602 *
2603 * @return array
2604 * array of activity profile Fields
2605 */
2606 public static function getProfileFields() {
2607 $exportableFields = self::exportableFields('Activity');
2608 $skipFields = array(
2609 'activity_id',
2610 'activity_type',
2611 'source_contact_id',
2612 'source_contact',
2613 'activity_campaign',
2614 'activity_is_test',
2615 'is_current_revision',
2616 'activity_is_deleted',
2617 );
2618 $config = CRM_Core_Config::singleton();
2619 if (!in_array('CiviCampaign', $config->enableComponents)) {
2620 $skipFields[] = 'activity_engagement_level';
2621 }
2622
2623 foreach ($skipFields as $field) {
2624 if (isset($exportableFields[$field])) {
2625 unset($exportableFields[$field]);
2626 }
2627 }
2628
2629 // hack to use 'activity_type_id' instead of 'activity_type'
2630 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2631 unset($exportableFields['activity_status']);
2632
2633 return $exportableFields;
2634 }
2635
2636 /**
2637 * This function deletes the activity record related to contact record.
2638 *
2639 * This is conditional on there being no target and assignee record
2640 * with other contacts.
2641 *
2642 * @param int $contactId
2643 * ContactId.
2644 *
2645 * @return true/null
2646 */
2647 public static function cleanupActivity($contactId) {
2648 $result = NULL;
2649 if (!$contactId) {
2650 return $result;
2651 }
2652 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2653 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2654
2655 $transaction = new CRM_Core_Transaction();
2656
2657 // delete activity if there is no record in civicrm_activity_contact
2658 // pointing to any other contact record
2659 $activityContact = new CRM_Activity_DAO_ActivityContact();
2660 $activityContact->contact_id = $contactId;
2661 $activityContact->record_type_id = $sourceID;
2662 $activityContact->find();
2663
2664 while ($activityContact->fetch()) {
2665 // delete activity_contact record for the deleted contact
2666 $activityContact->delete();
2667
2668 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2669 $activityContactOther->activity_id = $activityContact->activity_id;
2670
2671 // delete activity only if no other contacts connected
2672 if (!$activityContactOther->find(TRUE)) {
2673 $activityParams = array('id' => $activityContact->activity_id);
2674 $result = self::deleteActivity($activityParams);
2675 }
2676
2677 $activityContactOther->free();
2678 }
2679
2680 $activityContact->free();
2681 $transaction->commit();
2682
2683 return $result;
2684 }
2685
2686 /**
2687 * Does user has sufficient permission for view/edit activity record.
2688 *
2689 * @param int $activityId
2690 * Activity record id.
2691 * @param int $action
2692 * Edit/view.
2693 *
2694 * @return bool
2695 */
2696 public static function checkPermission($activityId, $action) {
2697
2698 if (!$activityId ||
2699 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2700 ) {
2701 return FALSE;
2702 }
2703
2704 $activity = new CRM_Activity_DAO_Activity();
2705 $activity->id = $activityId;
2706 if (!$activity->find(TRUE)) {
2707 return FALSE;
2708 }
2709
2710 if (!self::hasPermissionForActivityType($activity->activity_type_id)) {
2711 // this check is redundant for api access / anything that calls the selectWhereClause
2712 // to determine ACLs.
2713 return FALSE;
2714 }
2715 // Return early when it is case activity.
2716 // Check for CiviCase related permission.
2717 if (CRM_Case_BAO_Case::isCaseActivity($activityId)) {
2718 return self::isContactPermittedAccessToCaseActivity($activityId, $action, $activity->activity_type_id);
2719 }
2720
2721 // Check for this permission related to contact.
2722 $permission = CRM_Core_Permission::VIEW;
2723 if ($action == CRM_Core_Action::UPDATE) {
2724 $permission = CRM_Core_Permission::EDIT;
2725 }
2726
2727 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2728 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2729 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2730 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2731
2732 // Check for source contact.
2733 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2734 // Account for possibility of activity not having a source contact (as it may have been deleted).
2735 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission) : TRUE;
2736 if (!$allow) {
2737 return FALSE;
2738 }
2739
2740 // Check for target and assignee contacts.
2741 // First check for supper permission.
2742 $supPermission = 'view all contacts';
2743 if ($action == CRM_Core_Action::UPDATE) {
2744 $supPermission = 'edit all contacts';
2745 }
2746 $allow = CRM_Core_Permission::check($supPermission);
2747
2748 // User might have sufficient permission, through acls.
2749 if (!$allow) {
2750 $allow = TRUE;
2751 // Get the target contacts.
2752 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
2753 foreach ($targetContacts as $cnt => $contactId) {
2754 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2755 $allow = FALSE;
2756 break;
2757 }
2758 }
2759
2760 // Get the assignee contacts.
2761 if ($allow) {
2762 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
2763 foreach ($assigneeContacts as $cnt => $contactId) {
2764 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2765 $allow = FALSE;
2766 break;
2767 }
2768 }
2769 }
2770 }
2771
2772 return $allow;
2773 }
2774
2775 /**
2776 * Check if the logged in user has permission for the given case activity.
2777 *
2778 * @param int $activityId
2779 * @param int $action
2780 * @param int $activityTypeID
2781 *
2782 * @return bool
2783 */
2784 protected static function isContactPermittedAccessToCaseActivity($activityId, $action, $activityTypeID) {
2785 $oper = 'view';
2786 if ($action == CRM_Core_Action::UPDATE) {
2787 $oper = 'edit';
2788 }
2789 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2790 $oper,
2791 $activityTypeID
2792 );
2793
2794 return $allow;
2795 }
2796
2797 /**
2798 * Check if the logged in user has permission to access the given activity type.
2799 *
2800 * @param int $activityTypeID
2801 *
2802 * @return bool
2803 */
2804 protected static function hasPermissionForActivityType($activityTypeID) {
2805 $permittedActivityTypes = self::getPermittedActivityTypes();
2806 return isset($permittedActivityTypes[$activityTypeID]);
2807 }
2808
2809 /**
2810 * Get the activity types the user is permitted to access.
2811 *
2812 * The types are filtered by the components they have access to. ie. a user
2813 * with access CiviContribute but not CiviMember will see contribution related
2814 * activities and activities with no component (e.g meetings) but not member related ones.
2815 *
2816 * @return array
2817 */
2818 protected static function getPermittedActivityTypes() {
2819 $userID = (int) CRM_Core_Session::getLoggedInContactID();
2820 if (!isset(Civi::$statics[__CLASS__]['permitted_activity_types'][$userID])) {
2821 $permittedActivityTypes = [];
2822 $components = self::activityComponents(FALSE);
2823 $componentClause = empty($components) ? '' : (' OR component_id IN (' . implode(', ', array_keys($components)) . ')');
2824
2825 $types = CRM_Core_DAO::executeQuery(
2826 "
2827 SELECT option_value.value activity_type_id
2828 FROM civicrm_option_value option_value
2829 INNER JOIN civicrm_option_group grp ON (grp.id = option_group_id AND grp.name = 'activity_type')
2830 WHERE component_id IS NULL $componentClause")->fetchAll();
2831 foreach ($types as $type) {
2832 $permittedActivityTypes[$type['activity_type_id']] = (int) $type['activity_type_id'];
2833 }
2834 Civi::$statics[__CLASS__]['permitted_activity_types'][$userID] = $permittedActivityTypes;
2835 }
2836 return Civi::$statics[__CLASS__]['permitted_activity_types'][$userID];
2837 }
2838
2839 /**
2840 * @param $params
2841 * @return array
2842 */
2843 protected static function getActivityParamsForDashboardFunctions($params) {
2844 $activityParams = [
2845 'is_deleted' => 0,
2846 'is_current_revision' => 1,
2847 'is_test' => 0,
2848 'contact_id' => CRM_Utils_Array::value('contact_id', $params),
2849 'check_permissions' => 1,
2850 'options' => [
2851 'offset' => CRM_Utils_Array::value('offset', $params, 0),
2852 ],
2853 ];
2854
2855 if (!empty($params['activity_status_id'])) {
2856 $activityParams['activity_status_id'] = ['IN' => explode(',', $params['activity_status_id'])];
2857 }
2858
2859 $activityParams['activity_type_id'] = self::filterActivityTypes($params);
2860 $enabledComponents = self::activityComponents();
2861 // @todo - should we move this to activity get api.
2862 foreach ([
2863 'case_id' => 'CiviCase',
2864 'campaign_id' => 'CiviCampaign'
2865 ] as $attr => $component) {
2866 if (!in_array($component, $enabledComponents)) {
2867 $activityParams[$attr] = ['IS NULL' => 1];
2868 }
2869 }
2870 return $activityParams;
2871 }
2872
2873 /**
2874 * Checks if user has permissions to edit inbound e-mails, either bsic info
2875 * or both basic information and content.
2876 *
2877 * @return bool
2878 */
2879 public function checkEditInboundEmailsPermissions() {
2880 if (CRM_Core_Permission::check('edit inbound email basic information')
2881 || CRM_Core_Permission::check('edit inbound email basic information and content')
2882 ) {
2883 return TRUE;
2884 }
2885
2886 return FALSE;
2887 }
2888
2889 /**
2890 * Wrapper for ajax activity selector.
2891 *
2892 * @param array $params
2893 * Associated array for params record id.
2894 *
2895 * @return array
2896 * Associated array of contact activities
2897 */
2898 public static function getContactActivitySelector(&$params) {
2899 // Format the params.
2900 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2901 $params['rowCount'] = $params['rp'];
2902 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2903 $params['caseId'] = NULL;
2904 $context = CRM_Utils_Array::value('context', $params);
2905 $showContactOverlay = !CRM_Utils_String::startsWith($context, "dashlet");
2906 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2907 'option_group_id' => "activity_type",
2908 'options' => array('limit' => 0),
2909 ));
2910 $activityIcons = array();
2911 foreach ($activityTypeInfo['values'] as $type) {
2912 if (!empty($type['icon'])) {
2913 $activityIcons[$type['value']] = $type['icon'];
2914 }
2915 }
2916
2917 // Get contact activities.
2918 $activities = CRM_Activity_BAO_Activity::deprecatedGetActivities($params);
2919
2920 // Add total.
2921 $params['total'] = CRM_Activity_BAO_Activity::deprecatedGetActivitiesCount($params);
2922
2923 // Format params and add links.
2924 $contactActivities = array();
2925
2926 if (!empty($activities)) {
2927 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2928
2929 // Check logged in user for permission.
2930 $page = new CRM_Core_Page();
2931 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2932 $permissions = array($page->_permission);
2933 if (CRM_Core_Permission::check('delete activities')) {
2934 $permissions[] = CRM_Core_Permission::DELETE;
2935 }
2936
2937 $mask = CRM_Core_Action::mask($permissions);
2938
2939 foreach ($activities as $activityId => $values) {
2940 $activity = array();
2941 $activity['DT_RowId'] = $activityId;
2942 // Add class to this row if overdue.
2943 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2944 if (self::isOverdue($values)) {
2945 $activity['DT_RowClass'] .= ' status-overdue';
2946 }
2947 else {
2948 $activity['DT_RowClass'] .= ' status-ontime';
2949 }
2950
2951 $activity['DT_RowAttr'] = array();
2952 $activity['DT_RowAttr']['data-entity'] = 'activity';
2953 $activity['DT_RowAttr']['data-id'] = $activityId;
2954
2955 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ? '<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2956 $activity['subject'] = $values['subject'];
2957
2958 $activity['source_contact_name'] = '';
2959 if ($params['contact_id'] == $values['source_contact_id']) {
2960 $activity['source_contact_name'] = $values['source_contact_name'];
2961 }
2962 elseif ($values['source_contact_id']) {
2963 $srcTypeImage = "";
2964 if ($showContactOverlay) {
2965 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2966 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2967 FALSE,
2968 $values['source_contact_id']);
2969 }
2970 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System::href($values['source_contact_name'],
2971 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2972 }
2973 else {
2974 $activity['source_contact_name'] = '<em>n/a</em>';
2975 }
2976
2977 $activity['target_contact_name'] = '';
2978 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2979 $activity['target_contact'] = CRM_Utils_System::href($values['recipients'],
2980 'civicrm/mailing/report/event',
2981 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2982 }
2983 elseif (!empty($values['recipients'])) {
2984 $activity['target_contact_name'] = $values['recipients'];
2985 }
2986 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2987 $activity['target_contact_name'] = '';
2988 $firstTargetName = reset($values['target_contact_name']);
2989 $firstTargetContactID = key($values['target_contact_name']);
2990
2991 $targetLink = CRM_Utils_System::href($firstTargetName, 'civicrm/contact/view', "reset=1&cid={$firstTargetContactID}");
2992 if ($showContactOverlay) {
2993 $targetTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2994 CRM_Contact_BAO_Contact::getContactType($firstTargetContactID),
2995 FALSE,
2996 $firstTargetContactID);
2997 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2998 }
2999 else {
3000 $activity['target_contact_name'] .= $targetLink;
3001 }
3002
3003 if ($extraCount = $values['target_contact_counter'] - 1) {
3004 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
3005 }
3006 if ($showContactOverlay) {
3007 $activity['target_contact_name'] .= "</div> ";
3008 }
3009 }
3010 elseif (!$values['target_contact_name']) {
3011 $activity['target_contact_name'] = '<em>n/a</em>';
3012 }
3013
3014 $activity['assignee_contact_name'] = '';
3015 if (empty($values['assignee_contact_name'])) {
3016 $activity['assignee_contact_name'] = '<em>n/a</em>';
3017 }
3018 elseif (!empty($values['assignee_contact_name'])) {
3019 $count = 0;
3020 $activity['assignee_contact_name'] = '';
3021 foreach ($values['assignee_contact_name'] as $acID => $acName) {
3022 if ($acID && $count < 5) {
3023 $assigneeTypeImage = "";
3024 $assigneeLink = CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
3025 if ($showContactOverlay) {
3026 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
3027 CRM_Contact_BAO_Contact::getContactType($acID),
3028 FALSE,
3029 $acID);
3030 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
3031 }
3032 else {
3033 $activity['assignee_contact_name'] .= $assigneeLink;
3034 }
3035
3036 $count++;
3037 if ($count) {
3038 $activity['assignee_contact_name'] .= ";&nbsp;";
3039 }
3040 if ($showContactOverlay) {
3041 $activity['assignee_contact_name'] .= "</div> ";
3042 }
3043
3044 if ($count == 4) {
3045 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
3046 break;
3047 }
3048 }
3049 }
3050 }
3051
3052 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
3053 $activity['status_id'] = $activityStatus[$values['status_id']];
3054
3055 // build links
3056 $activity['links'] = '';
3057 $accessMailingReport = FALSE;
3058 if (!empty($values['mailingId'])) {
3059 $accessMailingReport = TRUE;
3060 }
3061
3062 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
3063 CRM_Utils_Array::value('activity_type_id', $values),
3064 CRM_Utils_Array::value('source_record_id', $values),
3065 $accessMailingReport,
3066 CRM_Utils_Array::value('activity_id', $values)
3067 );
3068
3069 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
3070
3071 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
3072 $actionMask,
3073 array(
3074 'id' => $values['activity_id'],
3075 'cid' => $params['contact_id'],
3076 'cxt' => $context,
3077 'caseid' => CRM_Utils_Array::value('case_id', $values),
3078 ),
3079 ts('more'),
3080 FALSE,
3081 'activity.tab.row',
3082 'Activity',
3083 $values['activity_id']
3084 );
3085
3086 if ($values['is_recurring_activity']) {
3087 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
3088 }
3089
3090 array_push($contactActivities, $activity);
3091 }
3092 }
3093
3094 $activitiesDT = array();
3095 $activitiesDT['data'] = $contactActivities;
3096 $activitiesDT['recordsTotal'] = $params['total'];
3097 $activitiesDT['recordsFiltered'] = $params['total'];
3098
3099 return $activitiesDT;
3100 }
3101
3102 /**
3103 * Copy custom fields and attachments from an existing activity to another.
3104 *
3105 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
3106 *
3107 * @param array $params
3108 */
3109 public static function copyExtendedActivityData($params) {
3110 // attach custom data to the new activity
3111 $customParams = $htmlType = array();
3112 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
3113
3114 if (!empty($customValues)) {
3115 $fieldIds = implode(', ', array_keys($customValues));
3116 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
3117 $result = CRM_Core_DAO::executeQuery($sql);
3118
3119 while ($result->fetch()) {
3120 $htmlType[] = $result->id;
3121 }
3122
3123 foreach ($customValues as $key => $value) {
3124 if ($value !== NULL) {
3125 // CRM-10542
3126 if (in_array($key, $htmlType)) {
3127 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
3128 $customParams["custom_{$key}_-1"] = array(
3129 'name' => $fileValues[0],
3130 'type' => $fileValues[1],
3131 );
3132 }
3133 else {
3134 $customParams["custom_{$key}_-1"] = $value;
3135 }
3136 }
3137 }
3138 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
3139 $params['mainActivityId'], 'Activity'
3140 );
3141 }
3142
3143 // copy activity attachments ( if any )
3144 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
3145 }
3146
3147 /**
3148 * Get activity contact.
3149 *
3150 * @param int $activityId
3151 * @param int $recordTypeID
3152 * @param string $column
3153 *
3154 * @return null
3155 */
3156 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
3157 $activityContact = new CRM_Activity_BAO_ActivityContact();
3158 $activityContact->activity_id = $activityId;
3159 if ($recordTypeID) {
3160 $activityContact->record_type_id = $recordTypeID;
3161 }
3162 if ($activityContact->find(TRUE)) {
3163 return $activityContact->$column;
3164 }
3165 return NULL;
3166 }
3167
3168 /**
3169 * Get source contact id.
3170 *
3171 * @param int $activityId
3172 *
3173 * @return null
3174 */
3175 public static function getSourceContactID($activityId) {
3176 static $sourceID = NULL;
3177 if (!$sourceID) {
3178 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
3179 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
3180 }
3181
3182 return self::getActivityContact($activityId, $sourceID);
3183 }
3184
3185 /**
3186 * Set api filter.
3187 *
3188 * @todo Document what this is for.
3189 *
3190 * @param array $params
3191 */
3192 public function setApiFilter(&$params) {
3193 if (!empty($params['target_contact_id'])) {
3194 $this->selectAdd();
3195 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
3196 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3197 $obj = new CRM_Activity_BAO_ActivityContact();
3198 $params['return.target_contact_id'] = 1;
3199 $this->joinAdd($obj, 'LEFT');
3200 $this->selectAdd('civicrm_activity.*');
3201 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
3202 }
3203 }
3204
3205 /**
3206 * Send activity as attachment.
3207 *
3208 * @param object $activity
3209 * @param array $mailToContacts
3210 * @param array $params
3211 *
3212 * @return bool
3213 */
3214 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
3215 if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
3216 $clientID = CRM_Utils_Array::value('client_id', $params);
3217 $caseID = CRM_Utils_Array::value('case_id', $params);
3218
3219 $ics = new CRM_Activity_BAO_ICalendar($activity);
3220 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
3221 $ics->addAttachment($attachments, $mailToContacts);
3222
3223 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
3224 $ics->cleanup();
3225 return $result;
3226 }
3227 return FALSE;
3228 }
3229
3230 }