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