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