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