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