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