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