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