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