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