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