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