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