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