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