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