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