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