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