reminder fixes for CRM-12274
[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
1501 $escapeSmarty = $sent = FALSE;
1502 foreach ($contactDetails as $values) {
1503 $contactId = $values['contact_id'];
1504
1505 if (!empty($details) && is_array($details["{$contactId}"])) {
1506 // unset email from details since it always returns primary email address
1507 unset($details["{$contactId}"]['email']);
1508 unset($details["{$contactId}"]['email_id']);
1509 $values = array_merge($values, $details["{$contactId}"]);
1510 }
1511
1512 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1513 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1514
1515 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1516 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1517
d65e1a68
TW
1518 // Only send if the phone is of type mobile
1519 if($values['phone_type_id'] == 2) {
1520 $smsParams['To'] = $values['phone'];
1521 }else{
1522 $smsParams['To'] = '';
1523 }
6a488035
TO
1524
1525 if (self::sendSMSMessage($contactId,
1526 $tokenText,
1527 $tokenHtml,
1528 $smsParams,
1529 $activityID
1530 )) {
1531 // even a single successful delivery should set this falg to true
1532 $sent = TRUE;
1533 }
1534 }
1535
1536 return array($sent, $activity->id);
1537 }
1538
1539 /**
1540 * send the sms message to a specific contact
1541 *
1542 * @param int $toID the contact id of the recipient
1543 * @param int $activityID the activity ID that tracks the message
1544 * @param array $smsParams the params used for sending sms
1545 *
1546 * @return boolean true if successfull else false.
1547 * @access public
1548 * @static
1549 */
1550 static function sendSMSMessage($toID,
1551 &$tokenText,
1552 &$tokenHtml,
1553 $smsParams = array(),
1554 $activityID
1555 ) {
1556 $toDoNotSms = "";
1557 $toPhoneNumber = "";
1558
1559 if ($smsParams['To']) {
1560 $toPhoneNumber = trim($smsParams['To']);
1561 }
1562 elseif ($toID) {
1563 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1564 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
1565 //to get primary mobile ph,if not get a first mobile ph
1566 if (!empty($toPhoneNumbers)) {
1567 $toPhoneNumerDetails = reset($toPhoneNumbers);
1568 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumerDetails);
1569 //contact allows to send sms
1570 $toDoNotSms = 0;
1571 }
1572 }
1573
1574 // make sure both phone are valid
1575 // and that the recipient wants to receive sms
1576 if (empty($toPhoneNumber) or $toDoNotSms) {
1577 return FALSE;
1578 }
1579
1580 $message = $tokenHtml ? $tokenHtml : $tokenText;
1581 $recipient = $smsParams['To'];
1582 $smsParams['contact_id'] = $toID;
1583 $smsParams['parent_activity_id'] = $activityID;
1584
1585 $providerObj = CRM_SMS_Provider::singleton(array('provider_id' => $smsParams['provider_id']));
1586 if (!$providerObj->send($recipient, $smsParams, $message, NULL)) {
1587 return FALSE;
1588 }
1589
1590 // add activity target record for every sms that is send
1591 $activityTargetParams = array(
1592 'activity_id' => $activityID,
1593 'target_contact_id' => $toID,
1594 );
1595 self::createActivityTarget($activityTargetParams);
1596
1597 return TRUE;
1598 }
1599
1600 /**
1601 * send the message to a specific contact
1602 *
1603 * @param string $from the name and email of the sender
1604 * @param int $toID the contact id of the recipient
1605 * @param string $subject the subject of the message
1606 * @param string $message the message contents
1607 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1608 * @param int $activityID the activity ID that tracks the message
1609 *
1610 * @return boolean true if successfull else false.
1611 * @access public
1612 * @static
1613 */
1614 static function sendMessage($from,
1615 $fromID,
1616 $toID,
1617 &$subject,
1618 &$text_message,
1619 &$html_message,
1620 $emailAddress,
1621 $activityID,
1622 $attachments = NULL,
1623 $cc = NULL,
1624 $bcc = NULL
1625 ) {
1626 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1627 if ($emailAddress) {
1628 $toEmail = trim($emailAddress);
1629 }
1630
1631 // make sure both email addresses are valid
1632 // and that the recipient wants to receive email
1633 if (empty($toEmail) or $toDoNotEmail) {
1634 return FALSE;
1635 }
1636 if (!trim($toDisplayName)) {
1637 $toDisplayName = $toEmail;
1638 }
1639
1640 // create the params array
1641 $mailParams = array(
1642 'groupName' => 'Activity Email Sender',
1643 'from' => $from,
1644 'toName' => $toDisplayName,
1645 'toEmail' => $toEmail,
1646 'subject' => $subject,
1647 'cc' => $cc,
1648 'bcc' => $bcc,
1649 'text' => $text_message,
1650 'html' => $html_message,
1651 'attachments' => $attachments,
1652 );
1653
1654 if (!CRM_Utils_Mail::send($mailParams)) {
1655 return FALSE;
1656 }
1657
1658 // add activity target record for every mail that is send
1659 $activityTargetParams = array(
1660 'activity_id' => $activityID,
1661 'target_contact_id' => $toID,
1662 );
1663 self::createActivityTarget($activityTargetParams);
1664 return TRUE;
1665 }
1666
1667 /**
1668 * combine all the importable fields from the lower levels object
1669 *
1670 * The ordering is important, since currently we do not have a weight
1671 * scheme. Adding weight is super important and should be done in the
1672 * next week or so, before this can be called complete.
1673 *
1674 * @param NULL
1675 *
1676 * @return array array of importable Fields
1677 * @access public
1678 * @static
1679 */
1680 static function &importableFields($status = FALSE) {
1681 if (!self::$_importableFields) {
1682 if (!self::$_importableFields) {
1683 self::$_importableFields = array();
1684 }
1685 if (!$status) {
1686 $fields = array('' => array('title' => ts('- do not import -')));
1687 }
1688 else {
1689 $fields = array('' => array('title' => ts('- Activity Fields -')));
1690 }
1691
1692 $tmpFields = CRM_Activity_DAO_Activity::import();
1693 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1694
1695 // Using new Dedupe rule.
1696 $ruleParams = array(
1697 'contact_type' => 'Individual',
1698 'used' => 'Unsupervised',
1699 );
1700 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1701
1702 $tmpConatctField = array();
1703 if (is_array($fieldsArray)) {
1704 foreach ($fieldsArray as $value) {
1705 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1706 $value,
1707 'id',
1708 'column_name'
1709 );
1710 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1711 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1712 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1713 }
1714 }
1715 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1716 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1717 $fields = array_merge($fields, $tmpConatctField);
1718 $fields = array_merge($fields, $tmpFields);
1719 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
1720 self::$_importableFields = $fields;
1721 }
1722 return self::$_importableFields;
1723 }
1724
1725 /**
1726 * To get the Activities of a target contact
1727 *
1728 * @param $contactId Integer ContactId of the contact whose activities
1729 * need to find
1730 *
1731 * @return array array of activity fields
1732 * @access public
1733 */
1734 static function getContactActivity($contactId) {
1735 $activities = array();
1736
1737 // First look for activities where contactId is one of the targets
1738 $query = "SELECT activity_id FROM civicrm_activity_target
1739 WHERE target_contact_id = $contactId";
1740 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1741 while ($dao->fetch()) {
1742 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
1743 }
1744
1745 // Then get activities where contactId is an asignee
1746 $query = "SELECT activity_id FROM civicrm_activity_assignment
1747 WHERE assignee_contact_id = $contactId";
1748 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1749 while ($dao->fetch()) {
1750 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1751 }
1752
1753 // Then get activities that contactId created
1754 $query = "SELECT id AS activity_id FROM civicrm_activity
1755 WHERE source_contact_id = $contactId";
1756 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1757 while ($dao->fetch()) {
1758 $activities[$dao->activity_id]['source_contact_id'][] = $contactId;
1759 }
1760 $activityIds = array();
1761 // Then look up the activity details for each activity_id we saw above
1762 foreach ($activities as $activityId => $dummy) {
1763 $activityIds[] = $activityId;
1764 }
1765 if (count($activityIds) < 1) {
1766 return array();
1767 }
1768 $activityIds = implode(',', $activityIds);
1769 $query = "SELECT activity.id as activity_id, source_contact_id, target_contact_id, assignee_contact_id, activity_type_id,
1770 subject, location, activity_date_time, details, status_id
1771 FROM civicrm_activity activity
1772 LEFT JOIN civicrm_activity_target target ON activity.id = target.activity_id
1773 LEFT JOIN civicrm_activity_assignment assignment ON activity.id = assignment.activity_id
1774 WHERE activity.id IN ($activityIds)";
1775
1776 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1777
1778 $activityTypes = CRM_Core_OptionGroup::values('activity_type');
1779 $activityStatuses = CRM_Core_OptionGroup::values('activity_status');
1780
1781 while ($dao->fetch()) {
1782 $activities[$dao->activity_id]['source_contact_id'] = $dao->source_contact_id;
1783 $activities[$dao->activity_id]['id'] = $dao->activity_id;
1784 if ($dao->target_contact_id) {
1785 $activities[$dao->activity_id]['targets'][$dao->target_contact_id] = $dao->target_contact_id;
1786 }
1787 if (isset($dao->assignee_contact_id)) {
1788 $activities[$dao->activity_id]['asignees'][$dao->assignee_contact_id] = $dao->assignee_contact_id;
1789 }
1790 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
1791 $activities[$dao->activity_id]['subject'] = $dao->subject;
1792 $activities[$dao->activity_id]['location'] = $dao->location;
1793 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
1794 $activities[$dao->activity_id]['details'] = $dao->details;
1795 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
1796 $activities[$dao->activity_id]['activity_name'] = $activityTypes[$dao->activity_type_id];
1797 $activities[$dao->activity_id]['status'] = $activityStatuses[$dao->status_id];
1798 }
1799 return $activities;
1800 }
1801
1802 /**
1803 * Function to add activity for Membership/Event/Contribution
1804 *
1805 * @param object $activity (reference) perticular component object
1806 * @param string $activityType for Membership Signup or Renewal
1807 *
1808 *
1809 * @static
1810 * @access public
1811 */
1812 static function addActivity(&$activity,
1813 $activityType = 'Membership Signup',
1814 $targetContactID = NULL
1815 ) {
1816 if ($activity->__table == 'civicrm_membership') {
1817 $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id);
1818
1819 if (!$membershipType) {
1820 $membershipType = ts('Membership');
1821 }
1822
1823 $subject = "{$membershipType}";
1824
1825 if (!empty($activity->source) && $activity->source != 'null') {
1826 $subject .= " - {$activity->source}";
1827 }
1828
1829 if ($activity->owner_membership_id) {
1830 $query = "
1831SELECT display_name
1832 FROM civicrm_contact, civicrm_membership
1833 WHERE civicrm_contact.id = civicrm_membership.contact_id
1834 AND civicrm_membership.id = $activity->owner_membership_id
1835";
1836 $displayName = CRM_Core_DAO::singleValueQuery($query);
1837 $subject .= " (by {$displayName})";
1838 }
1839
1840 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id);
1841 // CRM-72097 changed from start date to today
1842 $date = date('YmdHis');
1843 $component = 'Membership';
1844 }
1845 elseif ($activity->__table == 'civicrm_participant') {
1846 $event = CRM_Event_BAO_Event::getEvents(TRUE, $activity->event_id, TRUE, FALSE);
1847
1848 $roles = CRM_Event_PseudoConstant::participantRole();
1849 $status = CRM_Event_PseudoConstant::participantStatus();
1850
1851 $subject = $event[$activity->event_id];
1852 if (CRM_Utils_Array::value($activity->role_id, $roles)) {
1853 $subject .= ' - ' . $roles[$activity->role_id];
1854 }
1855 if (CRM_Utils_Array::value($activity->status_id, $status)) {
1856 $subject .= ' - ' . $status[$activity->status_id];
1857 }
1858 $date = date('YmdHis');
1859 if ($activityType != 'Email') {
1860 $activityType = 'Event Registration';
1861 }
1862 $component = 'Event';
1863 }
1864 elseif ($activity->__table == 'civicrm_contribution') {
1865 //create activity record only for Completed Contributions
1866 if ($activity->contribution_status_id != 1) {
1867 return;
1868 }
1869
1870 $subject = NULL;
1871
1872 $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency);
1873 if (!empty($activity->source) && $activity->source != 'null') {
1874 $subject .= " - {$activity->source}";
1875 }
1876 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
1877 $activityType = $component = 'Contribution';
1878 }
1879 $activityParams = array(
1880 'source_contact_id' => $activity->contact_id,
1881 'source_record_id' => $activity->id,
1882 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1883 $activityType,
1884 'name'
1885 ),
1886 'subject' => $subject,
1887 'activity_date_time' => $date,
1888 'is_test' => $activity->is_test,
1889 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
1890 'Completed',
1891 'name'
1892 ),
1893 'skipRecentView' => TRUE,
1894 'campaign_id' => $activity->campaign_id,
1895 );
1896
1897 // create activity with target contacts
1898 $session = CRM_Core_Session::singleton();
1899 $id = $session->get('userID');
1900 if ($id) {
1901 $activityParams['source_contact_id'] = $id;
1902 $activityParams['target_contact_id'][] = $activity->contact_id;
1903 }
1904
1905 //CRM-4027
1906 if ($targetContactID) {
1907 $activityParams['target_contact_id'][] = $targetContactID;
1908 }
1909 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
1910 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
1911 return FALSE;
1912 }
1913 }
1914
1915 /**
1916 * Function to get Parent activity for currently viewd activity
1917 *
1918 * @param int $activityId current activity id
1919 *
1920 * @return int $parentId Id of parent acyivity otherwise false.
1921 * @access public
1922 */
1923 static function getParentActivity($activityId) {
1924 static $parentActivities = array();
1925
1926 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1927
1928 if (!array_key_exists($activityId, $parentActivities)) {
1929 $parentActivities[$activityId] = array();
1930
1931 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1932 $activityId,
1933 'parent_id'
1934 );
1935
1936 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1937 }
1938
1939 return $parentActivities[$activityId];
1940 }
1941
1942 /**
1943 * Function to get total count of prior revision of currently viewd activity
1944 *
1945 * @param int $activityId current activity id
1946 *
1947 * @return int $params count of prior acyivities otherwise false.
1948 * @access public
1949 */
1950 static function getPriorCount($activityID) {
1951 static $priorCounts = array();
1952
1953 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1954
1955 if (!array_key_exists($activityID, $priorCounts)) {
1956 $priorCounts[$activityID] = array();
1957 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1958 $activityID,
1959 'original_id'
1960 );
1961 $count = 0;
1962 if ($originalID) {
1963 $query = "
1964SELECT count( id ) AS cnt
1965FROM civicrm_activity
1966WHERE ( id = {$originalID} OR original_id = {$originalID} )
1967AND is_current_revision = 0
1968AND id < {$activityID}
1969";
1970 $params = array(1 => array($originalID, 'Integer'));
1971 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1972 }
1973 $priorCounts[$activityID] = $count ? $count : 0;
1974 }
1975
1976 return $priorCounts[$activityID];
1977 }
1978
1979 /**
1980 * Function to get all prior activities of currently viewd activity
1981 *
1982 * @param int $activityId current activity id
1983 *
1984 * @return array $result prior acyivities info.
1985 * @access public
1986 */
1987 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1988 static $priorActivities = array();
1989
1990 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1991 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1992
1993 if (!array_key_exists($index, $priorActivities)) {
1994 $priorActivities[$index] = array();
1995
1996 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1997 $activityID,
1998 'original_id'
1999 );
2000 if ($originalID) {
2001 $query = "
2002SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2003FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2004WHERE (ca.id = %1 OR ca.original_id = %1)
2005AND cl.entity_table = 'civicrm_activity'
2006AND cl.entity_id = ca.id
2007AND cl.modified_id = c.id
2008";
2009 if ($onlyPriorRevisions) {
2010 $query .= " AND ca.id < {$activityID}";
2011 }
2012 $query .= " ORDER BY ca.id DESC";
2013
2014 $params = array(1 => array($originalID, 'Integer'));
2015 $dao = CRM_Core_DAO::executeQuery($query, $params);
2016
2017 while ($dao->fetch()) {
2018 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
2019 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
2020 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
2021 $priorActivities[$index][$dao->activityID]['link'] = 'javascript:viewActivity( $dao->activityID );';
2022 }
2023 $dao->free();
2024 }
2025 }
2026 return $priorActivities[$index];
2027 }
2028
2029 /**
2030 * Function to find the latest revision of a given activity
2031 *
2032 * @param int $activityId prior activity id
2033 *
2034 * @return int $params current activity id.
2035 * @access public
2036 */
2037 static function getLatestActivityId($activityID) {
2038 static $latestActivityIds = array();
2039
2040 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2041
2042 if (!array_key_exists($activityID, $latestActivityIds)) {
2043 $latestActivityIds[$activityID] = array();
2044
2045 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2046 $activityID,
2047 'original_id'
2048 );
2049 if ($originalID) {
2050 $activityID = $originalID;
2051 }
2052 $params = array(1 => array($activityID, 'Integer'));
2053 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2054
2055 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
2056 }
2057
2058 return $latestActivityIds[$activityID];
2059 }
2060
2061 /**
2062 * Function to create a follow up a given activity
2063 *
2064 * @activityId int activity id of parent activity
2065 *
2066 * @param array $activity details
2067 *
2068 * @access public
2069 */
2070 static function createFollowupActivity($activityId, $params) {
2071 if (!$activityId) {
2072 return;
2073 }
2074
2075 $session = CRM_Core_Session::singleton();
2076
2077 $followupParams = array();
2078 $followupParams['parent_id'] = $activityId;
2079 $followupParams['source_contact_id'] = $session->get('userID');
2080 $followupParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
2081
2082 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2083 // Get Subject of Follow-up Activiity, CRM-4491
2084 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
2085
2086 //create target contact for followup
2087 if (CRM_Utils_Array::value('target_contact_id', $params)) {
2088 $followupParams['target_contact_id'] = $params['target_contact_id'];
2089 }
2090
2091 $followupParams['activity_date_time'] = CRM_Utils_Date::processDate($params['followup_date'],
2092 $params['followup_date_time']
2093 );
2094 $followupActivity = self::create($followupParams);
2095
2096 return $followupActivity;
2097 }
2098
2099 /**
2100 * Function to get Activity specific File according activity type Id.
2101 *
2102 * @param int $activityTypeId activity id
2103 *
2104 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2105 *
2106 * @static
2107 */
2108 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2109 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2110
2111 if ($activityTypes[$activityTypeId]['name']) {
2112 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2113 }
2114 else {
2115 return FALSE;
2116 }
2117
2118 global $civicrm_root;
2119 $config = CRM_Core_Config::singleton();
2120 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2121 if (empty($config->customPHPPathDir)) {
2122 return FALSE;
2123 }
2124 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2125 return FALSE;
2126 }
2127 }
2128
2129 return $activityTypeFile;
2130 }
2131
2132 /**
2133 * Function to restore the activity
2134 *
2135 * @param array $params associated array
2136 *
2137 * @return void
2138 * @access public
2139 *
2140 */
2141 public static function restoreActivity(&$params) {
2142 $activity = new CRM_Activity_DAO_Activity();
2143 $activity->copyValues($params);
2144
2145 $activity->is_deleted = 0;
2146 $result = $activity->save();
2147
2148 return $result;
2149 }
2150
2151 /**
2152 * Get the exportable fields for Activities
2153 *
2154 * @param string $name if it is called by case $name = Case else $name = Activity
2155 *
2156 * @return array array of exportable Fields
2157 * @access public
2158 * @static
2159 */
2160 static function &exportableFields($name = 'Activity') {
2161 if (!isset(self::$_exportableFields[$name])) {
2162 self::$_exportableFields[$name] = array();
2163
2164 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2165 // my case hence we have defined fields as case_*
2166 if ($name == 'Activity') {
2167 $exportableFields = CRM_Activity_DAO_Activity::export();
2168 if (isset($exportableFields['activity_campaign_id'])) {
2169 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2170 }
2171 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2172 $exportableFields['source_contact'] = array(
2173 'title' => ts('Source Contact'),
2174 'type' => CRM_Utils_Type::T_STRING,
2175 );
2176
2177
2178 $Activityfields = array(
2179 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2180 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2181 );
2182 $fields = array_merge($Activityfields, $exportableFields);
2183 }
2184 else {
2185 //set title to activity fields
2186 $fields = array(
2187 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
2188 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
2189 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
2190 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type::T_DATE),
2191 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2192 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2193 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
2194 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
2195 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
2196 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type::T_BOOLEAN),
2197 );
2198
2199 // add custom data for cases
2200 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Case'));
2201 }
2202
2203 // add custom data for case activities
2204 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2205
2206 self::$_exportableFields[$name] = $fields;
2207 }
2208 return self::$_exportableFields[$name];
2209 }
2210
2211 /**
2212 * Get the allowed profile fields for Activities
2213 *
2214 * @return array array of activity profile Fields
2215 * @access public
2216 */
2217 static function getProfileFields() {
2218 $exportableFields = self::exportableFields('Activity');
2219 $skipFields = array('activity_id', 'activity_type', 'source_contact_id', 'activity_campaign', 'activity_is_test', 'is_current_revision', 'activity_is_deleted',);
2220 $config = CRM_Core_Config::singleton();
2221 if (!in_array('CiviCampaign', $config->enableComponents)) {
2222 $skipFields[] = 'activity_engagement_level';
2223 }
2224
2225 foreach ($skipFields as $field) {
2226 if (isset($exportableFields[$field])) {
2227 unset($exportableFields[$field]);
2228 }
2229 }
2230
2231 // hack to use 'activity_type_id' instead of 'activity_type'
2232 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2233 unset($exportableFields['activity_status']);
2234
2235 return $exportableFields;
2236 }
2237
2238 /**
2239 * This function delete activity record related to contact record,
2240 * when there are no target and assignee record w/ other contact.
2241 *
2242 * @param int $contactId contactId
2243 *
2244 * @return true/null
2245 * @access public
2246 */
2247 public static function cleanupActivity($contactId) {
2248 $result = NULL;
2249 if (!$contactId) {
2250 return $result;
2251 }
2252
2253 $transaction = new CRM_Core_Transaction();
2254
2255 // delete activity if there are no record in
2256 // civicrm_activity_assignment or civicrm_activity_target
2257 // pointing to any other contact record.
2258
2259
2260 $activity = new CRM_Activity_DAO_Activity();
2261 $activity->source_contact_id = $contactId;
2262 $activity->find();
2263
2264 while ($activity->fetch()) {
2265 $noTarget = $noAssignee = TRUE;
2266
2267 // check for target activity record.
2268 $target = new CRM_Activity_DAO_ActivityTarget();
2269 $target->activity_id = $activity->id;
2270 $target->find();
2271 while ($target->fetch()) {
2272 if ($target->target_contact_id != $contactId) {
2273 $noTarget = FALSE;
2274 break;
2275 }
2276 }
2277 $target->free();
2278
2279 // check for assignee activity record.
2280 $assignee = new CRM_Activity_DAO_ActivityAssignment();
2281 $assignee->activity_id = $activity->id;
2282 $assignee->find();
2283 while ($assignee->fetch()) {
2284 if ($assignee->assignee_contact_id != $contactId) {
2285 $noAssignee = FALSE;
2286 break;
2287 }
2288 }
2289 $assignee->free();
2290
2291 // finally delete activity.
2292 if ($noTarget && $noAssignee) {
2293 $activityParams = array('id' => $activity->id);
2294 $result = self::deleteActivity($activityParams);
2295 }
2296 }
2297 $activity->free();
2298
2299 $transaction->commit();
2300
2301 return $result;
2302 }
2303
2304 /**
2305 * Does user has sufficient permission for view/edit activity record.
2306 *
2307 * @param int $activityId activity record id.
2308 * @param int $action edit/view
2309 *
2310 * @return boolean $allow true/false
2311 * @access public
2312 */
2313 public static function checkPermission($activityId, $action) {
2314 $allow = FALSE;
2315 if (!$activityId ||
2316 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2317 ) {
2318 return $allow;
2319 }
2320
2321 $activity = new CRM_Activity_DAO_Activity();
2322 $activity->id = $activityId;
2323 if (!$activity->find(TRUE)) {
2324 return $allow;
2325 }
2326
2327 //component related permissions.
2328 $compPermissions = array(
2329 'CiviCase' => array('administer CiviCase',
2330 'access my cases and activities',
2331 'access all cases and activities',
2332 ),
2333 'CiviMail' => array('access CiviMail'),
2334 'CiviEvent' => array('access CiviEvent'),
2335 'CiviGrant' => array('access CiviGrant'),
2336 'CiviPledge' => array('access CiviPledge'),
2337 'CiviMember' => array('access CiviMember'),
2338 'CiviReport' => array('access CiviReport'),
2339 'CiviContribute' => array('access CiviContribute'),
2340 'CiviCampaign' => array('administer CiviCampaign'),
2341 );
2342
2343 //return early when it is case activity.
2344 $isCaseActivity = CRM_Case_BAO_Case::isCaseActivity($activityId);
2345 //check for civicase related permission.
2346 if ($isCaseActivity) {
2347 $allow = FALSE;
2348 foreach ($compPermissions['CiviCase'] as $per) {
2349 if (CRM_Core_Permission::check($per)) {
2350 $allow = TRUE;
2351 break;
2352 }
2353 }
2354
2355 //check for case specific permissions.
2356 if ($allow) {
2357 $oper = 'view';
2358 if ($action == CRM_Core_Action::UPDATE) {
2359 $oper = 'edit';
2360 }
2361 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2362 $oper,
2363 $activity->activity_type_id
2364 );
2365 }
2366
2367 return $allow;
2368 }
2369
2370
2371 //first check the component permission.
2372 $sql = "
2373 SELECT component_id
2374 FROM civicrm_option_value val
2375INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2376 WHERE val.value = %2";
2377 $params = array(1 => array('activity_type', 'String'),
2378 2 => array($activity->activity_type_id, 'Integer'),
2379 );
2380 $componentId = CRM_Core_DAO::singleValueQuery($sql, $params);
2381
2382 if ($componentId) {
2383 $componentName = CRM_Core_Component::getComponentName($componentId);
2384 $compPermission = CRM_Utils_Array::value($componentName, $compPermissions);
2385
2386 //here we are interesting in any single permission.
2387 if (is_array($compPermission)) {
2388 foreach ($compPermission as $per) {
2389 if (CRM_Core_Permission::check($per)) {
2390 $allow = TRUE;
2391 break;
2392 }
2393 }
2394 }
2395 }
2396
2397 //check for this permission related to contact.
2398 $permission = CRM_Core_Permission::VIEW;
2399 if ($action == CRM_Core_Action::UPDATE) {
2400 $permission = CRM_Core_Permission::EDIT;
2401 }
2402
2403 //check for source contact.
2404 if (!$componentId || $allow) {
2405 $allow = CRM_Contact_BAO_Contact_Permission::allow($activity->source_contact_id, $permission);
2406 }
2407
2408 //check for target and assignee contacts.
2409 if ($allow) {
2410 //first check for supper permission.
2411 $supPermission = 'view all contacts';
2412 if ($action == CRM_Core_Action::UPDATE) {
2413 $supPermission = 'edit all contacts';
2414 }
2415 $allow = CRM_Core_Permission::check($supPermission);
2416
2417 //user might have sufficient permission, through acls.
2418 if (!$allow) {
2419 $allow = TRUE;
2420 //get the target contacts.
2421 $targetContacts = CRM_Activity_BAO_ActivityTarget::retrieveTargetIdsByActivityId($activity->id);
2422 foreach ($targetContacts as $cnt => $contactId) {
2423 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2424 $allow = FALSE;
2425 break;
2426 }
2427 }
2428
2429 //get the assignee contacts.
2430 if ($allow) {
2431 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($activity->id);
2432 foreach ($assigneeContacts as $cnt => $contactId) {
2433 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2434 $allow = FALSE;
2435 break;
2436 }
2437 }
2438 }
2439 }
2440 }
2441
2442 return $allow;
2443 }
2444
2445 /**
2446 * This function is a wrapper for ajax activity selector
2447 *
2448 * @param array $params associated array for params record id.
2449 *
2450 * @return array $contactActivities associated array of contact activities
2451 * @access public
2452 */
2453 public static function getContactActivitySelector(&$params) {
2454 // format the params
2455 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2456 $params['rowCount'] = $params['rp'];
2457 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2458 $params['caseId'] = NULL;
2459 $context = CRM_Utils_Array::value('context', $params);
2460
2461 // get contact activities
2462 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2463
2464 // add total
2465 $params['total'] = CRM_Activity_BAO_Activity::getActivitiesCount($params);
2466
2467 // format params and add links
2468 $contactActivities = array();
2469
2470 if (!empty($activities)) {
2471 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2472
2473 // check logged in user for permission
2474 $page = new CRM_Core_Page();
2475 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2476 $permissions = array($page->_permission);
2477 if (CRM_Core_Permission::check('delete activities')) {
2478 $permissions[] = CRM_Core_Permission::DELETE;
2479 }
2480
2481 $mask = CRM_Core_Action::mask($permissions);
2482
2483 foreach ($activities as $activityId => $values) {
2484 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2485 $contactActivities[$activityId]['subject'] = $values['subject'];
2486 if ($params['contact_id'] == $values['source_contact_id']) {
2487 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2488 }
2489 elseif ($values['source_contact_id']) {
2490 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System::href($values['source_contact_name'], 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2491 }
2492 else {
2493 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2494 }
2495
2496 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2497 $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");
2498 }
2499 elseif (CRM_Utils_Array::value('recipients', $values)) {
2500 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2501 }
2502 elseif (!$values['target_contact_name']) {
2503 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2504 }
2505 elseif (!empty($values['target_contact_name'])) {
2506 $count = 0;
2507 $contactActivities[$activityId]['target_contact'] = '';
2508 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2509 if ($tcID && $count < 5) {
2510 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2511 $count++;
2512 if ($count) {
2513 $contactActivities[$activityId]['target_contact'] .= ";&nbsp;";
2514 }
2515
2516 if ($count == 4) {
2517 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2518 break;
2519 }
2520 }
2521 }
2522 }
2523
2524 if (empty($values['assignee_contact_name'])) {
2525 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2526 }
2527 elseif (!empty($values['assignee_contact_name'])) {
2528 $count = 0;
2529 $contactActivities[$activityId]['assignee_contact'] = '';
2530 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2531 if ($acID && $count < 5) {
2532 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2533 $count++;
2534 if ($count) {
2535 $contactActivities[$activityId]['assignee_contact'] .= ";&nbsp;";
2536 }
2537
2538 if ($count == 4) {
2539 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2540 break;
2541 }
2542 }
2543 }
2544 }
2545 if ( $values['activity_type'] == 'Bulk Email'){
2546 $contactActivities[$activityId]['openstats'] = "Opens: ".
2547 count(CRM_Mailing_Event_BAO_Opened::getRows(
2548 CRM_Utils_Array::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, $params['contact_id']
2549 )
2550 )."<br />Clicks:" .
2551 count(CRM_Mailing_Event_BAO_TrackableURLOpen::getRows(
2552 CRM_Utils_Array::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, NULL, $params['contact_id']
2553 ) );
2554 }else {
2555 $contactActivities[$activityId]['openstats'] = '';
2556 }
2557
2558 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2559 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2560
2561 // add class to this row if overdue
2562 $contactActivities[$activityId]['class'] = '';
2563 if (CRM_Utils_Date::overdue(CRM_Utils_Array::value('activity_date_time', $values))
2564 && CRM_Utils_Array::value('status_id', $values) == 1
2565 ) {
2566 $contactActivities[$activityId]['class'] = 'status-overdue';
2567 }
2568 else {
2569 $contactActivities[$activityId]['class'] = 'status-ontime';
2570 }
2571
2572 // build links
2573 $contactActivities[$activityId]['links'] = '';
2574 $accessMailingReport = FALSE;
2575 if (CRM_Utils_Array::value('mailingId', $values)) {
2576 $accessMailingReport = TRUE;
2577 }
2578
2579 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2580 CRM_Utils_Array::value('activity_type_id', $values),
2581 CRM_Utils_Array::value('source_record_id', $values),
2582 $accessMailingReport,
2583 CRM_Utils_Array::value('activity_id', $values)
2584 );
2585
2586 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2587
2588 $contactActivities[$activityId]['links'] = CRM_Core_Action::formLink($actionLinks,
2589 $actionMask,
2590 array(
2591 'id' => $values['activity_id'],
2592 'cid' => $params['contact_id'],
2593 'cxt' => $context,
2594 'caseid' => CRM_Utils_Array::value('case_id', $values),
2595 )
2596 );
2597 }
2598 }
2599
2600 return $contactActivities;
2601 }
2602
2603 /*
2604 * Used to copy custom fields and attachments from an existing activity to another.
2605 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2606 */
2607 static function copyExtendedActivityData($params) {
2608 // attach custom data to the new activity
2609 $customParams = $htmlType = array();
2610 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
2611
2612 if (!empty($customValues)) {
2613 $fieldIds = implode(', ', array_keys($customValues));
2614 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2615 $result = CRM_Core_DAO::executeQuery($sql);
2616
2617 while ($result->fetch()) {
2618 $htmlType[] = $result->id;
2619 }
2620
2621 foreach ($customValues as $key => $value) {
2622 if ($value !== NULL) { // CRM-10542
2623 if (in_array($key, $htmlType)) {
2624 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
2625 $customParams["custom_{$key}_-1"] = array(
2626 'name' => $fileValues[0],
2627 'path' => $fileValues[1],
2628 );
2629 }
2630 else {
2631 $customParams["custom_{$key}_-1"] = $value;
2632 }
2633 }
2634 }
2635 CRM_Core_BAO_CustomValueTable::postProcess($customParams, CRM_Core_DAO::$_nullArray, 'civicrm_activity',
2636 $params['mainActivityId'], 'Activity'
2637 );
2638 }
2639
2640 // copy activity attachments ( if any )
2641 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2642 }
2643}
2644