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