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