Amount and source could exceed max length of subject column
[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 // Amount and source could exceed max length of subject column.
2202 return CRM_Utils_String::ellipsify($subject, 255);
2203 }
2204 }
2205
2206 /**
2207 * Get Parent activity for currently viewed activity.
2208 *
2209 * @param int $activityId
2210 * Current activity id.
2211 *
2212 * @return int
2213 * Id of parent activity otherwise false.
2214 */
2215 public static function getParentActivity($activityId) {
2216 static $parentActivities = array();
2217
2218 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
2219
2220 if (!array_key_exists($activityId, $parentActivities)) {
2221 $parentActivities[$activityId] = array();
2222
2223 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2224 $activityId,
2225 'parent_id'
2226 );
2227
2228 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
2229 }
2230
2231 return $parentActivities[$activityId];
2232 }
2233
2234 /**
2235 * Get total count of prior revision of currently viewed activity.
2236 *
2237 * @param $activityID
2238 * Current activity id.
2239 *
2240 * @return int
2241 * $params count of prior activities otherwise false.
2242 */
2243 public static function getPriorCount($activityID) {
2244 static $priorCounts = array();
2245
2246 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2247
2248 if (!array_key_exists($activityID, $priorCounts)) {
2249 $priorCounts[$activityID] = array();
2250 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2251 $activityID,
2252 'original_id'
2253 );
2254 $count = 0;
2255 if ($originalID) {
2256 $query = "
2257 SELECT count( id ) AS cnt
2258 FROM civicrm_activity
2259 WHERE ( id = {$originalID} OR original_id = {$originalID} )
2260 AND is_current_revision = 0
2261 AND id < {$activityID}
2262 ";
2263 $params = array(1 => array($originalID, 'Integer'));
2264 $count = CRM_Core_DAO::singleValueQuery($query, $params);
2265 }
2266 $priorCounts[$activityID] = $count ? $count : 0;
2267 }
2268
2269 return $priorCounts[$activityID];
2270 }
2271
2272 /**
2273 * Get all prior activities of currently viewed activity.
2274 *
2275 * @param $activityID
2276 * Current activity id.
2277 * @param bool $onlyPriorRevisions
2278 *
2279 * @return array
2280 * prior activities info.
2281 */
2282 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
2283 static $priorActivities = array();
2284
2285 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2286 $index = $activityID . '_' . (int) $onlyPriorRevisions;
2287
2288 if (!array_key_exists($index, $priorActivities)) {
2289 $priorActivities[$index] = array();
2290
2291 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2292 $activityID,
2293 'original_id'
2294 );
2295 if (!$originalID) {
2296 $originalID = $activityID;
2297 }
2298 if ($originalID) {
2299 $query = "
2300 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2301 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2302 WHERE (ca.id = %1 OR ca.original_id = %1)
2303 AND cl.entity_table = 'civicrm_activity'
2304 AND cl.entity_id = ca.id
2305 AND cl.modified_id = c.id
2306 ";
2307 if ($onlyPriorRevisions) {
2308 $query .= " AND ca.id < {$activityID}";
2309 }
2310 $query .= " ORDER BY ca.id DESC";
2311
2312 $params = array(1 => array($originalID, 'Integer'));
2313 $dao = CRM_Core_DAO::executeQuery($query, $params);
2314
2315 while ($dao->fetch()) {
2316 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
2317 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
2318 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
2319 }
2320 $dao->free();
2321 }
2322 }
2323 return $priorActivities[$index];
2324 }
2325
2326 /**
2327 * Find the latest revision of a given activity.
2328 *
2329 * @param int $activityID
2330 * Prior activity id.
2331 *
2332 * @return int
2333 * current activity id.
2334 */
2335 public static function getLatestActivityId($activityID) {
2336 static $latestActivityIds = array();
2337
2338 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2339
2340 if (!array_key_exists($activityID, $latestActivityIds)) {
2341 $latestActivityIds[$activityID] = array();
2342
2343 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2344 $activityID,
2345 'original_id'
2346 );
2347 if ($originalID) {
2348 $activityID = $originalID;
2349 }
2350 $params = array(1 => array($activityID, 'Integer'));
2351 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2352
2353 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
2354 }
2355
2356 return $latestActivityIds[$activityID];
2357 }
2358
2359 /**
2360 * Create a follow up a given activity.
2361 *
2362 * @param int $activityId
2363 * activity id of parent activity.
2364 * @param array $params
2365 *
2366 * @return CRM_Activity_BAO_Activity|null|object
2367 */
2368 public static function createFollowupActivity($activityId, $params) {
2369 if (!$activityId) {
2370 return NULL;
2371 }
2372
2373 $followupParams = array();
2374 $followupParams['parent_id'] = $activityId;
2375 $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
2376 $followupParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
2377 'activity_status_id',
2378 'Scheduled'
2379 );
2380
2381 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2382 // Get Subject of Follow-up Activiity, CRM-4491
2383 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
2384 $followupParams['assignee_contact_id'] = CRM_Utils_Array::value('followup_assignee_contact_id', $params);
2385
2386 // Create target contact for followup.
2387 if (!empty($params['target_contact_id'])) {
2388 $followupParams['target_contact_id'] = $params['target_contact_id'];
2389 }
2390
2391 $followupParams['activity_date_time'] = CRM_Utils_Date::processDate($params['followup_date'],
2392 $params['followup_date_time']
2393 );
2394 $followupActivity = self::create($followupParams);
2395
2396 return $followupActivity;
2397 }
2398
2399 /**
2400 * Get Activity specific File according activity type Id.
2401 *
2402 * @param int $activityTypeId
2403 * Activity id.
2404 * @param string $crmDir
2405 *
2406 * @return string|bool
2407 * if file exists returns $activityTypeFile activity filename otherwise false.
2408 */
2409 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2410 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2411
2412 if ($activityTypes[$activityTypeId]['name']) {
2413 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2414 }
2415 else {
2416 return FALSE;
2417 }
2418
2419 global $civicrm_root;
2420 $config = CRM_Core_Config::singleton();
2421 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2422 if (empty($config->customPHPPathDir)) {
2423 return FALSE;
2424 }
2425 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2426 return FALSE;
2427 }
2428 }
2429
2430 return $activityTypeFile;
2431 }
2432
2433 /**
2434 * Restore the activity.
2435 *
2436 * @param array $params
2437 *
2438 * @return CRM_Activity_DAO_Activity
2439 */
2440 public static function restoreActivity(&$params) {
2441 $activity = new CRM_Activity_DAO_Activity();
2442 $activity->copyValues($params);
2443
2444 $activity->is_deleted = 0;
2445 $result = $activity->save();
2446
2447 return $result;
2448 }
2449
2450 /**
2451 * Return list of activity statuses of a given type.
2452 *
2453 * Note: activity status options use the "grouping" field to distinguish status types.
2454 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2455 *
2456 * @param int $type
2457 *
2458 * @return array
2459 */
2460 public static function getStatusesByType($type) {
2461 if (!isset(Civi::$statics[__CLASS__][__FUNCTION__])) {
2462 $statuses = civicrm_api3('OptionValue', 'get', array(
2463 'option_group_id' => 'activity_status',
2464 'return' => array('value', 'name', 'filter'),
2465 'options' => array('limit' => 0),
2466 ));
2467 Civi::$statics[__CLASS__][__FUNCTION__] = $statuses['values'];
2468 }
2469 $ret = array();
2470 foreach (Civi::$statics[__CLASS__][__FUNCTION__] as $status) {
2471 if ($status['filter'] == $type) {
2472 $ret[$status['value']] = $status['name'];
2473 }
2474 }
2475 return $ret;
2476 }
2477
2478 /**
2479 * Check if activity is overdue.
2480 *
2481 * @param array $activity
2482 *
2483 * @return bool
2484 */
2485 public static function isOverdue($activity) {
2486 return array_key_exists($activity['status_id'], self::getStatusesByType(self::INCOMPLETE)) && CRM_Utils_Date::overdue($activity['activity_date_time']);
2487 }
2488
2489 /**
2490 * Get the exportable fields for Activities.
2491 *
2492 * @param string $name
2493 * If it is called by case $name = Case else $name = Activity.
2494 *
2495 * @return array
2496 * array of exportable Fields
2497 */
2498 public static function &exportableFields($name = 'Activity') {
2499 if (!isset(self::$_exportableFields[$name])) {
2500 self::$_exportableFields[$name] = array();
2501
2502 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2503 // my case hence we have defined fields as case_*
2504 if ($name == 'Activity') {
2505 $exportableFields = CRM_Activity_DAO_Activity::export();
2506 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2507 $exportableFields['source_contact'] = array(
2508 'title' => ts('Source Contact'),
2509 'type' => CRM_Utils_Type::T_STRING,
2510 );
2511
2512 $Activityfields = array(
2513 'activity_type' => array(
2514 'title' => ts('Activity Type'),
2515 'name' => 'activity_type',
2516 'type' => CRM_Utils_Type::T_STRING,
2517 'searchByLabel' => TRUE,
2518 ),
2519 'activity_status' => array(
2520 'title' => ts('Activity Status'),
2521 'name' => 'activity_status',
2522 'type' => CRM_Utils_Type::T_STRING,
2523 'searchByLabel' => TRUE,
2524 ),
2525 'activity_priority' => array(
2526 'title' => ts('Activity Priority'),
2527 'name' => 'activity_priority',
2528 'type' => CRM_Utils_Type::T_STRING,
2529 'searchByLabel' => TRUE,
2530 ),
2531 );
2532 $fields = array_merge($Activityfields, $exportableFields);
2533 }
2534 else {
2535 // Set title to activity fields.
2536 $fields = array(
2537 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
2538 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
2539 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
2540 'case_scheduled_activity_date' => array(
2541 'title' => ts('Activity Scheduled Date'),
2542 'type' => CRM_Utils_Type::T_DATE,
2543 ),
2544 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2545 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2546 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
2547 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
2548 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
2549 'case_activity_is_auto' => array(
2550 'title' => ts('Activity Auto-generated?'),
2551 'type' => CRM_Utils_Type::T_BOOLEAN,
2552 ),
2553 );
2554 }
2555
2556 // add custom data for case activities
2557 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2558
2559 self::$_exportableFields[$name] = $fields;
2560 }
2561 return self::$_exportableFields[$name];
2562 }
2563
2564 /**
2565 * Get the allowed profile fields for Activities.
2566 *
2567 * @return array
2568 * array of activity profile Fields
2569 */
2570 public static function getProfileFields() {
2571 $exportableFields = self::exportableFields('Activity');
2572 $skipFields = array(
2573 'activity_id',
2574 'activity_type',
2575 'source_contact_id',
2576 'source_contact',
2577 'activity_campaign',
2578 'activity_is_test',
2579 'is_current_revision',
2580 'activity_is_deleted',
2581 );
2582 $config = CRM_Core_Config::singleton();
2583 if (!in_array('CiviCampaign', $config->enableComponents)) {
2584 $skipFields[] = 'activity_engagement_level';
2585 }
2586
2587 foreach ($skipFields as $field) {
2588 if (isset($exportableFields[$field])) {
2589 unset($exportableFields[$field]);
2590 }
2591 }
2592
2593 // hack to use 'activity_type_id' instead of 'activity_type'
2594 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2595 unset($exportableFields['activity_status']);
2596
2597 return $exportableFields;
2598 }
2599
2600 /**
2601 * This function deletes the activity record related to contact record.
2602 *
2603 * This is conditional on there being no target and assignee record
2604 * with other contacts.
2605 *
2606 * @param int $contactId
2607 * ContactId.
2608 *
2609 * @return true/null
2610 */
2611 public static function cleanupActivity($contactId) {
2612 $result = NULL;
2613 if (!$contactId) {
2614 return $result;
2615 }
2616 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2617 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2618
2619 $transaction = new CRM_Core_Transaction();
2620
2621 // delete activity if there is no record in civicrm_activity_contact
2622 // pointing to any other contact record
2623 $activityContact = new CRM_Activity_DAO_ActivityContact();
2624 $activityContact->contact_id = $contactId;
2625 $activityContact->record_type_id = $sourceID;
2626 $activityContact->find();
2627
2628 while ($activityContact->fetch()) {
2629 // delete activity_contact record for the deleted contact
2630 $activityContact->delete();
2631
2632 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2633 $activityContactOther->activity_id = $activityContact->activity_id;
2634
2635 // delete activity only if no other contacts connected
2636 if (!$activityContactOther->find(TRUE)) {
2637 $activityParams = array('id' => $activityContact->activity_id);
2638 $result = self::deleteActivity($activityParams);
2639 }
2640
2641 $activityContactOther->free();
2642 }
2643
2644 $activityContact->free();
2645 $transaction->commit();
2646
2647 return $result;
2648 }
2649
2650 /**
2651 * Does user has sufficient permission for view/edit activity record.
2652 *
2653 * @param int $activityId
2654 * Activity record id.
2655 * @param int $action
2656 * Edit/view.
2657 *
2658 * @return bool
2659 */
2660 public static function checkPermission($activityId, $action) {
2661 $allow = FALSE;
2662 if (!$activityId ||
2663 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2664 ) {
2665 return $allow;
2666 }
2667
2668 $activity = new CRM_Activity_DAO_Activity();
2669 $activity->id = $activityId;
2670 if (!$activity->find(TRUE)) {
2671 return $allow;
2672 }
2673
2674 // Component related permissions.
2675 $compPermissions = array(
2676 'CiviCase' => array(
2677 'administer CiviCase',
2678 'access my cases and activities',
2679 'access all cases and activities',
2680 ),
2681 'CiviMail' => array('access CiviMail'),
2682 'CiviEvent' => array('access CiviEvent'),
2683 'CiviGrant' => array('access CiviGrant'),
2684 'CiviPledge' => array('access CiviPledge'),
2685 'CiviMember' => array('access CiviMember'),
2686 'CiviReport' => array('access CiviReport'),
2687 'CiviContribute' => array('access CiviContribute'),
2688 'CiviCampaign' => array('administer CiviCampaign'),
2689 );
2690
2691 // Return early when it is case activity.
2692 $isCaseActivity = CRM_Case_BAO_Case::isCaseActivity($activityId);
2693 // Check for civicase related permission.
2694 if ($isCaseActivity) {
2695 $allow = FALSE;
2696 foreach ($compPermissions['CiviCase'] as $per) {
2697 if (CRM_Core_Permission::check($per)) {
2698 $allow = TRUE;
2699 break;
2700 }
2701 }
2702
2703 // Check for case specific permissions.
2704 if ($allow) {
2705 $oper = 'view';
2706 if ($action == CRM_Core_Action::UPDATE) {
2707 $oper = 'edit';
2708 }
2709 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2710 $oper,
2711 $activity->activity_type_id
2712 );
2713 }
2714
2715 return $allow;
2716 }
2717
2718 // First check the component permission.
2719 $sql = "
2720 SELECT component_id
2721 FROM civicrm_option_value val
2722 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2723 WHERE val.value = %2";
2724 $params = array(
2725 1 => array('activity_type', 'String'),
2726 2 => array($activity->activity_type_id, 'Integer'),
2727 );
2728 $componentId = CRM_Core_DAO::singleValueQuery($sql, $params);
2729
2730 if ($componentId) {
2731 $componentName = CRM_Core_Component::getComponentName($componentId);
2732 $compPermission = CRM_Utils_Array::value($componentName, $compPermissions);
2733
2734 // Here we are interesting in any single permission.
2735 if (is_array($compPermission)) {
2736 foreach ($compPermission as $per) {
2737 if (CRM_Core_Permission::check($per)) {
2738 $allow = TRUE;
2739 break;
2740 }
2741 }
2742 }
2743 }
2744
2745 // Check for this permission related to contact.
2746 $permission = CRM_Core_Permission::VIEW;
2747 if ($action == CRM_Core_Action::UPDATE) {
2748 $permission = CRM_Core_Permission::EDIT;
2749 }
2750
2751 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2752 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2753 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2754 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2755
2756 // Check for source contact.
2757 if (!$componentId || $allow) {
2758 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2759 // Account for possibility of activity not having a source contact (as it may have been deleted).
2760 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission) : TRUE;
2761 }
2762
2763 // Check for target and assignee contacts.
2764 if ($allow) {
2765 // First check for supper permission.
2766 $supPermission = 'view all contacts';
2767 if ($action == CRM_Core_Action::UPDATE) {
2768 $supPermission = 'edit all contacts';
2769 }
2770 $allow = CRM_Core_Permission::check($supPermission);
2771
2772 // User might have sufficient permission, through acls.
2773 if (!$allow) {
2774 $allow = TRUE;
2775 // Get the target contacts.
2776 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
2777 foreach ($targetContacts as $cnt => $contactId) {
2778 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2779 $allow = FALSE;
2780 break;
2781 }
2782 }
2783
2784 // Get the assignee contacts.
2785 if ($allow) {
2786 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
2787 foreach ($assigneeContacts as $cnt => $contactId) {
2788 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2789 $allow = FALSE;
2790 break;
2791 }
2792 }
2793 }
2794 }
2795 }
2796
2797 return $allow;
2798 }
2799
2800 /**
2801 * Wrapper for ajax activity selector.
2802 *
2803 * @param array $params
2804 * Associated array for params record id.
2805 *
2806 * @return array
2807 * Associated array of contact activities
2808 */
2809 public static function getContactActivitySelector(&$params) {
2810 // Format the params.
2811 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2812 $params['rowCount'] = $params['rp'];
2813 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2814 $params['caseId'] = NULL;
2815 $context = CRM_Utils_Array::value('context', $params);
2816 $showContactOverlay = !CRM_Utils_String::startsWith($context, "dashlet");
2817 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2818 'option_group_id' => "activity_type",
2819 'options' => array('limit' => 0),
2820 ));
2821 $activityIcons = array();
2822 foreach ($activityTypeInfo['values'] as $type) {
2823 if (!empty($type['icon'])) {
2824 $activityIcons[$type['value']] = $type['icon'];
2825 }
2826 }
2827
2828 // Get contact activities.
2829 $activities = CRM_Activity_BAO_Activity::deprecatedGetActivities($params);
2830
2831 // Add total.
2832 $params['total'] = CRM_Activity_BAO_Activity::deprecatedGetActivitiesCount($params);
2833
2834 // Format params and add links.
2835 $contactActivities = array();
2836
2837 if (!empty($activities)) {
2838 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2839
2840 // Check logged in user for permission.
2841 $page = new CRM_Core_Page();
2842 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2843 $permissions = array($page->_permission);
2844 if (CRM_Core_Permission::check('delete activities')) {
2845 $permissions[] = CRM_Core_Permission::DELETE;
2846 }
2847
2848 $mask = CRM_Core_Action::mask($permissions);
2849
2850 foreach ($activities as $activityId => $values) {
2851 $activity = array();
2852 $activity['DT_RowId'] = $activityId;
2853 // Add class to this row if overdue.
2854 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2855 if (self::isOverdue($values)) {
2856 $activity['DT_RowClass'] .= ' status-overdue';
2857 }
2858 else {
2859 $activity['DT_RowClass'] .= ' status-ontime';
2860 }
2861
2862 $activity['DT_RowAttr'] = array();
2863 $activity['DT_RowAttr']['data-entity'] = 'activity';
2864 $activity['DT_RowAttr']['data-id'] = $activityId;
2865
2866 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ? '<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2867 $activity['subject'] = $values['subject'];
2868
2869 $activity['source_contact_name'] = '';
2870 if ($params['contact_id'] == $values['source_contact_id']) {
2871 $activity['source_contact_name'] = $values['source_contact_name'];
2872 }
2873 elseif ($values['source_contact_id']) {
2874 $srcTypeImage = "";
2875 if ($showContactOverlay) {
2876 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2877 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2878 FALSE,
2879 $values['source_contact_id']);
2880 }
2881 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System::href($values['source_contact_name'],
2882 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2883 }
2884 else {
2885 $activity['source_contact_name'] = '<em>n/a</em>';
2886 }
2887
2888 $activity['target_contact_name'] = '';
2889 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2890 $activity['target_contact'] = CRM_Utils_System::href($values['recipients'],
2891 'civicrm/mailing/report/event',
2892 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2893 }
2894 elseif (!empty($values['recipients'])) {
2895 $activity['target_contact_name'] = $values['recipients'];
2896 }
2897 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2898 $activity['target_contact_name'] = '';
2899 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2900 $targetTypeImage = "";
2901 $targetLink = CRM_Utils_System::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2902 if ($showContactOverlay) {
2903 $targetTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2904 CRM_Contact_BAO_Contact::getContactType($tcID),
2905 FALSE,
2906 $tcID);
2907 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2908 }
2909 else {
2910 $activity['target_contact_name'] .= $targetLink;
2911 }
2912 }
2913
2914 if ($extraCount = $values['target_contact_counter'] - 1) {
2915 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2916 }
2917 if ($showContactOverlay) {
2918 $activity['target_contact_name'] .= "</div> ";
2919 }
2920 }
2921 elseif (!$values['target_contact_name']) {
2922 $activity['target_contact_name'] = '<em>n/a</em>';
2923 }
2924
2925 $activity['assignee_contact_name'] = '';
2926 if (empty($values['assignee_contact_name'])) {
2927 $activity['assignee_contact_name'] = '<em>n/a</em>';
2928 }
2929 elseif (!empty($values['assignee_contact_name'])) {
2930 $count = 0;
2931 $activity['assignee_contact_name'] = '';
2932 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2933 if ($acID && $count < 5) {
2934 $assigneeTypeImage = "";
2935 $assigneeLink = CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2936 if ($showContactOverlay) {
2937 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2938 CRM_Contact_BAO_Contact::getContactType($acID),
2939 FALSE,
2940 $acID);
2941 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2942 }
2943 else {
2944 $activity['assignee_contact_name'] .= $assigneeLink;
2945 }
2946
2947 $count++;
2948 if ($count) {
2949 $activity['assignee_contact_name'] .= ";&nbsp;";
2950 }
2951 if ($showContactOverlay) {
2952 $activity['assignee_contact_name'] .= "</div> ";
2953 }
2954
2955 if ($count == 4) {
2956 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2957 break;
2958 }
2959 }
2960 }
2961 }
2962
2963 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2964 $activity['status_id'] = $activityStatus[$values['status_id']];
2965
2966 // build links
2967 $activity['links'] = '';
2968 $accessMailingReport = FALSE;
2969 if (!empty($values['mailingId'])) {
2970 $accessMailingReport = TRUE;
2971 }
2972
2973 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2974 CRM_Utils_Array::value('activity_type_id', $values),
2975 CRM_Utils_Array::value('source_record_id', $values),
2976 $accessMailingReport,
2977 CRM_Utils_Array::value('activity_id', $values)
2978 );
2979
2980 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2981
2982 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
2983 $actionMask,
2984 array(
2985 'id' => $values['activity_id'],
2986 'cid' => $params['contact_id'],
2987 'cxt' => $context,
2988 'caseid' => CRM_Utils_Array::value('case_id', $values),
2989 ),
2990 ts('more'),
2991 FALSE,
2992 'activity.tab.row',
2993 'Activity',
2994 $values['activity_id']
2995 );
2996
2997 if ($values['is_recurring_activity']) {
2998 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2999 }
3000
3001 array_push($contactActivities, $activity);
3002 }
3003 }
3004
3005 $activitiesDT = array();
3006 $activitiesDT['data'] = $contactActivities;
3007 $activitiesDT['recordsTotal'] = $params['total'];
3008 $activitiesDT['recordsFiltered'] = $params['total'];
3009
3010 return $activitiesDT;
3011 }
3012
3013 /**
3014 * Copy custom fields and attachments from an existing activity to another.
3015 *
3016 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
3017 *
3018 * @param array $params
3019 */
3020 public static function copyExtendedActivityData($params) {
3021 // attach custom data to the new activity
3022 $customParams = $htmlType = array();
3023 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
3024
3025 if (!empty($customValues)) {
3026 $fieldIds = implode(', ', array_keys($customValues));
3027 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
3028 $result = CRM_Core_DAO::executeQuery($sql);
3029
3030 while ($result->fetch()) {
3031 $htmlType[] = $result->id;
3032 }
3033
3034 foreach ($customValues as $key => $value) {
3035 if ($value !== NULL) {
3036 // CRM-10542
3037 if (in_array($key, $htmlType)) {
3038 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
3039 $customParams["custom_{$key}_-1"] = array(
3040 'name' => $fileValues[0],
3041 'path' => $fileValues[1],
3042 );
3043 }
3044 else {
3045 $customParams["custom_{$key}_-1"] = $value;
3046 }
3047 }
3048 }
3049 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
3050 $params['mainActivityId'], 'Activity'
3051 );
3052 }
3053
3054 // copy activity attachments ( if any )
3055 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
3056 }
3057
3058 /**
3059 * Get activity contact.
3060 *
3061 * @param int $activityId
3062 * @param int $recordTypeID
3063 * @param string $column
3064 *
3065 * @return null
3066 */
3067 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
3068 $activityContact = new CRM_Activity_BAO_ActivityContact();
3069 $activityContact->activity_id = $activityId;
3070 if ($recordTypeID) {
3071 $activityContact->record_type_id = $recordTypeID;
3072 }
3073 if ($activityContact->find(TRUE)) {
3074 return $activityContact->$column;
3075 }
3076 return NULL;
3077 }
3078
3079 /**
3080 * Get source contact id.
3081 *
3082 * @param int $activityId
3083 *
3084 * @return null
3085 */
3086 public static function getSourceContactID($activityId) {
3087 static $sourceID = NULL;
3088 if (!$sourceID) {
3089 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
3090 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
3091 }
3092
3093 return self::getActivityContact($activityId, $sourceID);
3094 }
3095
3096 /**
3097 * Set api filter.
3098 *
3099 * @todo Document what this is for.
3100 *
3101 * @param array $params
3102 */
3103 public function setApiFilter(&$params) {
3104 if (!empty($params['target_contact_id'])) {
3105 $this->selectAdd();
3106 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
3107 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3108 $obj = new CRM_Activity_BAO_ActivityContact();
3109 $params['return.target_contact_id'] = 1;
3110 $this->joinAdd($obj, 'LEFT');
3111 $this->selectAdd('civicrm_activity.*');
3112 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
3113 }
3114 }
3115
3116 /**
3117 * Send activity as attachment.
3118 *
3119 * @param object $activity
3120 * @param array $mailToContacts
3121 * @param array $params
3122 *
3123 * @return bool
3124 */
3125 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
3126 if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
3127 $clientID = CRM_Utils_Array::value('client_id', $params);
3128 $caseID = CRM_Utils_Array::value('case_id', $params);
3129
3130 $ics = new CRM_Activity_BAO_ICalendar($activity);
3131 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
3132 $ics->addAttachment($attachments, $mailToContacts);
3133
3134 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
3135 $ics->cleanup();
3136 return $result;
3137 }
3138 return FALSE;
3139 }
3140
3141 }