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