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