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