Merge pull request #2120 from pratik-joshi/CRM-13857
[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',
679 'status_id' => 'int unsigned',
680 'subject' => 'varchar(255)',
cec82bce 681 'source_contact_name' => 'varchar(255)',
6a488035
TO
682 'activity_type_id' => 'int unsigned',
683 'activity_type' => 'varchar(128)',
684 'case_id' => 'int unsigned',
685 'case_subject' => 'varchar(255)',
686 'campaign_id' => 'int unsigned',
687 );
688
689 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
690 $insertValueSQL = array();
6da5bfce 691 // The activityTempTable contains the sorted rows
692 // so in order to maintain the sort order as-is we add an auto_increment
693 // field; we can sort by this later to ensure the sort order stays correct.
694 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
6a488035
TO
695 foreach ($tableFields as $name => $desc) {
696 $sql .= "$name $desc,\n";
697 $insertValueSQL[] = $name;
698 }
699
6da5bfce 700 // add unique key on activity_id just to be sure
701 // this cannot be primary key because we need that for the auto_increment
702 // fixed_sort_order field
6a488035 703 $sql .= "
c1d26519 704 UNIQUE KEY ( activity_id )
6a488035
TO
705 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
706 ";
707
708 CRM_Core_DAO::executeQuery($sql);
709
710 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
711
712 $order = $limit = $groupBy = '';
6a488035
TO
713
714 if (!empty($input['sort'])) {
715 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
716 $orderBy = $input['sort']->orderBy();
717 if (!empty($orderBy)) {
718 $order = " ORDER BY $orderBy";
719 }
720 }
721 elseif (trim($input['sort'])) {
21d32567
DL
722 $sort = CRM_Utils_Type::escape($input['sort'], 'String');
723 $order = " ORDER BY $sort ";
6a488035
TO
724 }
725 }
726
727 if (empty($order)) {
6da5bfce 728 // context = 'activity' in Activities tab.
6a488035
TO
729 $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 ";
730 }
731
732 if (!empty($input['rowCount']) &&
733 $input['rowCount'] > 0
734 ) {
735 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
736 }
737
738 $input['count'] = FALSE;
739 list($sqlClause, $params) = self::getActivitySQLClause($input);
740
741 $query = "{$insertSQL}
742 SELECT DISTINCT tbl.* from ( {$sqlClause} )
743as tbl ";
744
745 //filter case activities - CRM-5761
746 $components = self::activityComponents();
747 if (!in_array('CiviCase', $components)) {
748 $query .= "
749LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
750 WHERE civicrm_case_activity.id IS NULL";
751 }
752
753 $query = $query . $groupBy . $order . $limit;
754
755 $dao = CRM_Core_DAO::executeQuery($query, $params);
756
6a488035
TO
757 // step 2: Get target and assignee contacts for above activities
758 // create temp table for target contacts
91da6cd5
DL
759 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
760 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
a24b3694 761 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16), contact_name varchar(255) )
6a488035
TO
762 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
763
764 CRM_Core_DAO::executeQuery($query);
765
766 // note that we ignore bulk email for targets, since we don't show it in selector
91da6cd5 767 $query = "
a24b3694 768INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name )
91da6cd5
DL
769SELECT ac.activity_id,
770 ac.contact_id,
5b5da1ef 771 ac.record_type_id,
91da6cd5
DL
772 c.sort_name
773FROM civicrm_activity_contact ac
ef41c3d4 774INNER JOIN {$activityTempTable} ON ( ac.activity_id = {$activityTempTable}.activity_id )
5b5da1ef 775INNER JOIN civicrm_contact c ON c.id = ac.contact_id
91da6cd5 776WHERE c.is_deleted = 0
b319d00a 777
91da6cd5 778";
6a488035
TO
779 CRM_Core_DAO::executeQuery($query);
780
6a488035 781 // step 3: Combine all temp tables to get final query for activity selector
6da5bfce 782 // sort by the original sort order, stored in fixed_sort_order
6a488035 783 $query = "
91da6cd5
DL
784SELECT {$activityTempTable}.*,
785 {$activityContactTempTable}.contact_id,
a24b3694 786 {$activityContactTempTable}.record_type_id,
5b5da1ef 787 {$activityContactTempTable}.contact_name
91da6cd5
DL
788FROM {$activityTempTable}
789INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
6da5bfce 790ORDER BY fixed_sort_order
6a488035
TO
791 ";
792
793
794 $dao = CRM_Core_DAO::executeQuery($query);
795
796 //CRM-3553, need to check user has access to target groups.
797 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
798 $accessCiviMail = (
799 (CRM_Core_Permission::check('access CiviMail')) ||
800 (CRM_Mailing_Info::workflowEnabled() &&
801 CRM_Core_Permission::check('create mailings'))
802 );
803
804 //get all campaigns.
805 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
806
807 $values = array();
e7e657f0 808 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 809 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
810 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
811 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
b319d00a 812
a24b3694 813
6a488035
TO
814 while ($dao->fetch()) {
815 $activityID = $dao->activity_id;
816 $values[$activityID]['activity_id'] = $dao->activity_id;
817 $values[$activityID]['source_record_id'] = $dao->source_record_id;
818 $values[$activityID]['activity_type_id'] = $dao->activity_type_id;
819 $values[$activityID]['activity_type'] = $dao->activity_type;
820 $values[$activityID]['activity_date_time'] = $dao->activity_date_time;
821 $values[$activityID]['status_id'] = $dao->status_id;
822 $values[$activityID]['subject'] = $dao->subject;
6a488035
TO
823 $values[$activityID]['campaign_id'] = $dao->campaign_id;
824
825 if ($dao->campaign_id) {
826 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id];
827 }
828
829 if (!CRM_Utils_Array::value('assignee_contact_name', $values[$activityID])) {
830 $values[$activityID]['assignee_contact_name'] = array();
831 }
832
833 if (!CRM_Utils_Array::value('target_contact_name', $values[$activityID])) {
834 $values[$activityID]['target_contact_name'] = array();
835 }
836
a24b3694 837 if ($dao->record_type_id == $sourceID && $dao->contact_id) {
91da6cd5
DL
838 $values[$activityID]['source_contact_id'] = $dao->contact_id;
839 $values[$activityID]['source_contact_name'] = $dao->contact_name;
840 }
841
6a488035
TO
842 if (!$bulkActivityTypeID || ($bulkActivityTypeID != $dao->activity_type_id)) {
843 // build array of target / assignee names
a24b3694 844 if ($dao->record_type_id == $targetID && $dao->contact_id) {
91da6cd5 845 $values[$activityID]['target_contact_name'][$dao->contact_id] = $dao->contact_name;
6a488035 846 }
a24b3694 847 if ($dao->record_type_id == $assigneeID && $dao->contact_id) {
91da6cd5 848 $values[$activityID]['assignee_contact_name'][$dao->contact_id] = $dao->contact_name;
6a488035
TO
849 }
850
851 // case related fields
852 $values[$activityID]['case_id'] = $dao->case_id;
853 $values[$activityID]['case_subject'] = $dao->case_subject;
854 }
855 else {
856 $values[$activityID]['recipients'] = ts('(recipients)');
2678caac 857 $values[$activityID]['mailingId'] = false;
6a488035
TO
858 if (
859 $accessCiviMail &&
860 ($mailingIDs === TRUE || in_array($dao->source_record_id, $mailingIDs))
861 ) {
2678caac 862 $values[$activityID]['mailingId'] = true;
6a488035
TO
863 }
864 }
865 }
866
867 // add info on whether the related contacts are deleted (CRM-5673)
868 // FIXME: ideally this should be tied to ACLs
869
870 // grab all the related contact ids
871 $cids = array();
872 foreach ($values as $value) {
873 $cids[] = $value['source_contact_id'];
874 }
875 $cids = array_filter(array_unique($cids));
876
877 // see which of the cids are of deleted contacts
878 if ($cids) {
879 $sql = 'SELECT id FROM civicrm_contact WHERE id IN (' . implode(', ', $cids) . ') AND is_deleted = 1';
880 $dao = CRM_Core_DAO::executeQuery($sql);
881 $dels = array();
882 while ($dao->fetch()) {
883 $dels[] = $dao->id;
884 }
885
886 // hide the deleted contacts
887 foreach ($values as & $value) {
888 if (in_array($value['source_contact_id'], $dels)) {
889 unset($value['source_contact_id'], $value['source_contact_name']);
890 }
891 }
892 }
893
894 return $values;
895 }
896
897 /**
898 * Get the component id and name those are enabled and logged in
899 * user has permission. To decide whether we are going to include
900 * component related activities w/ core activity retrieve process.
901 *
902 * return an array of component id and name.
903 * @static
904 **/
905 static function activityComponents() {
906 $components = array();
907 $compInfo = CRM_Core_Component::getEnabledComponents();
908 foreach ($compInfo as $compObj) {
909 if (CRM_Utils_Array::value('showActivitiesInCore', $compObj->info)) {
910 if ($compObj->info['name'] == 'CiviCampaign') {
911 $componentPermission = "administer {$compObj->name}";
912 }
913 else {
914 $componentPermission = "access {$compObj->name}";
915 }
916 if ($compObj->info['name'] == 'CiviCase') {
917 if (CRM_Case_BAO_Case::accessCiviCase()) {
918 $components[$compObj->componentID] = $compObj->info['name'];
919 }
920 }
921 elseif (CRM_Core_Permission::check($componentPermission)) {
922 $components[$compObj->componentID] = $compObj->info['name'];
923 }
924 }
925 }
926
927 return $components;
928 }
929
930 /**
931 * function to get the activity Count
932 *
933 * @param array $input array of parameters
934 * Keys include
0a9f61c4 935 * - contact_id int contact_id whose activities we want to retrieve
6a488035
TO
936 * - admin boolean if contact is admin
937 * - caseId int case ID
938 * - context string page on which selector is build
0a9f61c4 939 * - activity_type_id int|string the activity types we want to restrict by
6a488035
TO
940 *
941 * @return int count of activities
942 *
943 * @access public
944 * @static
945 */
946 static function &getActivitiesCount($input) {
947 $input['count'] = TRUE;
948 list($sqlClause, $params) = self::getActivitySQLClause($input);
949
950 //filter case activities - CRM-5761
951 $components = self::activityComponents();
952 if (!in_array('CiviCase', $components)) {
953 $query = "
954 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
955 FROM ( {$sqlClause} ) as tbl
956LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
957 WHERE civicrm_case_activity.id IS NULL";
958 }
959 else {
960 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
961 }
962
963 return CRM_Core_DAO::singleValueQuery($query, $params);
964 }
965
966 /**
967 * function to get the activity sql clause to pick activities
968 *
969 * @param array $input array of parameters
970 * Keys include
0a9f61c4 971 * - contact_id int contact_id whose activities we want to retrieve
6a488035
TO
972 * - admin boolean if contact is admin
973 * - caseId int case ID
974 * - context string page on which selector is build
975 * - count boolean are we interested in the count clause only?
0a9f61c4 976 * - activity_type_id int|string the activity types we want to restrict by
6a488035
TO
977 *
978 * @return int count of activities
979 *
980 * @access public
981 * @static
982 */
983 static function getActivitySQLClause($input) {
984 $params = array();
985 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
986
987 $config = CRM_Core_Config::singleton();
988 if (!CRM_Utils_Array::value('admin', $input, FALSE)) {
91da6cd5 989 $sourceWhere = ' ac.contact_id = %1 ';
6a488035
TO
990 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
991
992 $params = array(1 => array($input['contact_id'], 'Integer'));
993 }
994
995 $commonClauses = array(
996 "civicrm_option_group.name = 'activity_type'",
997 "civicrm_activity.is_deleted = 0",
998 "civicrm_activity.is_current_revision = 1",
2517d079 999 "civicrm_activity.is_test= 0",
6a488035
TO
1000 );
1001
1002 if ($input['context'] != 'activity') {
1003 $commonClauses[] = "civicrm_activity.status_id = 1";
1004 }
1005
1006 //Filter on component IDs.
1007 $components = self::activityComponents();
1008 if (!empty($components)) {
1009 $componentsIn = implode(',', array_keys($components));
1010 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1011 }
1012 else {
1013 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1014 }
1015
1016 // activity type ID clause
1017 if (!empty($input['activity_type_id'])) {
1018 if (is_array($input['activity_type_id'])) {
1019 foreach ($input['activity_type_id'] as $idx => $value) {
1020 $input['activity_type_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1021 }
1022 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1023 }
1024 else {
1025 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_id'], 'Positive');
1026 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1027 }
1028 }
1029
1030 // exclude by activity type clause
1031 if (!empty($input['activity_type_exclude_id'])) {
1032 if (is_array($input['activity_type_exclude_id'])) {
1033 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1034 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1035 }
1036 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1037 }
1038 else {
1039 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_exclude_id'], 'Positive');
1040 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1041 }
1042 }
1043
1044 $commonClause = implode(' AND ', $commonClauses);
1045
1046 $includeCaseActivities = FALSE;
1047 if (in_array('CiviCase', $components)) {
1048 $includeCaseActivities = TRUE;
1049 }
1050
1051
1052 // build main activity table select clause
1053 $sourceSelect = '';
cec82bce 1054
1055 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1056 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
a3696ce8 1057 $sourceJoin = "
cec82bce 1058INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id AND record_type_id = {$sourceID}
a3696ce8
DL
1059INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1060";
6a488035
TO
1061
1062 if (!$input['count']) {
1063 $sourceSelect = ',
1064 civicrm_activity.activity_date_time,
1065 civicrm_activity.status_id,
1066 civicrm_activity.subject,
cec82bce 1067 contact.sort_name as source_contact_name,
6a488035
TO
1068 civicrm_option_value.value as activity_type_id,
1069 civicrm_option_value.label as activity_type,
1070 null as case_id, null as case_subject,
5b5da1ef 1071 civicrm_activity.campaign_id as campaign_id
6a488035
TO
1072 ';
1073
6a488035
TO
1074 }
1075
1076 $sourceClause = "
1077 SELECT civicrm_activity.id as activity_id
1078 {$sourceSelect}
1079 from civicrm_activity
1080 left join civicrm_option_value on
1081 civicrm_activity.activity_type_id = civicrm_option_value.value
1082 left join civicrm_option_group on
1083 civicrm_option_group.id = civicrm_option_value.option_group_id
1084 {$sourceJoin}
1085 where
1086 {$sourceWhere}
1087 AND $commonClause
1088 ";
1089
6a488035
TO
1090 // Build case clause
1091 // or else exclude Inbound Emails that have been filed on a case.
1092 $caseClause = '';
1093
1094 if ($includeCaseActivities) {
1095 $caseSelect = '';
1096 if (!$input['count']) {
1097 $caseSelect = ',
1098 civicrm_activity.activity_date_time,
1099 civicrm_activity.status_id,
1100 civicrm_activity.subject,
ecaec004 1101 ac.contact_id,
cec82bce 1102 contact.sort_name as source_contact_name,
6a488035
TO
1103 civicrm_option_value.value as activity_type_id,
1104 civicrm_option_value.label as activity_type,
1105 null as case_id, null as case_subject,
1106 civicrm_activity.campaign_id as campaign_id';
1107 }
1108
1109 $caseClause = "
1110 union all
1111
1112 SELECT civicrm_activity.id as activity_id
1113 {$caseSelect}
1114 from civicrm_activity
1115 inner join civicrm_case_activity on
1116 civicrm_case_activity.activity_id = civicrm_activity.id
1117 inner join civicrm_case on
1118 civicrm_case_activity.case_id = civicrm_case.id
1119 inner join civicrm_case_contact on
1120 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1121 left join civicrm_option_value on
1122 civicrm_activity.activity_type_id = civicrm_option_value.value
1123 left join civicrm_option_group on
1124 civicrm_option_group.id = civicrm_option_value.option_group_id
1125 {$sourceJoin}
1126 where
1127 {$caseWhere}
1128 AND $commonClause
1129 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1130 ( civicrm_option_value.name <> 'Inbound Email' AND
1131 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1132 IS NOT NULL )
1133 )
1134 ";
1135 }
1136
a3696ce8 1137 $returnClause = " {$sourceClause} {$caseClause} ";
6a488035
TO
1138
1139 return array($returnClause, $params);
1140 }
1141
1142 /**
1143 * send the message to all the contacts and also insert a
1144 * contact activity in each contacts record
1145 *
1146 * @param array $contactDetails the array of contact details to send the email
1147 * @param string $subject the subject of the message
1148 * @param string $message the message contents
1149 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1150 * @param int $userID use this userID if set
1151 * @param string $from
1152 * @param array $attachments the array of attachments if any
0a9f61c4 1153 * @param string $cc cc recipient
1154 * @param string $bcc bcc recipient
6a488035 1155 * @param array $contactIds contact ids
c1d26519 1156 * @param string $additionalDetails the additional information of CC and BCC appended to the activity Details
6a488035
TO
1157 *
1158 * @return array ( sent, activityId) if any email is sent and activityId
1159 * @access public
1160 * @static
1161 */
1162 static function sendEmail(
1163 &$contactDetails,
1164 &$subject,
1165 &$text,
1166 &$html,
1167 $emailAddress,
1168 $userID = NULL,
1169 $from = NULL,
1170 $attachments = NULL,
1171 $cc = NULL,
1172 $bcc = NULL,
c1d26519 1173 $contactIds, // FIXME a param with no default shouldn't be last
1174 $additionalDetails = NULL
6a488035
TO
1175 ) {
1176 // get the contact details of logged in contact, which we set as from email
1177 if ($userID == NULL) {
1178 $session = CRM_Core_Session::singleton();
1179 $userID = $session->get('userID');
1180 }
1181
1182 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1183 if (!$fromEmail) {
1184 return array(count($contactDetails), 0, count($contactDetails));
1185 }
1186 if (!trim($fromDisplayName)) {
1187 $fromDisplayName = $fromEmail;
1188 }
1189
1190 // CRM-4575
1191 // token replacement of addressee/email/postal greetings
1192 // get the tokens added in subject and message
1193 $subjectToken = CRM_Utils_Token::getTokens($subject);
1194 $messageToken = CRM_Utils_Token::getTokens($text);
1195 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1196
1197 if (!$from) {
1198 $from = "$fromDisplayName <$fromEmail>";
1199 }
1200
1201 //create the meta level record first ( email activity )
1202 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1203 'Email',
1204 'name'
1205 );
1206
1207 // CRM-6265: save both text and HTML parts in details (if present)
1208 if ($html and $text) {
c1d26519 1209 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
6a488035
TO
1210 }
1211 else {
1212 $details = $html ? $html : $text;
c1d26519 1213 $details .= $additionalDetails;
6a488035
TO
1214 }
1215
1216 $activityParams = array(
1217 'source_contact_id' => $userID,
1218 'activity_type_id' => $activityTypeID,
1219 'activity_date_time' => date('YmdHis'),
1220 'subject' => $subject,
1221 'details' => $details,
1222 // FIXME: check for name Completed and get ID from that lookup
1223 'status_id' => 2,
1224 );
1225
1226 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1227 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1228
1229 // add the attachments to activity params here
1230 if ($attachments) {
1231 // first process them
1232 $activityParams = array_merge($activityParams,
1233 $attachments
1234 );
1235 }
1236
1237 $activity = self::create($activityParams);
1238
1239 // get the set of attachments from where they are stored
1240 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity',
1241 $activity->id
1242 );
1243 $returnProperties = array();
1244 if (isset($messageToken['contact'])) {
1245 foreach ($messageToken['contact'] as $key => $value) {
1246 $returnProperties[$value] = 1;
1247 }
1248 }
1249
1250 if (isset($subjectToken['contact'])) {
1251 foreach ($subjectToken['contact'] as $key => $value) {
1252 if (!isset($returnProperties[$value])) {
1253 $returnProperties[$value] = 1;
1254 }
1255 }
1256 }
1257
1258
1259 // get token details for contacts, call only if tokens are used
1260 $details = array();
1261 if (!empty($returnProperties)) {
1262 list($details) = CRM_Utils_Token::getTokenDetails(
1263 $contactIds,
1264 $returnProperties,
1265 NULL, NULL, FALSE,
1266 $messageToken,
1267 'CRM_Activity_BAO_Activity'
1268 );
1269 }
1270
1271 // call token hook
1272 $tokens = array();
1273 CRM_Utils_Hook::tokens($tokens);
1274 $categories = array_keys($tokens);
1275
1276 $escapeSmarty = FALSE;
1277 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1278 $smarty = CRM_Core_Smarty::singleton();
1279 $escapeSmarty = TRUE;
1280 }
1281
1282 $sent = $notSent = array();
1283 foreach ($contactDetails as $values) {
1284 $contactId = $values['contact_id'];
1285 $emailAddress = $values['email'];
1286
1287 if (!empty($details) && is_array($details["{$contactId}"])) {
1288 // unset email from details since it always returns primary email address
1289 unset($details["{$contactId}"]['email']);
1290 unset($details["{$contactId}"]['email_id']);
1291 $values = array_merge($values, $details["{$contactId}"]);
1292 }
1293
1294 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1295 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1296
1297 //CRM-4539
1298 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1299 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1300 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1301 }
1302 else {
1303 $tokenText = NULL;
1304 }
1305
1306 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1307 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1308 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1309 }
1310 else {
1311 $tokenHtml = NULL;
1312 }
1313
1314 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1315 // also add the contact tokens to the template
1316 $smarty->assign_by_ref('contact', $values);
1317
1318 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1319 $tokenText = $smarty->fetch("string:$tokenText");
1320 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1321 }
1322
1323 $sent = FALSE;
1324 if (self::sendMessage(
1325 $from,
1326 $userID,
1327 $contactId,
1328 $tokenSubject,
1329 $tokenText,
1330 $tokenHtml,
1331 $emailAddress,
1332 $activity->id,
1333 $attachments,
1334 $cc,
1335 $bcc
1336 )) {
1337 $sent = TRUE;
1338 }
1339 }
1340
1341 return array($sent, $activity->id);
1342 }
1343
1344 static function sendSMS(&$contactDetails,
1345 &$activityParams,
1346 &$smsParams = array(),
1347 &$contactIds,
1348 $userID = NULL
1349 ) {
1350 if ($userID == NULL) {
1351 $session = CRM_Core_Session::singleton();
1352 $userID = $session->get('userID');
1353 }
1354
1355 $text = &$activityParams['text_message'];
1356 $html = &$activityParams['html_message'];
1357
1358 // CRM-4575
1359 // token replacement of addressee/email/postal greetings
1360 // get the tokens added in subject and message
1361 $messageToken = CRM_Utils_Token::getTokens($text);
1362 $messageToken = array_merge($messageToken,
1363 CRM_Utils_Token::getTokens($html)
1364 );
1365
1366 //create the meta level record first ( sms activity )
1367 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1368 'SMS',
1369 'name'
1370 );
1371
1372 // CRM-6265: save both text and HTML parts in details (if present)
1373 if ($html and $text) {
1374 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1375 }
1376 else {
1377 $details = $html ? $html : $text;
1378 }
1379
1380 $activitySubject = $activityParams['activity_subject'];
1381 $activityParams = array(
1382 'source_contact_id' => $userID,
1383 'activity_type_id' => $activityTypeID,
1384 'activity_date_time' => date('YmdHis'),
1385 'subject' => $activitySubject,
1386 'details' => $details,
1387 // FIXME: check for name Completed and get ID from that lookup
1388 'status_id' => 2,
1389 );
1390
1391 $activity = self::create($activityParams);
1392 $activityID = $activity->id;
1393
1394 $returnProperties = array();
1395
1396 if (isset($messageToken['contact'])) {
1397 foreach ($messageToken['contact'] as $key => $value) {
1398 $returnProperties[$value] = 1;
1399 }
1400 }
1401
1402 // call token hook
1403 $tokens = array();
1404 CRM_Utils_Hook::tokens($tokens);
1405 $categories = array_keys($tokens);
1406
1407 // get token details for contacts, call only if tokens are used
1408 $details = array();
1409 if (!empty($returnProperties) || !empty($tokens)) {
1410 list($details) = CRM_Utils_Token::getTokenDetails($contactIds,
1411 $returnProperties,
1412 NULL, NULL, FALSE,
1413 $messageToken,
1414 'CRM_Activity_BAO_Activity'
1415 );
1416 }
1417
f53ea1ce 1418 $success = 0;
c5a6413b
DS
1419 $escapeSmarty = FALSE;
1420 $errMsgs = array();
6a488035
TO
1421 foreach ($contactDetails as $values) {
1422 $contactId = $values['contact_id'];
1423
1424 if (!empty($details) && is_array($details["{$contactId}"])) {
1425 // unset email from details since it always returns primary email address
1426 unset($details["{$contactId}"]['email']);
1427 unset($details["{$contactId}"]['email_id']);
1428 $values = array_merge($values, $details["{$contactId}"]);
1429 }
1430
1431 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1432 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1433
1434 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1435 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1436
d65e1a68 1437 // Only send if the phone is of type mobile
9357a775
DS
1438 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1439 if ($values['phone_type_id'] == CRM_Utils_Array::value('Mobile', $phoneTypes)) {
d65e1a68 1440 $smsParams['To'] = $values['phone'];
01aca362
DL
1441 }
1442 else {
d65e1a68
TW
1443 $smsParams['To'] = '';
1444 }
6a488035 1445
c5a6413b
DS
1446 $sendResult = self::sendSMSMessage(
1447 $contactId,
1448 $tokenText,
1449 $tokenHtml,
1450 $smsParams,
e8cb3963
DS
1451 $activityID,
1452 $userID
c5a6413b
DS
1453 );
1454
1455 if (PEAR::isError($sendResult)) {
1456 // Collect all of the PEAR_Error objects
1457 $errMsgs[] = $sendResult;
1458 } else {
f53ea1ce 1459 $success++;
6a488035
TO
1460 }
1461 }
1462
c5a6413b
DS
1463 // If at least one message was sent and no errors
1464 // were generated then return a boolean value of TRUE.
1465 // Otherwise, return FALSE (no messages sent) or
1466 // and array of 1 or more PEAR_Error objects.
1467 $sent = FALSE;
1468 if ($success > 0 && count($errMsgs) == 0) {
1469 $sent = TRUE;
1470 } elseif (count($errMsgs) > 0) {
1471 $sent = $errMsgs;
1472 }
1473
f53ea1ce 1474 return array($sent, $activity->id, $success);
6a488035
TO
1475 }
1476
1477 /**
1478 * send the sms message to a specific contact
1479 *
1480 * @param int $toID the contact id of the recipient
1481 * @param int $activityID the activity ID that tracks the message
1482 * @param array $smsParams the params used for sending sms
1483 *
c5a6413b 1484 * @return mixed true on success or PEAR_Error object
6a488035
TO
1485 * @access public
1486 * @static
1487 */
1488 static function sendSMSMessage($toID,
1489 &$tokenText,
1490 &$tokenHtml,
1491 $smsParams = array(),
e8cb3963
DS
1492 $activityID,
1493 $userID = null
6a488035
TO
1494 ) {
1495 $toDoNotSms = "";
1496 $toPhoneNumber = "";
1497
1498 if ($smsParams['To']) {
1499 $toPhoneNumber = trim($smsParams['To']);
1500 }
1501 elseif ($toID) {
1502 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1503 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
1504 //to get primary mobile ph,if not get a first mobile ph
1505 if (!empty($toPhoneNumbers)) {
1506 $toPhoneNumerDetails = reset($toPhoneNumbers);
1507 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumerDetails);
1508 //contact allows to send sms
1509 $toDoNotSms = 0;
1510 }
1511 }
1512
1513 // make sure both phone are valid
1514 // and that the recipient wants to receive sms
1515 if (empty($toPhoneNumber) or $toDoNotSms) {
c5a6413b
DS
1516 return PEAR::raiseError(
1517 'Recipient phone number is invalid or recipient does not want to receive SMS',
1518 null,
1519 PEAR_ERROR_RETURN
1520 );
6a488035
TO
1521 }
1522
1523 $message = $tokenHtml ? $tokenHtml : $tokenText;
1524 $recipient = $smsParams['To'];
1525 $smsParams['contact_id'] = $toID;
1526 $smsParams['parent_activity_id'] = $activityID;
1527
1528 $providerObj = CRM_SMS_Provider::singleton(array('provider_id' => $smsParams['provider_id']));
e8cb3963 1529 $sendResult = $providerObj->send($recipient, $smsParams, $message, NULL, $userID);
c5a6413b
DS
1530 if (PEAR::isError($sendResult)) {
1531 return $sendResult;
6a488035
TO
1532 }
1533
e7e657f0 1534 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 1535 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
b319d00a 1536
a24b3694 1537
6a488035
TO
1538 // add activity target record for every sms that is send
1539 $activityTargetParams = array(
1540 'activity_id' => $activityID,
1d85d241 1541 'contact_id' => $toID,
a24b3694 1542 'record_type_id' => $targetID
6a488035 1543 );
1d85d241 1544 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
6a488035
TO
1545
1546 return TRUE;
1547 }
1548
1549 /**
1550 * send the message to a specific contact
1551 *
1552 * @param string $from the name and email of the sender
1553 * @param int $toID the contact id of the recipient
1554 * @param string $subject the subject of the message
1555 * @param string $message the message contents
1556 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1557 * @param int $activityID the activity ID that tracks the message
1558 *
1559 * @return boolean true if successfull else false.
1560 * @access public
1561 * @static
1562 */
1563 static function sendMessage($from,
1564 $fromID,
1565 $toID,
1566 &$subject,
1567 &$text_message,
1568 &$html_message,
1569 $emailAddress,
1570 $activityID,
1571 $attachments = NULL,
1572 $cc = NULL,
1573 $bcc = NULL
1574 ) {
1575 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1576 if ($emailAddress) {
1577 $toEmail = trim($emailAddress);
1578 }
1579
1580 // make sure both email addresses are valid
1581 // and that the recipient wants to receive email
1582 if (empty($toEmail) or $toDoNotEmail) {
1583 return FALSE;
1584 }
1585 if (!trim($toDisplayName)) {
1586 $toDisplayName = $toEmail;
1587 }
1588
e7e657f0 1589 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 1590 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1591 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1592 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1593
6a488035
TO
1594 // create the params array
1595 $mailParams = array(
1596 'groupName' => 'Activity Email Sender',
1597 'from' => $from,
1598 'toName' => $toDisplayName,
1599 'toEmail' => $toEmail,
1600 'subject' => $subject,
1601 'cc' => $cc,
1602 'bcc' => $bcc,
1603 'text' => $text_message,
1604 'html' => $html_message,
1605 'attachments' => $attachments,
1606 );
1607
1608 if (!CRM_Utils_Mail::send($mailParams)) {
1609 return FALSE;
1610 }
1611
1612 // add activity target record for every mail that is send
1613 $activityTargetParams = array(
1614 'activity_id' => $activityID,
1d85d241 1615 'contact_id' => $toID,
b319d00a 1616 'record_type_id' => $targetID
6a488035 1617 );
1d85d241 1618 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
6a488035
TO
1619 return TRUE;
1620 }
1621
1622 /**
1623 * combine all the importable fields from the lower levels object
1624 *
1625 * The ordering is important, since currently we do not have a weight
1626 * scheme. Adding weight is super important and should be done in the
1627 * next week or so, before this can be called complete.
1628 *
1629 * @param NULL
1630 *
1631 * @return array array of importable Fields
1632 * @access public
1633 * @static
1634 */
1635 static function &importableFields($status = FALSE) {
1636 if (!self::$_importableFields) {
1637 if (!self::$_importableFields) {
1638 self::$_importableFields = array();
1639 }
1640 if (!$status) {
1641 $fields = array('' => array('title' => ts('- do not import -')));
1642 }
1643 else {
1644 $fields = array('' => array('title' => ts('- Activity Fields -')));
1645 }
1646
1647 $tmpFields = CRM_Activity_DAO_Activity::import();
1648 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1649
1650 // Using new Dedupe rule.
1651 $ruleParams = array(
1652 'contact_type' => 'Individual',
1653 'used' => 'Unsupervised',
1654 );
1655 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1656
1657 $tmpConatctField = array();
1658 if (is_array($fieldsArray)) {
1659 foreach ($fieldsArray as $value) {
1660 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1661 $value,
1662 'id',
1663 'column_name'
1664 );
1665 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1666 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1667 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1668 }
1669 }
1670 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1671 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1672 $fields = array_merge($fields, $tmpConatctField);
1673 $fields = array_merge($fields, $tmpFields);
1674 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
1675 self::$_importableFields = $fields;
1676 }
1677 return self::$_importableFields;
1678 }
1679
1680 /**
1681 * To get the Activities of a target contact
1682 *
1683 * @param $contactId Integer ContactId of the contact whose activities
1684 * need to find
1685 *
1686 * @return array array of activity fields
1687 * @access public
1688 */
1689 static function getContactActivity($contactId) {
1690 $activities = array();
e7e657f0 1691 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
a24b3694 1692 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1693 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1694 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
b319d00a 1695
6a488035
TO
1696
1697 // First look for activities where contactId is one of the targets
91da6cd5 1698 $query = "
a24b3694 1699SELECT activity_id, record_type_id
91da6cd5
DL
1700FROM civicrm_activity_contact
1701WHERE contact_id = $contactId
1702";
1703 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 1704 while ($dao->fetch()) {
a24b3694 1705 if ($dao->record_type_id == $targetID ) {
91da6cd5
DL
1706 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
1707 }
a24b3694 1708 else if ($dao->record_type_id == $assigneeID) {
91da6cd5
DL
1709 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1710 }
1711 else {
1712 // do source stuff here
42d30b83 1713 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
91da6cd5 1714 }
6a488035
TO
1715 }
1716
91da6cd5 1717 $activityIds = array_keys($activities);
6a488035
TO
1718 if (count($activityIds) < 1) {
1719 return array();
1720 }
91da6cd5 1721
6a488035 1722 $activityIds = implode(',', $activityIds);
91da6cd5
DL
1723 $query = "
1724SELECT activity.id as activity_id,
1725 activity_type_id,
1726 subject, location, activity_date_time, details, status_id
1727FROM civicrm_activity activity
1728WHERE activity.id IN ($activityIds)";
6a488035 1729
91da6cd5 1730 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1731
1732 $activityTypes = CRM_Core_OptionGroup::values('activity_type');
1733 $activityStatuses = CRM_Core_OptionGroup::values('activity_status');
1734
1735 while ($dao->fetch()) {
6a488035 1736 $activities[$dao->activity_id]['id'] = $dao->activity_id;
6a488035
TO
1737 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
1738 $activities[$dao->activity_id]['subject'] = $dao->subject;
1739 $activities[$dao->activity_id]['location'] = $dao->location;
1740 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
1741 $activities[$dao->activity_id]['details'] = $dao->details;
1742 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
1743 $activities[$dao->activity_id]['activity_name'] = $activityTypes[$dao->activity_type_id];
1744 $activities[$dao->activity_id]['status'] = $activityStatuses[$dao->status_id];
42d30b83
DL
1745
1746 // set to null if not set
1747 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
1748 $activities[$dao->activity_id]['source_contact_id'] = NULL;
1749 }
6a488035
TO
1750 }
1751 return $activities;
1752 }
1753
1754 /**
1755 * Function to add activity for Membership/Event/Contribution
1756 *
0a9f61c4 1757 * @param object $activity (reference) particular component object
6a488035
TO
1758 * @param string $activityType for Membership Signup or Renewal
1759 *
1760 *
1761 * @static
1762 * @access public
1763 */
1764 static function addActivity(&$activity,
1765 $activityType = 'Membership Signup',
1766 $targetContactID = NULL
1767 ) {
1768 if ($activity->__table == 'civicrm_membership') {
1769 $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id);
1770
1771 if (!$membershipType) {
1772 $membershipType = ts('Membership');
1773 }
1774
1775 $subject = "{$membershipType}";
1776
1777 if (!empty($activity->source) && $activity->source != 'null') {
1778 $subject .= " - {$activity->source}";
1779 }
1780
1781 if ($activity->owner_membership_id) {
1782 $query = "
1783SELECT display_name
1784 FROM civicrm_contact, civicrm_membership
1785 WHERE civicrm_contact.id = civicrm_membership.contact_id
1786 AND civicrm_membership.id = $activity->owner_membership_id
1787";
1788 $displayName = CRM_Core_DAO::singleValueQuery($query);
1789 $subject .= " (by {$displayName})";
1790 }
1791
1792 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id);
1793 // CRM-72097 changed from start date to today
1794 $date = date('YmdHis');
1795 $component = 'Membership';
1796 }
1797 elseif ($activity->__table == 'civicrm_participant') {
c2be40dc 1798 $event = CRM_Event_BAO_Event::getEvents(1, $activity->event_id, TRUE, FALSE);
6a488035
TO
1799
1800 $roles = CRM_Event_PseudoConstant::participantRole();
1801 $status = CRM_Event_PseudoConstant::participantStatus();
1802
1803 $subject = $event[$activity->event_id];
1804 if (CRM_Utils_Array::value($activity->role_id, $roles)) {
1805 $subject .= ' - ' . $roles[$activity->role_id];
1806 }
1807 if (CRM_Utils_Array::value($activity->status_id, $status)) {
1808 $subject .= ' - ' . $status[$activity->status_id];
1809 }
1810 $date = date('YmdHis');
1811 if ($activityType != 'Email') {
1812 $activityType = 'Event Registration';
1813 }
1814 $component = 'Event';
1815 }
1816 elseif ($activity->__table == 'civicrm_contribution') {
1817 //create activity record only for Completed Contributions
1818 if ($activity->contribution_status_id != 1) {
1819 return;
1820 }
1821
1822 $subject = NULL;
1823
1824 $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency);
1825 if (!empty($activity->source) && $activity->source != 'null') {
1826 $subject .= " - {$activity->source}";
1827 }
1828 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
1829 $activityType = $component = 'Contribution';
1830 }
1831 $activityParams = array(
1832 'source_contact_id' => $activity->contact_id,
1833 'source_record_id' => $activity->id,
1834 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1835 $activityType,
1836 'name'
1837 ),
1838 'subject' => $subject,
1839 'activity_date_time' => $date,
1840 'is_test' => $activity->is_test,
1841 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
1842 'Completed',
1843 'name'
1844 ),
1845 'skipRecentView' => TRUE,
1846 'campaign_id' => $activity->campaign_id,
1847 );
1848
1849 // create activity with target contacts
1850 $session = CRM_Core_Session::singleton();
1851 $id = $session->get('userID');
1852 if ($id) {
1853 $activityParams['source_contact_id'] = $id;
1854 $activityParams['target_contact_id'][] = $activity->contact_id;
1855 }
1856
1857 //CRM-4027
1858 if ($targetContactID) {
1859 $activityParams['target_contact_id'][] = $targetContactID;
1860 }
1861 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
1862 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
1863 return FALSE;
1864 }
1865 }
1866
1867 /**
0a9f61c4 1868 * Function to get Parent activity for currently viewed activity
6a488035
TO
1869 *
1870 * @param int $activityId current activity id
1871 *
0a9f61c4 1872 * @return int $parentId Id of parent activity otherwise false.
6a488035
TO
1873 * @access public
1874 */
1875 static function getParentActivity($activityId) {
1876 static $parentActivities = array();
1877
1878 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1879
1880 if (!array_key_exists($activityId, $parentActivities)) {
1881 $parentActivities[$activityId] = array();
1882
1883 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1884 $activityId,
1885 'parent_id'
1886 );
1887
1888 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1889 }
1890
1891 return $parentActivities[$activityId];
1892 }
1893
1894 /**
1895 * Function to get total count of prior revision of currently viewd activity
1896 *
1897 * @param int $activityId current activity id
1898 *
0a9f61c4 1899 * @return int $params count of prior activities otherwise false.
6a488035
TO
1900 * @access public
1901 */
1902 static function getPriorCount($activityID) {
1903 static $priorCounts = array();
1904
1905 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1906
1907 if (!array_key_exists($activityID, $priorCounts)) {
1908 $priorCounts[$activityID] = array();
1909 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1910 $activityID,
1911 'original_id'
1912 );
1913 $count = 0;
1914 if ($originalID) {
1915 $query = "
1916SELECT count( id ) AS cnt
1917FROM civicrm_activity
1918WHERE ( id = {$originalID} OR original_id = {$originalID} )
1919AND is_current_revision = 0
1920AND id < {$activityID}
1921";
1922 $params = array(1 => array($originalID, 'Integer'));
1923 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1924 }
1925 $priorCounts[$activityID] = $count ? $count : 0;
1926 }
1927
1928 return $priorCounts[$activityID];
1929 }
1930
1931 /**
0a9f61c4 1932 * Function to get all prior activities of currently viewe
1933 * d activity
6a488035
TO
1934 *
1935 * @param int $activityId current activity id
1936 *
0a9f61c4 1937 * @return array $result prior activities info.
6a488035
TO
1938 * @access public
1939 */
1940 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1941 static $priorActivities = array();
1942
1943 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1944 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1945
1946 if (!array_key_exists($index, $priorActivities)) {
1947 $priorActivities[$index] = array();
1948
1949 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1950 $activityID,
1951 'original_id'
1952 );
1953 if ($originalID) {
1954 $query = "
1955SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1956FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1957WHERE (ca.id = %1 OR ca.original_id = %1)
1958AND cl.entity_table = 'civicrm_activity'
1959AND cl.entity_id = ca.id
1960AND cl.modified_id = c.id
1961";
1962 if ($onlyPriorRevisions) {
1963 $query .= " AND ca.id < {$activityID}";
1964 }
1965 $query .= " ORDER BY ca.id DESC";
1966
1967 $params = array(1 => array($originalID, 'Integer'));
1968 $dao = CRM_Core_DAO::executeQuery($query, $params);
1969
1970 while ($dao->fetch()) {
1971 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
1972 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
1973 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
1974 $priorActivities[$index][$dao->activityID]['link'] = 'javascript:viewActivity( $dao->activityID );';
1975 }
1976 $dao->free();
1977 }
1978 }
1979 return $priorActivities[$index];
1980 }
1981
1982 /**
1983 * Function to find the latest revision of a given activity
1984 *
1985 * @param int $activityId prior activity id
1986 *
1987 * @return int $params current activity id.
1988 * @access public
1989 */
1990 static function getLatestActivityId($activityID) {
1991 static $latestActivityIds = array();
1992
1993 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1994
1995 if (!array_key_exists($activityID, $latestActivityIds)) {
1996 $latestActivityIds[$activityID] = array();
1997
1998 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1999 $activityID,
2000 'original_id'
2001 );
2002 if ($originalID) {
2003 $activityID = $originalID;
2004 }
2005 $params = array(1 => array($activityID, 'Integer'));
2006 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2007
2008 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
2009 }
2010
2011 return $latestActivityIds[$activityID];
2012 }
2013
2014 /**
2015 * Function to create a follow up a given activity
2016 *
2017 * @activityId int activity id of parent activity
2018 *
2019 * @param array $activity details
2020 *
2021 * @access public
2022 */
2023 static function createFollowupActivity($activityId, $params) {
2024 if (!$activityId) {
2025 return;
2026 }
2027
2028 $session = CRM_Core_Session::singleton();
2029
2030 $followupParams = array();
2031 $followupParams['parent_id'] = $activityId;
2032 $followupParams['source_contact_id'] = $session->get('userID');
2033 $followupParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
2034
2035 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2036 // Get Subject of Follow-up Activiity, CRM-4491
2037 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
2038
2039 //create target contact for followup
2040 if (CRM_Utils_Array::value('target_contact_id', $params)) {
2041 $followupParams['target_contact_id'] = $params['target_contact_id'];
2042 }
2043
2044 $followupParams['activity_date_time'] = CRM_Utils_Date::processDate($params['followup_date'],
2045 $params['followup_date_time']
2046 );
2047 $followupActivity = self::create($followupParams);
2048
2049 return $followupActivity;
2050 }
2051
2052 /**
2053 * Function to get Activity specific File according activity type Id.
2054 *
2055 * @param int $activityTypeId activity id
2056 *
2057 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2058 *
2059 * @static
2060 */
2061 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2062 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2063
2064 if ($activityTypes[$activityTypeId]['name']) {
2065 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2066 }
2067 else {
2068 return FALSE;
2069 }
2070
2071 global $civicrm_root;
2072 $config = CRM_Core_Config::singleton();
2073 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2074 if (empty($config->customPHPPathDir)) {
2075 return FALSE;
2076 }
2077 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2078 return FALSE;
2079 }
2080 }
2081
2082 return $activityTypeFile;
2083 }
2084
2085 /**
2086 * Function to restore the activity
2087 *
2088 * @param array $params associated array
2089 *
2090 * @return void
2091 * @access public
2092 *
2093 */
2094 public static function restoreActivity(&$params) {
2095 $activity = new CRM_Activity_DAO_Activity();
2096 $activity->copyValues($params);
2097
2098 $activity->is_deleted = 0;
2099 $result = $activity->save();
2100
2101 return $result;
2102 }
2103
2104 /**
2105 * Get the exportable fields for Activities
2106 *
2107 * @param string $name if it is called by case $name = Case else $name = Activity
2108 *
2109 * @return array array of exportable Fields
2110 * @access public
2111 * @static
2112 */
2113 static function &exportableFields($name = 'Activity') {
2114 if (!isset(self::$_exportableFields[$name])) {
2115 self::$_exportableFields[$name] = array();
2116
2117 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2118 // my case hence we have defined fields as case_*
2119 if ($name == 'Activity') {
2120 $exportableFields = CRM_Activity_DAO_Activity::export();
2121 if (isset($exportableFields['activity_campaign_id'])) {
2122 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2123 }
2124 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2125 $exportableFields['source_contact'] = array(
2126 'title' => ts('Source Contact'),
2127 'type' => CRM_Utils_Type::T_STRING,
2128 );
2129
2130
2131 $Activityfields = array(
2132 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2133 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2134 );
2135 $fields = array_merge($Activityfields, $exportableFields);
2136 }
2137 else {
2138 //set title to activity fields
2139 $fields = array(
2140 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
2141 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
2142 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
2143 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type::T_DATE),
2144 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2145 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2146 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
2147 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
2148 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
2149 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type::T_BOOLEAN),
2150 );
2151
2152 // add custom data for cases
2153 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Case'));
2154 }
2155
2156 // add custom data for case activities
2157 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2158
2159 self::$_exportableFields[$name] = $fields;
2160 }
2161 return self::$_exportableFields[$name];
2162 }
2163
2164 /**
2165 * Get the allowed profile fields for Activities
2166 *
2167 * @return array array of activity profile Fields
2168 * @access public
2169 */
2170 static function getProfileFields() {
2171 $exportableFields = self::exportableFields('Activity');
4f79a2f5 2172 $skipFields = array(
2173 'activity_id',
2174 'activity_type',
2175 'source_contact_id',
2176 'source_contact',
2177 'activity_campaign',
2178 'activity_is_test',
2179 'is_current_revision',
2180 'activity_is_deleted',
2181 );
6a488035
TO
2182 $config = CRM_Core_Config::singleton();
2183 if (!in_array('CiviCampaign', $config->enableComponents)) {
2184 $skipFields[] = 'activity_engagement_level';
2185 }
2186
2187 foreach ($skipFields as $field) {
2188 if (isset($exportableFields[$field])) {
2189 unset($exportableFields[$field]);
2190 }
2191 }
2192
2193 // hack to use 'activity_type_id' instead of 'activity_type'
2194 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2195 unset($exportableFields['activity_status']);
2196
2197 return $exportableFields;
2198 }
2199
2200 /**
2201 * This function delete activity record related to contact record,
2202 * when there are no target and assignee record w/ other contact.
2203 *
2204 * @param int $contactId contactId
2205 *
2206 * @return true/null
2207 * @access public
2208 */
2209 public static function cleanupActivity($contactId) {
2210 $result = NULL;
2211 if (!$contactId) {
2212 return $result;
2213 }
e7e657f0 2214 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2bf96211 2215 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
6a488035
TO
2216
2217 $transaction = new CRM_Core_Transaction();
2218
1d85d241
DL
2219 // delete activity if there is no record in
2220 // civicrm_activity_contact
6a488035 2221 // pointing to any other contact record.
2bf96211 2222 $activityContact = new CRM_Activity_DAO_ActivityContact();
2223 $activityContact->contact_id = $contactId;
2224 $activityContact->record_type_id = $sourceID;
2225 $activityContact->find();
6a488035 2226
2bf96211 2227 while ($activityContact->fetch()) {
6a488035 2228 // finally delete activity.
2d66ec23
RN
2229 $activityParams = array('id' => $activityContact->activity_id);
2230 $result = self::deleteActivity($activityParams);
6a488035 2231 }
6a488035 2232
2bf96211 2233 $activityContact->free();
6a488035
TO
2234 $transaction->commit();
2235
2236 return $result;
2237 }
2238
2239 /**
2240 * Does user has sufficient permission for view/edit activity record.
2241 *
2242 * @param int $activityId activity record id.
2243 * @param int $action edit/view
2244 *
2245 * @return boolean $allow true/false
2246 * @access public
2247 */
2248 public static function checkPermission($activityId, $action) {
2249 $allow = FALSE;
2250 if (!$activityId ||
2251 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2252 ) {
2253 return $allow;
2254 }
2255
2256 $activity = new CRM_Activity_DAO_Activity();
2257 $activity->id = $activityId;
2258 if (!$activity->find(TRUE)) {
2259 return $allow;
2260 }
2261
2262 //component related permissions.
2263 $compPermissions = array(
2264 'CiviCase' => array('administer CiviCase',
2265 'access my cases and activities',
2266 'access all cases and activities',
2267 ),
2268 'CiviMail' => array('access CiviMail'),
2269 'CiviEvent' => array('access CiviEvent'),
2270 'CiviGrant' => array('access CiviGrant'),
2271 'CiviPledge' => array('access CiviPledge'),
2272 'CiviMember' => array('access CiviMember'),
2273 'CiviReport' => array('access CiviReport'),
2274 'CiviContribute' => array('access CiviContribute'),
2275 'CiviCampaign' => array('administer CiviCampaign'),
2276 );
2277
2278 //return early when it is case activity.
2279 $isCaseActivity = CRM_Case_BAO_Case::isCaseActivity($activityId);
2280 //check for civicase related permission.
2281 if ($isCaseActivity) {
2282 $allow = FALSE;
2283 foreach ($compPermissions['CiviCase'] as $per) {
2284 if (CRM_Core_Permission::check($per)) {
2285 $allow = TRUE;
2286 break;
2287 }
2288 }
2289
2290 //check for case specific permissions.
2291 if ($allow) {
2292 $oper = 'view';
2293 if ($action == CRM_Core_Action::UPDATE) {
2294 $oper = 'edit';
2295 }
2296 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2297 $oper,
2298 $activity->activity_type_id
2299 );
2300 }
2301
2302 return $allow;
2303 }
2304
6a488035
TO
2305 //first check the component permission.
2306 $sql = "
2307 SELECT component_id
2308 FROM civicrm_option_value val
2309INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2310 WHERE val.value = %2";
2311 $params = array(1 => array('activity_type', 'String'),
2312 2 => array($activity->activity_type_id, 'Integer'),
2313 );
2314 $componentId = CRM_Core_DAO::singleValueQuery($sql, $params);
2315
2316 if ($componentId) {
2317 $componentName = CRM_Core_Component::getComponentName($componentId);
2318 $compPermission = CRM_Utils_Array::value($componentName, $compPermissions);
2319
2320 //here we are interesting in any single permission.
2321 if (is_array($compPermission)) {
2322 foreach ($compPermission as $per) {
2323 if (CRM_Core_Permission::check($per)) {
2324 $allow = TRUE;
2325 break;
2326 }
2327 }
2328 }
2329 }
2330
2331 //check for this permission related to contact.
2332 $permission = CRM_Core_Permission::VIEW;
2333 if ($action == CRM_Core_Action::UPDATE) {
2334 $permission = CRM_Core_Permission::EDIT;
2335 }
2336
e7e657f0 2337 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
034500d4 2338 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2339 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2340 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2341
6a488035
TO
2342 //check for source contact.
2343 if (!$componentId || $allow) {
65ebc887 2344 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2345 $allow = CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission);
6a488035
TO
2346 }
2347
2348 //check for target and assignee contacts.
2349 if ($allow) {
2350 //first check for supper permission.
2351 $supPermission = 'view all contacts';
2352 if ($action == CRM_Core_Action::UPDATE) {
2353 $supPermission = 'edit all contacts';
2354 }
2355 $allow = CRM_Core_Permission::check($supPermission);
2356
2357 //user might have sufficient permission, through acls.
2358 if (!$allow) {
2359 $allow = TRUE;
2360 //get the target contacts.
034500d4 2361 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
6a488035
TO
2362 foreach ($targetContacts as $cnt => $contactId) {
2363 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2364 $allow = FALSE;
2365 break;
2366 }
2367 }
2368
2369 //get the assignee contacts.
2370 if ($allow) {
034500d4 2371 $assigneeContacts = CRM_Activity_BAO_Contact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
6a488035
TO
2372 foreach ($assigneeContacts as $cnt => $contactId) {
2373 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2374 $allow = FALSE;
2375 break;
2376 }
2377 }
2378 }
2379 }
2380 }
2381
2382 return $allow;
2383 }
2384
2385 /**
2386 * This function is a wrapper for ajax activity selector
2387 *
2388 * @param array $params associated array for params record id.
2389 *
2390 * @return array $contactActivities associated array of contact activities
2391 * @access public
2392 */
2393 public static function getContactActivitySelector(&$params) {
2394 // format the params
2395 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2396 $params['rowCount'] = $params['rp'];
2397 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2398 $params['caseId'] = NULL;
2399 $context = CRM_Utils_Array::value('context', $params);
2400
2401 // get contact activities
2402 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2403
2404 // add total
2405 $params['total'] = CRM_Activity_BAO_Activity::getActivitiesCount($params);
2406
2407 // format params and add links
2408 $contactActivities = array();
2409
2410 if (!empty($activities)) {
2411 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2412
2413 // check logged in user for permission
2414 $page = new CRM_Core_Page();
2415 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2416 $permissions = array($page->_permission);
2417 if (CRM_Core_Permission::check('delete activities')) {
2418 $permissions[] = CRM_Core_Permission::DELETE;
2419 }
2420
2421 $mask = CRM_Core_Action::mask($permissions);
2422
2423 foreach ($activities as $activityId => $values) {
2424 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2425 $contactActivities[$activityId]['subject'] = $values['subject'];
2426 if ($params['contact_id'] == $values['source_contact_id']) {
2427 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2428 }
2429 elseif ($values['source_contact_id']) {
5a99d240
KJ
2430 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System::href($values['source_contact_name'],
2431 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
6a488035
TO
2432 }
2433 else {
2434 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2435 }
2436
2437 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
5a99d240
KJ
2438 $contactActivities[$activityId]['target_contact'] = CRM_Utils_System::href($values['recipients'],
2439 'civicrm/mailing/report/event',
2440 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
6a488035
TO
2441 }
2442 elseif (CRM_Utils_Array::value('recipients', $values)) {
2443 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2444 }
2445 elseif (!$values['target_contact_name']) {
2446 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2447 }
2448 elseif (!empty($values['target_contact_name'])) {
2449 $count = 0;
2450 $contactActivities[$activityId]['target_contact'] = '';
2451 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2452 if ($tcID && $count < 5) {
5a99d240
KJ
2453 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System::href($tcName,
2454 'civicrm/contact/view', "reset=1&cid={$tcID}");
6a488035
TO
2455 $count++;
2456 if ($count) {
2457 $contactActivities[$activityId]['target_contact'] .= ";&nbsp;";
2458 }
2459
2460 if ($count == 4) {
2461 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2462 break;
2463 }
2464 }
2465 }
2466 }
2467
2468 if (empty($values['assignee_contact_name'])) {
2469 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2470 }
2471 elseif (!empty($values['assignee_contact_name'])) {
2472 $count = 0;
2473 $contactActivities[$activityId]['assignee_contact'] = '';
2474 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2475 if ($acID && $count < 5) {
2476 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2477 $count++;
2478 if ($count) {
2479 $contactActivities[$activityId]['assignee_contact'] .= ";&nbsp;";
2480 }
2481
2482 if ($count == 4) {
2483 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2484 break;
2485 }
2486 }
2487 }
2488 }
6a488035
TO
2489
2490 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2491 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2492
2493 // add class to this row if overdue
2494 $contactActivities[$activityId]['class'] = '';
2495 if (CRM_Utils_Date::overdue(CRM_Utils_Array::value('activity_date_time', $values))
2496 && CRM_Utils_Array::value('status_id', $values) == 1
2497 ) {
2498 $contactActivities[$activityId]['class'] = 'status-overdue';
2499 }
2500 else {
2501 $contactActivities[$activityId]['class'] = 'status-ontime';
2502 }
2503
2504 // build links
2505 $contactActivities[$activityId]['links'] = '';
2506 $accessMailingReport = FALSE;
2507 if (CRM_Utils_Array::value('mailingId', $values)) {
2508 $accessMailingReport = TRUE;
2509 }
2510
2511 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2512 CRM_Utils_Array::value('activity_type_id', $values),
2513 CRM_Utils_Array::value('source_record_id', $values),
2514 $accessMailingReport,
2515 CRM_Utils_Array::value('activity_id', $values)
2516 );
2517
2518 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2519
2520 $contactActivities[$activityId]['links'] = CRM_Core_Action::formLink($actionLinks,
2521 $actionMask,
2522 array(
2523 'id' => $values['activity_id'],
2524 'cid' => $params['contact_id'],
2525 'cxt' => $context,
2526 'caseid' => CRM_Utils_Array::value('case_id', $values),
87dab4a4
AH
2527 ),
2528 ts('more'),
2529 FALSE,
2530 'activity.tab.row',
2531 'Activity',
2532 $values['activity_id']
6a488035
TO
2533 );
2534 }
2535 }
2536
2537 return $contactActivities;
2538 }
2539
2540 /*
2541 * Used to copy custom fields and attachments from an existing activity to another.
2542 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2543 */
2544 static function copyExtendedActivityData($params) {
2545 // attach custom data to the new activity
2546 $customParams = $htmlType = array();
2547 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
2548
2549 if (!empty($customValues)) {
2550 $fieldIds = implode(', ', array_keys($customValues));
2551 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2552 $result = CRM_Core_DAO::executeQuery($sql);
2553
2554 while ($result->fetch()) {
2555 $htmlType[] = $result->id;
2556 }
2557
2558 foreach ($customValues as $key => $value) {
2559 if ($value !== NULL) { // CRM-10542
2560 if (in_array($key, $htmlType)) {
2561 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
2562 $customParams["custom_{$key}_-1"] = array(
2563 'name' => $fileValues[0],
2564 'path' => $fileValues[1],
2565 );
2566 }
2567 else {
2568 $customParams["custom_{$key}_-1"] = $value;
2569 }
2570 }
2571 }
2572 CRM_Core_BAO_CustomValueTable::postProcess($customParams, CRM_Core_DAO::$_nullArray, 'civicrm_activity',
2573 $params['mainActivityId'], 'Activity'
2574 );
2575 }
2576
2577 // copy activity attachments ( if any )
2578 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2579 }
65ebc887 2580
2581 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2582 $activityContact = new CRM_Activity_BAO_ActivityContact();
2583 $activityContact->activity_id = $activityId;
2584 if ($recordTypeID) {
2585 $activityContact->record_type_id = $recordTypeID;
2586 }
2587 if ($activityContact->find(TRUE)) {
b319d00a 2588 return $activityContact->$column;
65ebc887 2589 }
42d30b83
DL
2590 return NULL;
2591 }
2592
2593 public static function getSourceContactID($activityId) {
2594 static $sourceID = NULL;
2595 if (!$sourceID) {
e7e657f0 2596 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
42d30b83
DL
2597 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2598 }
2599
2600 return self::getActivityContact($activityId, $sourceID);
65ebc887 2601 }
42d30b83 2602
6a488035
TO
2603}
2604