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