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