fixed conflict
[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 // step 2: Get target and assignee contacts for above activities
750 // create temp table for target contacts
751 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
752 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
753 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16), contact_name varchar(255) )
754 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
755
756 CRM_Core_DAO::executeQuery($query);
757
758 // note that we ignore bulk email for targets, since we don't show it in selector
759 $query = "
760 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name )
761 SELECT ac.activity_id,
762 ac.contact_id,
763 ac.record_type_id,
764 c.sort_name
765 FROM civicrm_activity_contact ac
766 INNER JOIN {$activityTempTable} ON ( ac.activity_id = {$activityTempTable}.activity_id )
767 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
768 WHERE c.is_deleted = 0
769
770 ";
771 CRM_Core_DAO::executeQuery($query);
772
773 // step 3: Combine all temp tables to get final query for activity selector
774 $query = "
775 SELECT {$activityTempTable}.*,
776 {$activityContactTempTable}.contact_id,
777 {$activityContactTempTable}.record_type_id,
778 {$activityContactTempTable}.contact_name
779 FROM {$activityTempTable}
780 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
781 ";
782
783
784 $dao = CRM_Core_DAO::executeQuery($query);
785
786 //CRM-3553, need to check user has access to target groups.
787 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
788 $accessCiviMail = (
789 (CRM_Core_Permission::check('access CiviMail')) ||
790 (CRM_Mailing_Info::workflowEnabled() &&
791 CRM_Core_Permission::check('create mailings'))
792 );
793
794 //get all campaigns.
795 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
796
797 $values = array();
798 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
799 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
800 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
801 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
802
803
804 while ($dao->fetch()) {
805 $activityID = $dao->activity_id;
806 $values[$activityID]['activity_id'] = $dao->activity_id;
807 $values[$activityID]['source_record_id'] = $dao->source_record_id;
808 $values[$activityID]['activity_type_id'] = $dao->activity_type_id;
809 $values[$activityID]['activity_type'] = $dao->activity_type;
810 $values[$activityID]['activity_date_time'] = $dao->activity_date_time;
811 $values[$activityID]['status_id'] = $dao->status_id;
812 $values[$activityID]['subject'] = $dao->subject;
813 $values[$activityID]['campaign_id'] = $dao->campaign_id;
814
815 if ($dao->campaign_id) {
816 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id];
817 }
818
819 if (!CRM_Utils_Array::value('assignee_contact_name', $values[$activityID])) {
820 $values[$activityID]['assignee_contact_name'] = array();
821 }
822
823 if (!CRM_Utils_Array::value('target_contact_name', $values[$activityID])) {
824 $values[$activityID]['target_contact_name'] = array();
825 }
826
827 if ($dao->record_type_id == $sourceID && $dao->contact_id) {
828 $values[$activityID]['source_contact_id'] = $dao->contact_id;
829 $values[$activityID]['source_contact_name'] = $dao->contact_name;
830 }
831
832 if (!$bulkActivityTypeID || ($bulkActivityTypeID != $dao->activity_type_id)) {
833 // build array of target / assignee names
834 if ($dao->record_type_id == $targetID && $dao->contact_id) {
835 $values[$activityID]['target_contact_name'][$dao->contact_id] = $dao->contact_name;
836 }
837 if ($dao->record_type_id == $assigneeID && $dao->contact_id) {
838 $values[$activityID]['assignee_contact_name'][$dao->contact_id] = $dao->contact_name;
839 }
840
841 // case related fields
842 $values[$activityID]['case_id'] = $dao->case_id;
843 $values[$activityID]['case_subject'] = $dao->case_subject;
844 }
845 else {
846 $values[$activityID]['recipients'] = ts('(recipients)');
847 $values[$activityID]['mailingId'] = '';
848 if (
849 $accessCiviMail &&
850 ($mailingIDs === TRUE || in_array($dao->source_record_id, $mailingIDs))
851 ) {
852 $values[$activityID]['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report',
853 "mid={$dao->source_record_id}&reset=1&cid={$dao->source_contact_id}&context=activitySelector"
854 );
855 }
856 }
857 }
858
859 // add info on whether the related contacts are deleted (CRM-5673)
860 // FIXME: ideally this should be tied to ACLs
861
862 // grab all the related contact ids
863 $cids = array();
864 foreach ($values as $value) {
865 $cids[] = $value['source_contact_id'];
866 }
867 $cids = array_filter(array_unique($cids));
868
869 // see which of the cids are of deleted contacts
870 if ($cids) {
871 $sql = 'SELECT id FROM civicrm_contact WHERE id IN (' . implode(', ', $cids) . ') AND is_deleted = 1';
872 $dao = CRM_Core_DAO::executeQuery($sql);
873 $dels = array();
874 while ($dao->fetch()) {
875 $dels[] = $dao->id;
876 }
877
878 // hide the deleted contacts
879 foreach ($values as & $value) {
880 if (in_array($value['source_contact_id'], $dels)) {
881 unset($value['source_contact_id'], $value['source_contact_name']);
882 }
883 }
884 }
885
886 return $values;
887 }
888
889 /**
890 * Get the component id and name those are enabled and logged in
891 * user has permission. To decide whether we are going to include
892 * component related activities w/ core activity retrieve process.
893 *
894 * return an array of component id and name.
895 * @static
896 **/
897 static function activityComponents() {
898 $components = array();
899 $compInfo = CRM_Core_Component::getEnabledComponents();
900 foreach ($compInfo as $compObj) {
901 if (CRM_Utils_Array::value('showActivitiesInCore', $compObj->info)) {
902 if ($compObj->info['name'] == 'CiviCampaign') {
903 $componentPermission = "administer {$compObj->name}";
904 }
905 else {
906 $componentPermission = "access {$compObj->name}";
907 }
908 if ($compObj->info['name'] == 'CiviCase') {
909 if (CRM_Case_BAO_Case::accessCiviCase()) {
910 $components[$compObj->componentID] = $compObj->info['name'];
911 }
912 }
913 elseif (CRM_Core_Permission::check($componentPermission)) {
914 $components[$compObj->componentID] = $compObj->info['name'];
915 }
916 }
917 }
918
919 return $components;
920 }
921
922 /**
923 * function to get the activity Count
924 *
925 * @param array $input array of parameters
926 * Keys include
927 * - contact_id int contact_id whose activties we want to retrieve
928 * - admin boolean if contact is admin
929 * - caseId int case ID
930 * - context string page on which selector is build
931 * - activity_type_id int|string the activitiy types we want to restrict by
932 *
933 * @return int count of activities
934 *
935 * @access public
936 * @static
937 */
938 static function &getActivitiesCount($input) {
939 $input['count'] = TRUE;
940 list($sqlClause, $params) = self::getActivitySQLClause($input);
941
942 //filter case activities - CRM-5761
943 $components = self::activityComponents();
944 if (!in_array('CiviCase', $components)) {
945 $query = "
946 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
947 FROM ( {$sqlClause} ) as tbl
948 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
949 WHERE civicrm_case_activity.id IS NULL";
950 }
951 else {
952 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
953 }
954
955 return CRM_Core_DAO::singleValueQuery($query, $params);
956 }
957
958 /**
959 * function to get the activity sql clause to pick activities
960 *
961 * @param array $input array of parameters
962 * Keys include
963 * - contact_id int contact_id whose activties we want to retrieve
964 * - admin boolean if contact is admin
965 * - caseId int case ID
966 * - context string page on which selector is build
967 * - count boolean are we interested in the count clause only?
968 * - activity_type_id int|string the activitiy types we want to restrict by
969 *
970 * @return int count of activities
971 *
972 * @access public
973 * @static
974 */
975 static function getActivitySQLClause($input) {
976 $params = array();
977 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
978
979 $config = CRM_Core_Config::singleton();
980 if (!CRM_Utils_Array::value('admin', $input, FALSE)) {
981 $sourceWhere = ' ac.contact_id = %1 ';
982 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
983
984 $params = array(1 => array($input['contact_id'], 'Integer'));
985 }
986
987 $commonClauses = array(
988 "civicrm_option_group.name = 'activity_type'",
989 "civicrm_activity.is_deleted = 0",
990 "civicrm_activity.is_current_revision = 1",
991 "civicrm_activity.is_test= 0",
992 );
993
994 if ($input['context'] != 'activity') {
995 $commonClauses[] = "civicrm_activity.status_id = 1";
996 }
997
998 //Filter on component IDs.
999 $components = self::activityComponents();
1000 if (!empty($components)) {
1001 $componentsIn = implode(',', array_keys($components));
1002 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1003 }
1004 else {
1005 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1006 }
1007
1008 // activity type ID clause
1009 if (!empty($input['activity_type_id'])) {
1010 if (is_array($input['activity_type_id'])) {
1011 foreach ($input['activity_type_id'] as $idx => $value) {
1012 $input['activity_type_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1013 }
1014 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1015 }
1016 else {
1017 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_id'], 'Positive');
1018 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1019 }
1020 }
1021
1022 // exclude by activity type clause
1023 if (!empty($input['activity_type_exclude_id'])) {
1024 if (is_array($input['activity_type_exclude_id'])) {
1025 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1026 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1027 }
1028 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1029 }
1030 else {
1031 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_exclude_id'], 'Positive');
1032 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1033 }
1034 }
1035
1036 $commonClause = implode(' AND ', $commonClauses);
1037
1038 $includeCaseActivities = FALSE;
1039 if (in_array('CiviCase', $components)) {
1040 $includeCaseActivities = TRUE;
1041 }
1042
1043
1044 // build main activity table select clause
1045 $sourceSelect = '';
1046 $sourceJoin = "
1047 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1048 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1049 ";
1050
1051 if (!$input['count']) {
1052 $sourceSelect = ',
1053 civicrm_activity.activity_date_time,
1054 civicrm_activity.status_id,
1055 civicrm_activity.subject,
1056 civicrm_activity.source_record_id,
1057 civicrm_option_value.value as activity_type_id,
1058 civicrm_option_value.label as activity_type,
1059 null as case_id, null as case_subject,
1060 civicrm_activity.campaign_id as campaign_id
1061 ';
1062
1063 }
1064
1065 $sourceClause = "
1066 SELECT civicrm_activity.id as activity_id
1067 {$sourceSelect}
1068 from civicrm_activity
1069 left join civicrm_option_value on
1070 civicrm_activity.activity_type_id = civicrm_option_value.value
1071 left join civicrm_option_group on
1072 civicrm_option_group.id = civicrm_option_value.option_group_id
1073 {$sourceJoin}
1074 where
1075 {$sourceWhere}
1076 AND $commonClause
1077 ";
1078
1079 // Build case clause
1080 // or else exclude Inbound Emails that have been filed on a case.
1081 $caseClause = '';
1082
1083 if ($includeCaseActivities) {
1084 $caseSelect = '';
1085 if (!$input['count']) {
1086 $caseSelect = ',
1087 civicrm_activity.activity_date_time,
1088 civicrm_activity.status_id,
1089 civicrm_activity.subject,
1090 civicrm_activity.source_contact_id,
1091 civicrm_activity.source_record_id,
1092 civicrm_option_value.value as activity_type_id,
1093 civicrm_option_value.label as activity_type,
1094 null as case_id, null as case_subject,
1095 civicrm_activity.campaign_id as campaign_id';
1096 }
1097
1098 $caseClause = "
1099 union all
1100
1101 SELECT civicrm_activity.id as activity_id
1102 {$caseSelect}
1103 from civicrm_activity
1104 inner join civicrm_case_activity on
1105 civicrm_case_activity.activity_id = civicrm_activity.id
1106 inner join civicrm_case on
1107 civicrm_case_activity.case_id = civicrm_case.id
1108 inner join civicrm_case_contact on
1109 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1110 left join civicrm_option_value on
1111 civicrm_activity.activity_type_id = civicrm_option_value.value
1112 left join civicrm_option_group on
1113 civicrm_option_group.id = civicrm_option_value.option_group_id
1114 {$sourceJoin}
1115 where
1116 {$caseWhere}
1117 AND $commonClause
1118 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1119 ( civicrm_option_value.name <> 'Inbound Email' AND
1120 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1121 IS NOT NULL )
1122 )
1123 ";
1124 }
1125
1126 $returnClause = " {$sourceClause} {$caseClause} ";
1127
1128 return array($returnClause, $params);
1129 }
1130
1131 /**
1132 * send the message to all the contacts and also insert a
1133 * contact activity in each contacts record
1134 *
1135 * @param array $contactDetails the array of contact details to send the email
1136 * @param string $subject the subject of the message
1137 * @param string $message the message contents
1138 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1139 * @param int $userID use this userID if set
1140 * @param string $from
1141 * @param array $attachments the array of attachments if any
1142 * @param string $cc cc recepient
1143 * @param string $bcc bcc recepient
1144 * @param array $contactIds contact ids
1145 *
1146 * @return array ( sent, activityId) if any email is sent and activityId
1147 * @access public
1148 * @static
1149 */
1150 static function sendEmail(
1151 &$contactDetails,
1152 &$subject,
1153 &$text,
1154 &$html,
1155 $emailAddress,
1156 $userID = NULL,
1157 $from = NULL,
1158 $attachments = NULL,
1159 $cc = NULL,
1160 $bcc = NULL,
1161 $contactIds // FIXME a param with no default shouldn't be last
1162 ) {
1163 // get the contact details of logged in contact, which we set as from email
1164 if ($userID == NULL) {
1165 $session = CRM_Core_Session::singleton();
1166 $userID = $session->get('userID');
1167 }
1168
1169 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1170 if (!$fromEmail) {
1171 return array(count($contactDetails), 0, count($contactDetails));
1172 }
1173 if (!trim($fromDisplayName)) {
1174 $fromDisplayName = $fromEmail;
1175 }
1176
1177 // CRM-4575
1178 // token replacement of addressee/email/postal greetings
1179 // get the tokens added in subject and message
1180 $subjectToken = CRM_Utils_Token::getTokens($subject);
1181 $messageToken = CRM_Utils_Token::getTokens($text);
1182 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1183
1184 if (!$from) {
1185 $from = "$fromDisplayName <$fromEmail>";
1186 }
1187
1188 //create the meta level record first ( email activity )
1189 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1190 'Email',
1191 'name'
1192 );
1193
1194 // CRM-6265: save both text and HTML parts in details (if present)
1195 if ($html and $text) {
1196 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1197 }
1198 else {
1199 $details = $html ? $html : $text;
1200 }
1201
1202 $activityParams = array(
1203 'source_contact_id' => $userID,
1204 'activity_type_id' => $activityTypeID,
1205 'activity_date_time' => date('YmdHis'),
1206 'subject' => $subject,
1207 'details' => $details,
1208 // FIXME: check for name Completed and get ID from that lookup
1209 'status_id' => 2,
1210 );
1211
1212 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1213 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1214
1215 // add the attachments to activity params here
1216 if ($attachments) {
1217 // first process them
1218 $activityParams = array_merge($activityParams,
1219 $attachments
1220 );
1221 }
1222
1223 $activity = self::create($activityParams);
1224
1225 // get the set of attachments from where they are stored
1226 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity',
1227 $activity->id
1228 );
1229 $returnProperties = array();
1230 if (isset($messageToken['contact'])) {
1231 foreach ($messageToken['contact'] as $key => $value) {
1232 $returnProperties[$value] = 1;
1233 }
1234 }
1235
1236 if (isset($subjectToken['contact'])) {
1237 foreach ($subjectToken['contact'] as $key => $value) {
1238 if (!isset($returnProperties[$value])) {
1239 $returnProperties[$value] = 1;
1240 }
1241 }
1242 }
1243
1244
1245 // get token details for contacts, call only if tokens are used
1246 $details = array();
1247 if (!empty($returnProperties)) {
1248 list($details) = CRM_Utils_Token::getTokenDetails(
1249 $contactIds,
1250 $returnProperties,
1251 NULL, NULL, FALSE,
1252 $messageToken,
1253 'CRM_Activity_BAO_Activity'
1254 );
1255 }
1256
1257 // call token hook
1258 $tokens = array();
1259 CRM_Utils_Hook::tokens($tokens);
1260 $categories = array_keys($tokens);
1261
1262 $escapeSmarty = FALSE;
1263 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1264 $smarty = CRM_Core_Smarty::singleton();
1265 $escapeSmarty = TRUE;
1266 }
1267
1268 $sent = $notSent = array();
1269 foreach ($contactDetails as $values) {
1270 $contactId = $values['contact_id'];
1271 $emailAddress = $values['email'];
1272
1273 if (!empty($details) && is_array($details["{$contactId}"])) {
1274 // unset email from details since it always returns primary email address
1275 unset($details["{$contactId}"]['email']);
1276 unset($details["{$contactId}"]['email_id']);
1277 $values = array_merge($values, $details["{$contactId}"]);
1278 }
1279
1280 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1281 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1282
1283 //CRM-4539
1284 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1285 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1286 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1287 }
1288 else {
1289 $tokenText = NULL;
1290 }
1291
1292 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1293 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1294 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1295 }
1296 else {
1297 $tokenHtml = NULL;
1298 }
1299
1300 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1301 // also add the contact tokens to the template
1302 $smarty->assign_by_ref('contact', $values);
1303
1304 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1305 $tokenText = $smarty->fetch("string:$tokenText");
1306 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1307 }
1308
1309 $sent = FALSE;
1310 if (self::sendMessage(
1311 $from,
1312 $userID,
1313 $contactId,
1314 $tokenSubject,
1315 $tokenText,
1316 $tokenHtml,
1317 $emailAddress,
1318 $activity->id,
1319 $attachments,
1320 $cc,
1321 $bcc
1322 )) {
1323 $sent = TRUE;
1324 }
1325 }
1326
1327 return array($sent, $activity->id);
1328 }
1329
1330 static function sendSMS(&$contactDetails,
1331 &$activityParams,
1332 &$smsParams = array(),
1333 &$contactIds,
1334 $userID = NULL
1335 ) {
1336 if ($userID == NULL) {
1337 $session = CRM_Core_Session::singleton();
1338 $userID = $session->get('userID');
1339 }
1340
1341 $text = &$activityParams['text_message'];
1342 $html = &$activityParams['html_message'];
1343
1344 // CRM-4575
1345 // token replacement of addressee/email/postal greetings
1346 // get the tokens added in subject and message
1347 $messageToken = CRM_Utils_Token::getTokens($text);
1348 $messageToken = array_merge($messageToken,
1349 CRM_Utils_Token::getTokens($html)
1350 );
1351
1352 //create the meta level record first ( sms activity )
1353 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1354 'SMS',
1355 'name'
1356 );
1357
1358 // CRM-6265: save both text and HTML parts in details (if present)
1359 if ($html and $text) {
1360 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1361 }
1362 else {
1363 $details = $html ? $html : $text;
1364 }
1365
1366 $activitySubject = $activityParams['activity_subject'];
1367 $activityParams = array(
1368 'source_contact_id' => $userID,
1369 'activity_type_id' => $activityTypeID,
1370 'activity_date_time' => date('YmdHis'),
1371 'subject' => $activitySubject,
1372 'details' => $details,
1373 // FIXME: check for name Completed and get ID from that lookup
1374 'status_id' => 2,
1375 );
1376
1377 $activity = self::create($activityParams);
1378 $activityID = $activity->id;
1379
1380 $returnProperties = array();
1381
1382 if (isset($messageToken['contact'])) {
1383 foreach ($messageToken['contact'] as $key => $value) {
1384 $returnProperties[$value] = 1;
1385 }
1386 }
1387
1388 // call token hook
1389 $tokens = array();
1390 CRM_Utils_Hook::tokens($tokens);
1391 $categories = array_keys($tokens);
1392
1393 // get token details for contacts, call only if tokens are used
1394 $details = array();
1395 if (!empty($returnProperties) || !empty($tokens)) {
1396 list($details) = CRM_Utils_Token::getTokenDetails($contactIds,
1397 $returnProperties,
1398 NULL, NULL, FALSE,
1399 $messageToken,
1400 'CRM_Activity_BAO_Activity'
1401 );
1402 }
1403
1404 $success = 0;
1405 $escapeSmarty = $sent = FALSE;
1406 foreach ($contactDetails as $values) {
1407 $contactId = $values['contact_id'];
1408
1409 if (!empty($details) && is_array($details["{$contactId}"])) {
1410 // unset email from details since it always returns primary email address
1411 unset($details["{$contactId}"]['email']);
1412 unset($details["{$contactId}"]['email_id']);
1413 $values = array_merge($values, $details["{$contactId}"]);
1414 }
1415
1416 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1417 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1418
1419 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1420 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1421
1422 // Only send if the phone is of type mobile
1423 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1424 if ($values['phone_type_id'] == CRM_Utils_Array::value('Mobile', $phoneTypes)) {
1425 $smsParams['To'] = $values['phone'];
1426 }
1427 else {
1428 $smsParams['To'] = '';
1429 }
1430
1431 if (self::sendSMSMessage(
1432 $contactId,
1433 $tokenText,
1434 $tokenHtml,
1435 $smsParams,
1436 $activityID
1437 )) {
1438 // even a single successful delivery should set this falg to true
1439 $sent = TRUE;
1440 $success++;
1441 }
1442 }
1443
1444 return array($sent, $activity->id, $success);
1445 }
1446
1447 /**
1448 * send the sms message to a specific contact
1449 *
1450 * @param int $toID the contact id of the recipient
1451 * @param int $activityID the activity ID that tracks the message
1452 * @param array $smsParams the params used for sending sms
1453 *
1454 * @return boolean true if successfull else false.
1455 * @access public
1456 * @static
1457 */
1458 static function sendSMSMessage($toID,
1459 &$tokenText,
1460 &$tokenHtml,
1461 $smsParams = array(),
1462 $activityID
1463 ) {
1464 $toDoNotSms = "";
1465 $toPhoneNumber = "";
1466
1467 if ($smsParams['To']) {
1468 $toPhoneNumber = trim($smsParams['To']);
1469 }
1470 elseif ($toID) {
1471 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1472 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
1473 //to get primary mobile ph,if not get a first mobile ph
1474 if (!empty($toPhoneNumbers)) {
1475 $toPhoneNumerDetails = reset($toPhoneNumbers);
1476 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumerDetails);
1477 //contact allows to send sms
1478 $toDoNotSms = 0;
1479 }
1480 }
1481
1482 // make sure both phone are valid
1483 // and that the recipient wants to receive sms
1484 if (empty($toPhoneNumber) or $toDoNotSms) {
1485 return FALSE;
1486 }
1487
1488 $message = $tokenHtml ? $tokenHtml : $tokenText;
1489 $recipient = $smsParams['To'];
1490 $smsParams['contact_id'] = $toID;
1491 $smsParams['parent_activity_id'] = $activityID;
1492
1493 $providerObj = CRM_SMS_Provider::singleton(array('provider_id' => $smsParams['provider_id']));
1494 if (!$providerObj->send($recipient, $smsParams, $message, NULL)) {
1495 return FALSE;
1496 }
1497
1498 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
1499 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1500
1501
1502 // add activity target record for every sms that is send
1503 $activityTargetParams = array(
1504 'activity_id' => $activityID,
1505 'contact_id' => $toID,
1506 'record_type_id' => $targetID
1507 );
1508 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1509
1510 return TRUE;
1511 }
1512
1513 /**
1514 * send the message to a specific contact
1515 *
1516 * @param string $from the name and email of the sender
1517 * @param int $toID the contact id of the recipient
1518 * @param string $subject the subject of the message
1519 * @param string $message the message contents
1520 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1521 * @param int $activityID the activity ID that tracks the message
1522 *
1523 * @return boolean true if successfull else false.
1524 * @access public
1525 * @static
1526 */
1527 static function sendMessage($from,
1528 $fromID,
1529 $toID,
1530 &$subject,
1531 &$text_message,
1532 &$html_message,
1533 $emailAddress,
1534 $activityID,
1535 $attachments = NULL,
1536 $cc = NULL,
1537 $bcc = NULL
1538 ) {
1539 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1540 if ($emailAddress) {
1541 $toEmail = trim($emailAddress);
1542 }
1543
1544 // make sure both email addresses are valid
1545 // and that the recipient wants to receive email
1546 if (empty($toEmail) or $toDoNotEmail) {
1547 return FALSE;
1548 }
1549 if (!trim($toDisplayName)) {
1550 $toDisplayName = $toEmail;
1551 }
1552
1553 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
1554 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1555 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1556 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1557
1558 // create the params array
1559 $mailParams = array(
1560 'groupName' => 'Activity Email Sender',
1561 'from' => $from,
1562 'toName' => $toDisplayName,
1563 'toEmail' => $toEmail,
1564 'subject' => $subject,
1565 'cc' => $cc,
1566 'bcc' => $bcc,
1567 'text' => $text_message,
1568 'html' => $html_message,
1569 'attachments' => $attachments,
1570 );
1571
1572 if (!CRM_Utils_Mail::send($mailParams)) {
1573 return FALSE;
1574 }
1575
1576 // add activity target record for every mail that is send
1577 $activityTargetParams = array(
1578 'activity_id' => $activityID,
1579 'contact_id' => $toID,
1580 'record_type_id' => $targetID
1581 );
1582 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1583 return TRUE;
1584 }
1585
1586 /**
1587 * combine all the importable fields from the lower levels object
1588 *
1589 * The ordering is important, since currently we do not have a weight
1590 * scheme. Adding weight is super important and should be done in the
1591 * next week or so, before this can be called complete.
1592 *
1593 * @param NULL
1594 *
1595 * @return array array of importable Fields
1596 * @access public
1597 * @static
1598 */
1599 static function &importableFields($status = FALSE) {
1600 if (!self::$_importableFields) {
1601 if (!self::$_importableFields) {
1602 self::$_importableFields = array();
1603 }
1604 if (!$status) {
1605 $fields = array('' => array('title' => ts('- do not import -')));
1606 }
1607 else {
1608 $fields = array('' => array('title' => ts('- Activity Fields -')));
1609 }
1610
1611 $tmpFields = CRM_Activity_DAO_Activity::import();
1612 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1613
1614 // Using new Dedupe rule.
1615 $ruleParams = array(
1616 'contact_type' => 'Individual',
1617 'used' => 'Unsupervised',
1618 );
1619 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1620
1621 $tmpConatctField = array();
1622 if (is_array($fieldsArray)) {
1623 foreach ($fieldsArray as $value) {
1624 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1625 $value,
1626 'id',
1627 'column_name'
1628 );
1629 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1630 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1631 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1632 }
1633 }
1634 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1635 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1636 $fields = array_merge($fields, $tmpConatctField);
1637 $fields = array_merge($fields, $tmpFields);
1638 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
1639 self::$_importableFields = $fields;
1640 }
1641 return self::$_importableFields;
1642 }
1643
1644 /**
1645 * To get the Activities of a target contact
1646 *
1647 * @param $contactId Integer ContactId of the contact whose activities
1648 * need to find
1649 *
1650 * @return array array of activity fields
1651 * @access public
1652 */
1653 static function getContactActivity($contactId) {
1654 $activities = array();
1655 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
1656 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1657 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1658 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1659
1660
1661 // First look for activities where contactId is one of the targets
1662 $query = "
1663 SELECT activity_id, record_type_id
1664 FROM civicrm_activity_contact
1665 WHERE contact_id = $contactId
1666 ";
1667 $dao = CRM_Core_DAO::executeQuery($query);
1668 while ($dao->fetch()) {
1669 if ($dao->record_type_id == $targetID ) {
1670 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
1671 }
1672 else if ($dao->record_type_id == $assigneeID) {
1673 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1674 }
1675 else {
1676 // do source stuff here
1677 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
1678 }
1679 }
1680
1681 $activityIds = array_keys($activities);
1682 if (count($activityIds) < 1) {
1683 return array();
1684 }
1685
1686 $activityIds = implode(',', $activityIds);
1687 $query = "
1688 SELECT activity.id as activity_id,
1689 activity_type_id,
1690 subject, location, activity_date_time, details, status_id
1691 FROM civicrm_activity activity
1692 WHERE activity.id IN ($activityIds)";
1693
1694 $dao = CRM_Core_DAO::executeQuery($query);
1695
1696 $activityTypes = CRM_Core_OptionGroup::values('activity_type');
1697 $activityStatuses = CRM_Core_OptionGroup::values('activity_status');
1698
1699 while ($dao->fetch()) {
1700 $activities[$dao->activity_id]['id'] = $dao->activity_id;
1701 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
1702 $activities[$dao->activity_id]['subject'] = $dao->subject;
1703 $activities[$dao->activity_id]['location'] = $dao->location;
1704 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
1705 $activities[$dao->activity_id]['details'] = $dao->details;
1706 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
1707 $activities[$dao->activity_id]['activity_name'] = $activityTypes[$dao->activity_type_id];
1708 $activities[$dao->activity_id]['status'] = $activityStatuses[$dao->status_id];
1709
1710 // set to null if not set
1711 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
1712 $activities[$dao->activity_id]['source_contact_id'] = NULL;
1713 }
1714 }
1715 return $activities;
1716 }
1717
1718 /**
1719 * Function to add activity for Membership/Event/Contribution
1720 *
1721 * @param object $activity (reference) perticular component object
1722 * @param string $activityType for Membership Signup or Renewal
1723 *
1724 *
1725 * @static
1726 * @access public
1727 */
1728 static function addActivity(&$activity,
1729 $activityType = 'Membership Signup',
1730 $targetContactID = NULL
1731 ) {
1732 if ($activity->__table == 'civicrm_membership') {
1733 $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id);
1734
1735 if (!$membershipType) {
1736 $membershipType = ts('Membership');
1737 }
1738
1739 $subject = "{$membershipType}";
1740
1741 if (!empty($activity->source) && $activity->source != 'null') {
1742 $subject .= " - {$activity->source}";
1743 }
1744
1745 if ($activity->owner_membership_id) {
1746 $query = "
1747 SELECT display_name
1748 FROM civicrm_contact, civicrm_membership
1749 WHERE civicrm_contact.id = civicrm_membership.contact_id
1750 AND civicrm_membership.id = $activity->owner_membership_id
1751 ";
1752 $displayName = CRM_Core_DAO::singleValueQuery($query);
1753 $subject .= " (by {$displayName})";
1754 }
1755
1756 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id);
1757 // CRM-72097 changed from start date to today
1758 $date = date('YmdHis');
1759 $component = 'Membership';
1760 }
1761 elseif ($activity->__table == 'civicrm_participant') {
1762 $event = CRM_Event_BAO_Event::getEvents(TRUE, $activity->event_id, TRUE, FALSE);
1763
1764 $roles = CRM_Event_PseudoConstant::participantRole();
1765 $status = CRM_Event_PseudoConstant::participantStatus();
1766
1767 $subject = $event[$activity->event_id];
1768 if (CRM_Utils_Array::value($activity->role_id, $roles)) {
1769 $subject .= ' - ' . $roles[$activity->role_id];
1770 }
1771 if (CRM_Utils_Array::value($activity->status_id, $status)) {
1772 $subject .= ' - ' . $status[$activity->status_id];
1773 }
1774 $date = date('YmdHis');
1775 if ($activityType != 'Email') {
1776 $activityType = 'Event Registration';
1777 }
1778 $component = 'Event';
1779 }
1780 elseif ($activity->__table == 'civicrm_contribution') {
1781 //create activity record only for Completed Contributions
1782 if ($activity->contribution_status_id != 1) {
1783 return;
1784 }
1785
1786 $subject = NULL;
1787
1788 $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency);
1789 if (!empty($activity->source) && $activity->source != 'null') {
1790 $subject .= " - {$activity->source}";
1791 }
1792 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
1793 $activityType = $component = 'Contribution';
1794 }
1795 $activityParams = array(
1796 'source_contact_id' => $activity->contact_id,
1797 'source_record_id' => $activity->id,
1798 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1799 $activityType,
1800 'name'
1801 ),
1802 'subject' => $subject,
1803 'activity_date_time' => $date,
1804 'is_test' => $activity->is_test,
1805 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
1806 'Completed',
1807 'name'
1808 ),
1809 'skipRecentView' => TRUE,
1810 'campaign_id' => $activity->campaign_id,
1811 );
1812
1813 // create activity with target contacts
1814 $session = CRM_Core_Session::singleton();
1815 $id = $session->get('userID');
1816 if ($id) {
1817 $activityParams['source_contact_id'] = $id;
1818 $activityParams['target_contact_id'][] = $activity->contact_id;
1819 }
1820
1821 //CRM-4027
1822 if ($targetContactID) {
1823 $activityParams['target_contact_id'][] = $targetContactID;
1824 }
1825 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
1826 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
1827 return FALSE;
1828 }
1829 }
1830
1831 /**
1832 * Function to get Parent activity for currently viewd activity
1833 *
1834 * @param int $activityId current activity id
1835 *
1836 * @return int $parentId Id of parent acyivity otherwise false.
1837 * @access public
1838 */
1839 static function getParentActivity($activityId) {
1840 static $parentActivities = array();
1841
1842 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1843
1844 if (!array_key_exists($activityId, $parentActivities)) {
1845 $parentActivities[$activityId] = array();
1846
1847 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1848 $activityId,
1849 'parent_id'
1850 );
1851
1852 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1853 }
1854
1855 return $parentActivities[$activityId];
1856 }
1857
1858 /**
1859 * Function to get total count of prior revision of currently viewd activity
1860 *
1861 * @param int $activityId current activity id
1862 *
1863 * @return int $params count of prior acyivities otherwise false.
1864 * @access public
1865 */
1866 static function getPriorCount($activityID) {
1867 static $priorCounts = array();
1868
1869 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1870
1871 if (!array_key_exists($activityID, $priorCounts)) {
1872 $priorCounts[$activityID] = array();
1873 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1874 $activityID,
1875 'original_id'
1876 );
1877 $count = 0;
1878 if ($originalID) {
1879 $query = "
1880 SELECT count( id ) AS cnt
1881 FROM civicrm_activity
1882 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1883 AND is_current_revision = 0
1884 AND id < {$activityID}
1885 ";
1886 $params = array(1 => array($originalID, 'Integer'));
1887 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1888 }
1889 $priorCounts[$activityID] = $count ? $count : 0;
1890 }
1891
1892 return $priorCounts[$activityID];
1893 }
1894
1895 /**
1896 * Function to get all prior activities of currently viewd activity
1897 *
1898 * @param int $activityId current activity id
1899 *
1900 * @return array $result prior acyivities info.
1901 * @access public
1902 */
1903 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1904 static $priorActivities = array();
1905
1906 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1907 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1908
1909 if (!array_key_exists($index, $priorActivities)) {
1910 $priorActivities[$index] = array();
1911
1912 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1913 $activityID,
1914 'original_id'
1915 );
1916 if ($originalID) {
1917 $query = "
1918 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1919 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1920 WHERE (ca.id = %1 OR ca.original_id = %1)
1921 AND cl.entity_table = 'civicrm_activity'
1922 AND cl.entity_id = ca.id
1923 AND cl.modified_id = c.id
1924 ";
1925 if ($onlyPriorRevisions) {
1926 $query .= " AND ca.id < {$activityID}";
1927 }
1928 $query .= " ORDER BY ca.id DESC";
1929
1930 $params = array(1 => array($originalID, 'Integer'));
1931 $dao = CRM_Core_DAO::executeQuery($query, $params);
1932
1933 while ($dao->fetch()) {
1934 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
1935 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
1936 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
1937 $priorActivities[$index][$dao->activityID]['link'] = 'javascript:viewActivity( $dao->activityID );';
1938 }
1939 $dao->free();
1940 }
1941 }
1942 return $priorActivities[$index];
1943 }
1944
1945 /**
1946 * Function to find the latest revision of a given activity
1947 *
1948 * @param int $activityId prior activity id
1949 *
1950 * @return int $params current activity id.
1951 * @access public
1952 */
1953 static function getLatestActivityId($activityID) {
1954 static $latestActivityIds = array();
1955
1956 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1957
1958 if (!array_key_exists($activityID, $latestActivityIds)) {
1959 $latestActivityIds[$activityID] = array();
1960
1961 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1962 $activityID,
1963 'original_id'
1964 );
1965 if ($originalID) {
1966 $activityID = $originalID;
1967 }
1968 $params = array(1 => array($activityID, 'Integer'));
1969 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1970
1971 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
1972 }
1973
1974 return $latestActivityIds[$activityID];
1975 }
1976
1977 /**
1978 * Function to create a follow up a given activity
1979 *
1980 * @activityId int activity id of parent activity
1981 *
1982 * @param array $activity details
1983 *
1984 * @access public
1985 */
1986 static function createFollowupActivity($activityId, $params) {
1987 if (!$activityId) {
1988 return;
1989 }
1990
1991 $session = CRM_Core_Session::singleton();
1992
1993 $followupParams = array();
1994 $followupParams['parent_id'] = $activityId;
1995 $followupParams['source_contact_id'] = $session->get('userID');
1996 $followupParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
1997
1998 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1999 // Get Subject of Follow-up Activiity, CRM-4491
2000 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
2001
2002 //create target contact for followup
2003 if (CRM_Utils_Array::value('target_contact_id', $params)) {
2004 $followupParams['target_contact_id'] = $params['target_contact_id'];
2005 }
2006
2007 $followupParams['activity_date_time'] = CRM_Utils_Date::processDate($params['followup_date'],
2008 $params['followup_date_time']
2009 );
2010 $followupActivity = self::create($followupParams);
2011
2012 return $followupActivity;
2013 }
2014
2015 /**
2016 * Function to get Activity specific File according activity type Id.
2017 *
2018 * @param int $activityTypeId activity id
2019 *
2020 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2021 *
2022 * @static
2023 */
2024 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2025 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2026
2027 if ($activityTypes[$activityTypeId]['name']) {
2028 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2029 }
2030 else {
2031 return FALSE;
2032 }
2033
2034 global $civicrm_root;
2035 $config = CRM_Core_Config::singleton();
2036 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2037 if (empty($config->customPHPPathDir)) {
2038 return FALSE;
2039 }
2040 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2041 return FALSE;
2042 }
2043 }
2044
2045 return $activityTypeFile;
2046 }
2047
2048 /**
2049 * Function to restore the activity
2050 *
2051 * @param array $params associated array
2052 *
2053 * @return void
2054 * @access public
2055 *
2056 */
2057 public static function restoreActivity(&$params) {
2058 $activity = new CRM_Activity_DAO_Activity();
2059 $activity->copyValues($params);
2060
2061 $activity->is_deleted = 0;
2062 $result = $activity->save();
2063
2064 return $result;
2065 }
2066
2067 /**
2068 * Get the exportable fields for Activities
2069 *
2070 * @param string $name if it is called by case $name = Case else $name = Activity
2071 *
2072 * @return array array of exportable Fields
2073 * @access public
2074 * @static
2075 */
2076 static function &exportableFields($name = 'Activity') {
2077 if (!isset(self::$_exportableFields[$name])) {
2078 self::$_exportableFields[$name] = array();
2079
2080 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2081 // my case hence we have defined fields as case_*
2082 if ($name == 'Activity') {
2083 $exportableFields = CRM_Activity_DAO_Activity::export();
2084 if (isset($exportableFields['activity_campaign_id'])) {
2085 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2086 }
2087 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2088 $exportableFields['source_contact'] = array(
2089 'title' => ts('Source Contact'),
2090 'type' => CRM_Utils_Type::T_STRING,
2091 );
2092
2093
2094 $Activityfields = array(
2095 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2096 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2097 );
2098 $fields = array_merge($Activityfields, $exportableFields);
2099 }
2100 else {
2101 //set title to activity fields
2102 $fields = array(
2103 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
2104 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
2105 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
2106 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type::T_DATE),
2107 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2108 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2109 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
2110 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
2111 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
2112 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type::T_BOOLEAN),
2113 );
2114
2115 // add custom data for cases
2116 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Case'));
2117 }
2118
2119 // add custom data for case activities
2120 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2121
2122 self::$_exportableFields[$name] = $fields;
2123 }
2124 return self::$_exportableFields[$name];
2125 }
2126
2127 /**
2128 * Get the allowed profile fields for Activities
2129 *
2130 * @return array array of activity profile Fields
2131 * @access public
2132 */
2133 static function getProfileFields() {
2134 $exportableFields = self::exportableFields('Activity');
2135 $skipFields = array('activity_id', 'activity_type', 'source_contact_id', 'activity_campaign', 'activity_is_test', 'is_current_revision', 'activity_is_deleted',);
2136 $config = CRM_Core_Config::singleton();
2137 if (!in_array('CiviCampaign', $config->enableComponents)) {
2138 $skipFields[] = 'activity_engagement_level';
2139 }
2140
2141 foreach ($skipFields as $field) {
2142 if (isset($exportableFields[$field])) {
2143 unset($exportableFields[$field]);
2144 }
2145 }
2146
2147 // hack to use 'activity_type_id' instead of 'activity_type'
2148 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2149 unset($exportableFields['activity_status']);
2150
2151 return $exportableFields;
2152 }
2153
2154 /**
2155 * This function delete activity record related to contact record,
2156 * when there are no target and assignee record w/ other contact.
2157 *
2158 * @param int $contactId contactId
2159 *
2160 * @return true/null
2161 * @access public
2162 */
2163 public static function cleanupActivity($contactId) {
2164 $result = NULL;
2165 if (!$contactId) {
2166 return $result;
2167 }
2168 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
2169 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2170
2171 $transaction = new CRM_Core_Transaction();
2172
2173 // delete activity if there is no record in
2174 // civicrm_activity_contact
2175 // pointing to any other contact record.
2176 $activityContact = new CRM_Activity_DAO_ActivityContact();
2177 $activityContact->contact_id = $contactId;
2178 $activityContact->record_type_id = $sourceID;
2179 $activityContact->find();
2180
2181 while ($activityContact->fetch()) {
2182 // finally delete activity.
2183 if (CRM_Core_DAO::singleValueQuery($sql)) {
2184 $activityParams = array('id' => $activityContact->activity_id);
2185 $result = self::deleteActivity($activityParams);
2186 }
2187 }
2188
2189 $activityContact->free();
2190 $transaction->commit();
2191
2192 return $result;
2193 }
2194
2195 /**
2196 * Does user has sufficient permission for view/edit activity record.
2197 *
2198 * @param int $activityId activity record id.
2199 * @param int $action edit/view
2200 *
2201 * @return boolean $allow true/false
2202 * @access public
2203 */
2204 public static function checkPermission($activityId, $action) {
2205 $allow = FALSE;
2206 if (!$activityId ||
2207 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2208 ) {
2209 return $allow;
2210 }
2211
2212 $activity = new CRM_Activity_DAO_Activity();
2213 $activity->id = $activityId;
2214 if (!$activity->find(TRUE)) {
2215 return $allow;
2216 }
2217
2218 //component related permissions.
2219 $compPermissions = array(
2220 'CiviCase' => array('administer CiviCase',
2221 'access my cases and activities',
2222 'access all cases and activities',
2223 ),
2224 'CiviMail' => array('access CiviMail'),
2225 'CiviEvent' => array('access CiviEvent'),
2226 'CiviGrant' => array('access CiviGrant'),
2227 'CiviPledge' => array('access CiviPledge'),
2228 'CiviMember' => array('access CiviMember'),
2229 'CiviReport' => array('access CiviReport'),
2230 'CiviContribute' => array('access CiviContribute'),
2231 'CiviCampaign' => array('administer CiviCampaign'),
2232 );
2233
2234 //return early when it is case activity.
2235 $isCaseActivity = CRM_Case_BAO_Case::isCaseActivity($activityId);
2236 //check for civicase related permission.
2237 if ($isCaseActivity) {
2238 $allow = FALSE;
2239 foreach ($compPermissions['CiviCase'] as $per) {
2240 if (CRM_Core_Permission::check($per)) {
2241 $allow = TRUE;
2242 break;
2243 }
2244 }
2245
2246 //check for case specific permissions.
2247 if ($allow) {
2248 $oper = 'view';
2249 if ($action == CRM_Core_Action::UPDATE) {
2250 $oper = 'edit';
2251 }
2252 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2253 $oper,
2254 $activity->activity_type_id
2255 );
2256 }
2257
2258 return $allow;
2259 }
2260
2261 //first check the component permission.
2262 $sql = "
2263 SELECT component_id
2264 FROM civicrm_option_value val
2265 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2266 WHERE val.value = %2";
2267 $params = array(1 => array('activity_type', 'String'),
2268 2 => array($activity->activity_type_id, 'Integer'),
2269 );
2270 $componentId = CRM_Core_DAO::singleValueQuery($sql, $params);
2271
2272 if ($componentId) {
2273 $componentName = CRM_Core_Component::getComponentName($componentId);
2274 $compPermission = CRM_Utils_Array::value($componentName, $compPermissions);
2275
2276 //here we are interesting in any single permission.
2277 if (is_array($compPermission)) {
2278 foreach ($compPermission as $per) {
2279 if (CRM_Core_Permission::check($per)) {
2280 $allow = TRUE;
2281 break;
2282 }
2283 }
2284 }
2285 }
2286
2287 //check for this permission related to contact.
2288 $permission = CRM_Core_Permission::VIEW;
2289 if ($action == CRM_Core_Action::UPDATE) {
2290 $permission = CRM_Core_Permission::EDIT;
2291 }
2292
2293 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
2294 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2295 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2296 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2297
2298 //check for source contact.
2299 if (!$componentId || $allow) {
2300 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2301 $allow = CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission);
2302 }
2303
2304 //check for target and assignee contacts.
2305 if ($allow) {
2306 //first check for supper permission.
2307 $supPermission = 'view all contacts';
2308 if ($action == CRM_Core_Action::UPDATE) {
2309 $supPermission = 'edit all contacts';
2310 }
2311 $allow = CRM_Core_Permission::check($supPermission);
2312
2313 //user might have sufficient permission, through acls.
2314 if (!$allow) {
2315 $allow = TRUE;
2316 //get the target contacts.
2317 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
2318 foreach ($targetContacts as $cnt => $contactId) {
2319 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2320 $allow = FALSE;
2321 break;
2322 }
2323 }
2324
2325 //get the assignee contacts.
2326 if ($allow) {
2327 $assigneeContacts = CRM_Activity_BAO_Contact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
2328 foreach ($assigneeContacts as $cnt => $contactId) {
2329 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2330 $allow = FALSE;
2331 break;
2332 }
2333 }
2334 }
2335 }
2336 }
2337
2338 return $allow;
2339 }
2340
2341 /**
2342 * This function is a wrapper for ajax activity selector
2343 *
2344 * @param array $params associated array for params record id.
2345 *
2346 * @return array $contactActivities associated array of contact activities
2347 * @access public
2348 */
2349 public static function getContactActivitySelector(&$params) {
2350 // format the params
2351 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2352 $params['rowCount'] = $params['rp'];
2353 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2354 $params['caseId'] = NULL;
2355 $context = CRM_Utils_Array::value('context', $params);
2356
2357 // get contact activities
2358 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2359
2360 // add total
2361 $params['total'] = CRM_Activity_BAO_Activity::getActivitiesCount($params);
2362
2363 // format params and add links
2364 $contactActivities = array();
2365
2366 if (!empty($activities)) {
2367 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2368
2369 // check logged in user for permission
2370 $page = new CRM_Core_Page();
2371 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2372 $permissions = array($page->_permission);
2373 if (CRM_Core_Permission::check('delete activities')) {
2374 $permissions[] = CRM_Core_Permission::DELETE;
2375 }
2376
2377 $mask = CRM_Core_Action::mask($permissions);
2378
2379 foreach ($activities as $activityId => $values) {
2380 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2381 $contactActivities[$activityId]['subject'] = $values['subject'];
2382 if ($params['contact_id'] == $values['source_contact_id']) {
2383 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2384 }
2385 elseif ($values['source_contact_id']) {
2386 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System::href($values['source_contact_name'], 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2387 }
2388 else {
2389 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2390 }
2391
2392 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2393 $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");
2394 }
2395 elseif (CRM_Utils_Array::value('recipients', $values)) {
2396 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2397 }
2398 elseif (!$values['target_contact_name']) {
2399 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2400 }
2401 elseif (!empty($values['target_contact_name'])) {
2402 $count = 0;
2403 $contactActivities[$activityId]['target_contact'] = '';
2404 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2405 if ($tcID && $count < 5) {
2406 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2407 $count++;
2408 if ($count) {
2409 $contactActivities[$activityId]['target_contact'] .= ";&nbsp;";
2410 }
2411
2412 if ($count == 4) {
2413 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2414 break;
2415 }
2416 }
2417 }
2418 }
2419
2420 if (empty($values['assignee_contact_name'])) {
2421 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2422 }
2423 elseif (!empty($values['assignee_contact_name'])) {
2424 $count = 0;
2425 $contactActivities[$activityId]['assignee_contact'] = '';
2426 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2427 if ($acID && $count < 5) {
2428 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2429 $count++;
2430 if ($count) {
2431 $contactActivities[$activityId]['assignee_contact'] .= ";&nbsp;";
2432 }
2433
2434 if ($count == 4) {
2435 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2436 break;
2437 }
2438 }
2439 }
2440 }
2441 if ( $values['activity_type'] == 'Bulk Email'){
2442 $contactActivities[$activityId]['openstats'] = "Opens: ".
2443 count(CRM_Mailing_Event_BAO_Opened::getRows(
2444 CRM_Utils_Array::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, $params['contact_id']
2445 )
2446 )."<br />Clicks:" .
2447 count(CRM_Mailing_Event_BAO_TrackableURLOpen::getRows(
2448 CRM_Utils_Array::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, NULL, $params['contact_id']
2449 ) );
2450 }else {
2451 $contactActivities[$activityId]['openstats'] = '';
2452 }
2453
2454 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2455 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2456
2457 // add class to this row if overdue
2458 $contactActivities[$activityId]['class'] = '';
2459 if (CRM_Utils_Date::overdue(CRM_Utils_Array::value('activity_date_time', $values))
2460 && CRM_Utils_Array::value('status_id', $values) == 1
2461 ) {
2462 $contactActivities[$activityId]['class'] = 'status-overdue';
2463 }
2464 else {
2465 $contactActivities[$activityId]['class'] = 'status-ontime';
2466 }
2467
2468 // build links
2469 $contactActivities[$activityId]['links'] = '';
2470 $accessMailingReport = FALSE;
2471 if (CRM_Utils_Array::value('mailingId', $values)) {
2472 $accessMailingReport = TRUE;
2473 }
2474
2475 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2476 CRM_Utils_Array::value('activity_type_id', $values),
2477 CRM_Utils_Array::value('source_record_id', $values),
2478 $accessMailingReport,
2479 CRM_Utils_Array::value('activity_id', $values)
2480 );
2481
2482 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2483
2484 $contactActivities[$activityId]['links'] = CRM_Core_Action::formLink($actionLinks,
2485 $actionMask,
2486 array(
2487 'id' => $values['activity_id'],
2488 'cid' => $params['contact_id'],
2489 'cxt' => $context,
2490 'caseid' => CRM_Utils_Array::value('case_id', $values),
2491 )
2492 );
2493 }
2494 }
2495
2496 return $contactActivities;
2497 }
2498
2499 /*
2500 * Used to copy custom fields and attachments from an existing activity to another.
2501 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2502 */
2503 static function copyExtendedActivityData($params) {
2504 // attach custom data to the new activity
2505 $customParams = $htmlType = array();
2506 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
2507
2508 if (!empty($customValues)) {
2509 $fieldIds = implode(', ', array_keys($customValues));
2510 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2511 $result = CRM_Core_DAO::executeQuery($sql);
2512
2513 while ($result->fetch()) {
2514 $htmlType[] = $result->id;
2515 }
2516
2517 foreach ($customValues as $key => $value) {
2518 if ($value !== NULL) { // CRM-10542
2519 if (in_array($key, $htmlType)) {
2520 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
2521 $customParams["custom_{$key}_-1"] = array(
2522 'name' => $fileValues[0],
2523 'path' => $fileValues[1],
2524 );
2525 }
2526 else {
2527 $customParams["custom_{$key}_-1"] = $value;
2528 }
2529 }
2530 }
2531 CRM_Core_BAO_CustomValueTable::postProcess($customParams, CRM_Core_DAO::$_nullArray, 'civicrm_activity',
2532 $params['mainActivityId'], 'Activity'
2533 );
2534 }
2535
2536 // copy activity attachments ( if any )
2537 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2538 }
2539
2540 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2541 $activityContact = new CRM_Activity_BAO_ActivityContact();
2542 $activityContact->activity_id = $activityId;
2543 if ($recordTypeID) {
2544 $activityContact->record_type_id = $recordTypeID;
2545 }
2546 if ($activityContact->find(TRUE)) {
2547 return $activityContact->$column;
2548 }
2549 return NULL;
2550 }
2551
2552 public static function getSourceContactID($activityId) {
2553 static $sourceID = NULL;
2554 if (!$sourceID) {
2555 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
2556 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2557 }
2558
2559 return self::getActivityContact($activityId, $sourceID);
2560 }
2561
2562 }
2563