Merge pull request #20168 from larssandergreen/add-recurring-filter-to-contribution...
[civicrm-core.git] / api / v3 / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This api exposes CiviCRM Activity records.
14 *
15 * @package CiviCRM_APIv3
16 */
17
18 /**
19 * Creates or updates an Activity.
20 *
21 * @param array $params
22 * Array per getfields documentation.
23 *
24 * @throws API_Exception
25 * @return array
26 * API result array
27 */
28 function civicrm_api3_activity_create($params) {
29 $isNew = empty($params['id']);
30
31 if (empty($params['id'])) {
32 // an update does not require any mandatory parameters
33 civicrm_api3_verify_one_mandatory($params,
34 NULL,
35 [
36 'activity_name',
37 'activity_type_id',
38 'activity_label',
39 ]
40 );
41 }
42
43 // check for various error and required conditions
44 // note that almost all the processing in there should be managed by the wrapper layer
45 // & should be removed - needs testing
46 $errors = _civicrm_api3_activity_check_params($params);
47
48 // this should not be required as should throw exception rather than return errors -
49 //needs testing
50 if (!empty($errors)) {
51 return $errors;
52 }
53
54 // processing for custom data
55 $values = $activityArray = [];
56 _civicrm_api3_custom_format_params($params, $values, 'Activity');
57
58 if (!empty($values['custom'])) {
59 $params['custom'] = $values['custom'];
60 }
61
62 // this should be set as a default rather than hard coded
63 // needs testing
64 $params['skipRecentView'] = TRUE;
65
66 // If this is a case activity, see if there is an existing activity
67 // and set it as an old revision. Also retrieve details we'll need.
68 // this handling should all be moved to the BAO layer
69 $case_id = '';
70 $createRevision = FALSE;
71 $oldActivityValues = [];
72 // Lookup case id if not supplied
73 if (!isset($params['case_id']) && !empty($params['id'])) {
74 $params['case_id'] = CRM_Core_DAO::singleValueQuery("SELECT case_id FROM civicrm_case_activity WHERE activity_id = " . (int) $params['id']);
75 }
76 if (!empty($params['case_id'])) {
77 $case_id = $params['case_id'];
78 if (!empty($params['id']) && Civi::settings()->get('civicaseActivityRevisions')) {
79 $oldActivityParams = ['id' => $params['id']];
80 if (!$oldActivityValues) {
81 CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
82 }
83 if (empty($oldActivityValues)) {
84 throw new API_Exception(ts("Unable to locate existing activity."));
85 }
86 else {
87 $activityDAO = new CRM_Activity_DAO_Activity();
88 $activityDAO->id = $params['id'];
89 $activityDAO->is_current_revision = 0;
90 if (!$activityDAO->save()) {
91 throw new API_Exception(ts("Unable to revision existing case activity."));
92 }
93 $createRevision = TRUE;
94 }
95 }
96 }
97
98 if ($case_id && $createRevision) {
99 // This is very similar to the copy-to-case action.
100 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
101 $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
102 }
103 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
104 $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
105 }
106 $oldActivityValues['mode'] = 'copy';
107 $oldActivityValues['caseID'] = $case_id;
108 $oldActivityValues['activityID'] = $oldActivityValues['id'];
109 $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
110
111 $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
112 if (empty($copyToCase['error_msg'])) {
113 // now fix some things that are different from copy-to-case
114 // then fall through to the create below to update with the passed in params
115 $params['id'] = $copyToCase['newId'];
116 $params['is_auto'] = 0;
117 $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
118 }
119 else {
120 throw new API_Exception(ts("Unable to create new revision of case activity."));
121 }
122 }
123
124 // create activity
125 $activityBAO = CRM_Activity_BAO_Activity::create($params);
126
127 if (isset($activityBAO->id)) {
128 if ($case_id && $isNew && !$createRevision) {
129 // If this is a brand new case activity, add to case(s)
130 foreach ((array) $case_id as $singleCaseId) {
131 $caseActivityParams = ['activity_id' => $activityBAO->id, 'case_id' => $singleCaseId];
132 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
133 }
134 }
135
136 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
137 return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
138 }
139 }
140
141 /**
142 * Specify Meta data for create.
143 *
144 * Note that this data is retrievable via the getfields function and is used for pre-filling defaults and
145 * ensuring mandatory requirements are met.
146 *
147 * @param array $params
148 * Array of parameters determined by getfields.
149 */
150 function _civicrm_api3_activity_create_spec(&$params) {
151
152 $params['status_id']['api.aliases'] = ['activity_status'];
153
154 $params['assignee_contact_id'] = [
155 'name' => 'assignee_id',
156 'title' => 'Activity Assignee',
157 'description' => 'Contact(s) assigned to this activity.',
158 'type' => 1,
159 'FKClassName' => 'CRM_Contact_DAO_Contact',
160 'FKApiName' => 'Contact',
161 ];
162 $params['target_contact_id'] = [
163 'name' => 'target_id',
164 'title' => 'Activity Target',
165 'description' => 'Contact(s) participating in this activity.',
166 'type' => 1,
167 'FKClassName' => 'CRM_Contact_DAO_Contact',
168 'FKApiName' => 'Contact',
169 ];
170
171 $params['source_contact_id'] = [
172 'name' => 'source_contact_id',
173 'title' => 'Activity Source Contact',
174 'description' => 'Person who created this activity. Defaults to current user.',
175 'type' => 1,
176 'FKClassName' => 'CRM_Contact_DAO_Contact',
177 'api.default' => 'user_contact_id',
178 'FKApiName' => 'Contact',
179 'api.required' => TRUE,
180 ];
181
182 $params['case_id'] = [
183 'name' => 'case_id',
184 'title' => 'Case ID',
185 'description' => 'For creating an activity as part of a case.',
186 'type' => 1,
187 'FKClassName' => 'CRM_Case_DAO_Case',
188 'FKApiName' => 'Case',
189 ];
190
191 $params['activity_date_time']['api.default'] = 'now';
192
193 }
194
195 /**
196 * Specify Metadata for get.
197 *
198 * @param array $params
199 */
200 function _civicrm_api3_activity_get_spec(&$params) {
201 $params['tag_id'] = [
202 'title' => 'Tags',
203 'description' => 'Find activities with specified tags.',
204 'type' => CRM_Utils_Type::T_INT,
205 'FKClassName' => 'CRM_Core_DAO_Tag',
206 'FKApiName' => 'Tag',
207 'supports_joins' => TRUE,
208 ];
209 $params['file_id'] = [
210 'title' => 'Attached Files',
211 'description' => 'Find activities with attached files.',
212 'type' => CRM_Utils_Type::T_INT,
213 'FKClassName' => 'CRM_Core_DAO_File',
214 'FKApiName' => 'File',
215 ];
216 $params['case_id'] = [
217 'title' => 'Cases',
218 'description' => 'Find activities within specified cases.',
219 'type' => CRM_Utils_Type::T_INT,
220 'FKClassName' => 'CRM_Case_DAO_Case',
221 'FKApiName' => 'Case',
222 'supports_joins' => TRUE,
223 ];
224 $params['contact_id'] = [
225 'title' => 'Activity Contact ID',
226 'description' => 'Find activities involving this contact (as target, source, OR assignee).',
227 'type' => CRM_Utils_Type::T_INT,
228 'FKClassName' => 'CRM_Contact_DAO_Contact',
229 'FKApiName' => 'Contact',
230 ];
231 $params['target_contact_id'] = [
232 'title' => 'Target Contact ID',
233 'description' => 'Find activities with specified target contact.',
234 'type' => CRM_Utils_Type::T_INT,
235 'FKClassName' => 'CRM_Contact_DAO_Contact',
236 'FKApiName' => 'Contact',
237 ];
238 $params['source_contact_id'] = [
239 'title' => 'Source Contact ID',
240 'description' => 'Find activities with specified source contact.',
241 'type' => CRM_Utils_Type::T_INT,
242 'FKClassName' => 'CRM_Contact_DAO_Contact',
243 'FKApiName' => 'Contact',
244 ];
245 $params['assignee_contact_id'] = [
246 'title' => 'Assignee Contact ID',
247 'description' => 'Find activities with specified assignee contact.',
248 'type' => CRM_Utils_Type::T_INT,
249 'FKClassName' => 'CRM_Contact_DAO_Contact',
250 'FKApiName' => 'Contact',
251 ];
252 $params['is_overdue'] = [
253 'title' => 'Is Activity Overdue',
254 'description' => 'Incomplete activities with a past date.',
255 'type' => CRM_Utils_Type::T_BOOLEAN,
256 ];
257 }
258
259 /**
260 * Gets a CiviCRM activity according to parameters.
261 *
262 * @param array $params
263 * Array per getfields documentation.
264 *
265 * @return array
266 * API result array
267 *
268 * @throws \API_Exception
269 * @throws \CiviCRM_API3_Exception
270 * @throws \Civi\API\Exception\UnauthorizedException
271 */
272 function civicrm_api3_activity_get($params) {
273 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
274 $sql = CRM_Utils_SQL_Select::fragment();
275 _civicrm_activity_get_handleSourceContactNameOrderBy($params, $options, $sql);
276
277 _civicrm_api3_activity_get_extraFilters($params, $sql);
278
279 // Handle is_overdue sort
280 if (!empty($options['sort'])) {
281 $sort = explode(', ', $options['sort']);
282
283 foreach ($sort as $index => &$sortString) {
284 // Get sort field and direction
285 list($sortField, $dir) = array_pad(explode(' ', $sortString), 2, 'ASC');
286 if ($sortField == 'is_overdue') {
287 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
288 $sql->orderBy("IF((a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete)), 0, 1) $dir", NULL, $index);
289 // Replace the sort with a placeholder which will be ignored by sql
290 $sortString = '(1)';
291 }
292 }
293 $params['options']['sort'] = implode(', ', $sort);
294 }
295
296 // Ensure there's enough data for calculating is_overdue
297 if (!empty($options['return']['is_overdue']) && (empty($options['return']['status_id']) || empty($options['return']['activity_date_time']))) {
298 $options['return']['status_id'] = $options['return']['activity_date_time'] = 1;
299 $params['return'] = array_keys($options['return']);
300 }
301
302 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $sql);
303 if ($options['is_count']) {
304 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
305 }
306
307 $activities = _civicrm_api3_activity_get_formatResult($params, $activities, $options);
308 //legacy custom data get - so previous formatted response is still returned too
309 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
310 }
311
312 /**
313 * Handle source_contact_name as a sort parameter.
314 *
315 * This is passed from the activity selector - e.g search results or contact tab.
316 *
317 * It's a non-standard handling but this api already handles variations on handling source_contact
318 * as a filter & as a field so it's in keeping with that. Source contact has a one-one relationship
319 * with activity table.
320 *
321 * Test coverage in CRM_Activity_BAO_ActivtiyTest::testGetActivitiesforContactSummaryWithSortOptions
322 *
323 * @param array $params
324 * @param array $options
325 * @param CRM_Utils_SQL_Select $sql
326 */
327 function _civicrm_activity_get_handleSourceContactNameOrderBy(&$params, &$options, $sql) {
328 $sourceContactID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
329 if (!empty($options['sort'])
330 && in_array($options['sort'], [
331 'source_contact_name',
332 'source_contact_name desc',
333 'source_contact_name asc',
334 ])) {
335 $order = substr($options['sort'], -4) === 'desc' ? 'desc' : 'asc';
336 $sql->join(
337 'source_contact',
338 "LEFT JOIN
339 civicrm_activity_contact ac ON (ac.activity_id = a.id AND record_type_id = #sourceContactID)
340 LEFT JOIN civicrm_contact c ON c.id = ac.contact_id",
341 ['sourceContactID' => $sourceContactID]
342 );
343 $sql->orderBy("c.display_name $order");
344 unset($options['sort'], $params['options']['sort']);
345 }
346 }
347
348 /**
349 * Support filters beyond what basic_get can do.
350 *
351 * @param array $params
352 * @param CRM_Utils_SQL_Select $sql
353 * @throws \CiviCRM_API3_Exception
354 * @throws \Exception
355 */
356 function _civicrm_api3_activity_get_extraFilters(&$params, &$sql) {
357 // Filter by activity contacts
358 $activityContactOptions = [
359 'contact_id' => NULL,
360 'target_contact_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets'),
361 'source_contact_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'),
362 'assignee_contact_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Assignees'),
363 ];
364 foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
365 if (!empty($params[$activityContactName])) {
366 if (!is_array($params[$activityContactName])) {
367 $params[$activityContactName] = ['=' => $params[$activityContactName]];
368 }
369 $clause = \CRM_Core_DAO::createSQLFilter('contact_id', $params[$activityContactName]);
370 $typeClause = $activityContactValue ? 'record_type_id = #typeId AND ' : '';
371 $sql->where("a.id IN (SELECT activity_id FROM civicrm_activity_contact WHERE $typeClause !clause)",
372 ['#typeId' => $activityContactValue, '!clause' => $clause]
373 );
374 }
375 }
376
377 // Handle is_overdue filter
378 // Boolean calculated field - does not support operators
379 if (isset($params['is_overdue'])) {
380 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
381 if ($params['is_overdue']) {
382 $sql->where('a.activity_date_time < NOW()');
383 $sql->where("a.status_id IN ($incomplete)");
384 }
385 else {
386 $sql->where("(a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete))");
387 }
388 }
389
390 // Define how to handle filters on some related entities.
391 // Subqueries are nice in (a) avoiding duplicates and (b) when the result
392 // list is expected to be bite-sized. Joins are nice (a) with larger
393 // datasets and (b) checking for non-existent relations.
394 $rels = [
395 'tag_id' => [
396 'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_activity" AND !clause)',
397 'join' => '!joinType civicrm_entity_tag !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
398 'column' => 'tag_id',
399 ],
400 'file_id' => [
401 'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_file WHERE entity_table = "civicrm_activity" AND !clause)',
402 'join' => '!joinType civicrm_entity_file !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
403 'column' => 'file_id',
404 ],
405 'case_id' => [
406 'subquery' => 'a.id IN (SELECT activity_id FROM civicrm_case_activity WHERE !clause)',
407 'join' => '!joinType civicrm_case_activity !alias ON (!alias.activity_id = a.id)',
408 'column' => 'case_id',
409 ],
410 ];
411 foreach ($rels as $filter => $relSpec) {
412 if (!empty($params[$filter])) {
413 if (!is_array($params[$filter])) {
414 $params[$filter] = ['=' => $params[$filter]];
415 }
416 // $mode is one of ('LEFT JOIN', 'INNER JOIN', 'SUBQUERY')
417 $mode = isset($params[$filter]['IS NULL']) ? 'LEFT JOIN' : 'SUBQUERY';
418 if ($mode === 'SUBQUERY') {
419 $clause = \CRM_Core_DAO::createSQLFilter($relSpec['column'], $params[$filter]);
420 if ($clause) {
421 $sql->where($relSpec['subquery'], ['!clause' => $clause]);
422 }
423 }
424 else {
425 $alias = 'actjoin_' . $filter;
426 $clause = \CRM_Core_DAO::createSQLFilter($alias . "." . $relSpec['column'], $params[$filter]);
427 if ($clause) {
428 $sql->join($alias, $relSpec['join'], ['!alias' => $alias, 'joinType' => $mode]);
429 $sql->where($clause);
430 }
431 }
432 }
433 }
434 }
435
436 /**
437 * Given a list of activities, append any extra data requested about the activities.
438 *
439 * @note Called by civicrm-core and CiviHR
440 *
441 * @param array $params
442 * API request parameters.
443 * @param array $activities
444 * @param array $options
445 * Options array (pre-processed to extract 'return' from params).
446 *
447 * @return array
448 * new activities list
449 */
450 function _civicrm_api3_activity_get_formatResult($params, $activities, $options) {
451 if (!$activities) {
452 return $activities;
453 }
454
455 $returns = $options['return'];
456 foreach ($params as $n => $v) {
457 // @todo - the per-parsing on options should have already done this.
458 if (substr($n, 0, 7) == 'return.') {
459 $returnkey = substr($n, 7);
460 $returns[$returnkey] = $v;
461 }
462 }
463
464 _civicrm_api3_activity_fill_activity_contact_names($activities, $params, $returns);
465
466 $tagGet = ['tag_id', 'entity_id'];
467 $caseGet = $caseIds = [];
468 foreach (array_keys($returns) as $key) {
469 if (strpos($key, 'tag_id.') === 0) {
470 $tagGet[] = $key;
471 $returns['tag_id'] = 1;
472 }
473 if (strpos($key, 'case_id.') === 0) {
474 $caseGet[] = str_replace('case_id.', '', $key);
475 $returns['case_id'] = 1;
476 }
477 }
478
479 foreach ($returns as $n => $v) {
480 switch ($n) {
481 case 'assignee_contact_id':
482 case 'target_contact_id':
483 foreach ($activities as &$activity) {
484 if (!isset($activity[$n])) {
485 $activity[$n] = [];
486 }
487 }
488
489 case 'source_contact_id':
490 break;
491
492 case 'tag_id':
493 $tags = civicrm_api3('EntityTag', 'get', [
494 'entity_table' => 'civicrm_activity',
495 'entity_id' => ['IN' => array_keys($activities)],
496 'return' => $tagGet,
497 'options' => ['limit' => 0],
498 ]);
499 foreach ($tags['values'] as $tag) {
500 $key = (int) $tag['entity_id'];
501 unset($tag['entity_id'], $tag['id']);
502 $activities[$key]['tag_id'][$tag['tag_id']] = $tag;
503 }
504 break;
505
506 case 'file_id':
507 $dao = CRM_Core_DAO::executeQuery("SELECT entity_id, file_id FROM civicrm_entity_file WHERE entity_table = 'civicrm_activity' AND entity_id IN (%1)",
508 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]]);
509 while ($dao->fetch()) {
510 $activities[$dao->entity_id]['file_id'][] = $dao->file_id;
511 }
512 break;
513
514 case 'case_id':
515 $dao = CRM_Core_DAO::executeQuery("SELECT activity_id, case_id FROM civicrm_case_activity WHERE activity_id IN (%1)",
516 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]]);
517 while ($dao->fetch()) {
518 $activities[$dao->activity_id]['case_id'][] = $dao->case_id;
519 $caseIds[$dao->case_id] = $dao->case_id;
520 }
521 break;
522
523 case 'is_overdue':
524 foreach ($activities as $key => $activityArray) {
525 $activities[$key]['is_overdue'] = (int) CRM_Activity_BAO_Activity::isOverdue($activityArray);
526 }
527 break;
528
529 default:
530 if (substr($n, 0, 6) == 'custom') {
531 $returnProperties[$n] = $v;
532 }
533 }
534 }
535
536 // Fetch case fields via the join syntax
537 // Note this is limited to the first case if the activity belongs to more than one
538 if ($caseGet && $caseIds) {
539 $cases = civicrm_api3('Case', 'get', [
540 'id' => ['IN' => $caseIds],
541 'options' => ['limit' => 0],
542 'check_permissions' => !empty($params['check_permissions']),
543 'return' => $caseGet,
544 ]);
545 foreach ($activities as &$activity) {
546 if (!empty($activity['case_id'])) {
547 $case = $cases['values'][$activity['case_id'][0]] ?? NULL;
548 if ($case) {
549 foreach ($case as $key => $value) {
550 if ($key != 'id') {
551 $activity['case_id.' . $key] = $value;
552 }
553 }
554 }
555 }
556 }
557 }
558
559 // Legacy extras
560 if (!empty($params['contact_id'])) {
561 $statusOptions = CRM_Activity_BAO_Activity::buildOptions('status_id', 'get');
562 $typeOptions = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
563 foreach ($activities as $key => &$activityArray) {
564 if (!empty($activityArray['status_id'])) {
565 $activityArray['status'] = $statusOptions[$activityArray['status_id']];
566 }
567 if (!empty($activityArray['activity_type_id'])) {
568 $activityArray['activity_name'] = $typeOptions[$activityArray['activity_type_id']];
569 }
570 }
571 }
572
573 if (!empty($returnProperties) || !empty($params['contact_id'])) {
574 foreach ($activities as $activityId => $values) {
575 //@todo - should possibly load activity type id if not loaded (update with id)
576 _civicrm_api3_custom_data_get($activities[$activityId], CRM_Utils_Array::value('check_permissions', $params), 'Activity', $activityId, NULL, CRM_Utils_Array::value('activity_type_id', $values));
577 }
578 }
579 return $activities;
580 }
581
582 /**
583 * Append activity contact details to activity results.
584 *
585 * Adds id & name of activity contacts to results array if check_permissions
586 * does not block access to them.
587 *
588 * For historical reasons source_contact_id is always added & is not an array.
589 * The others are added depending on requested return params.
590 *
591 * @param array $activities
592 * @param array $params
593 * @param array $returns
594 */
595 function _civicrm_api3_activity_fill_activity_contact_names(&$activities, $params, $returns) {
596 $contactTypes = array_flip(CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate'));
597 $assigneeType = $contactTypes['Activity Assignees'];
598 $targetType = $contactTypes['Activity Targets'];
599 $sourceType = $contactTypes['Activity Source'];
600 $typeMap = [
601 $assigneeType => 'assignee',
602 $sourceType => 'source',
603 $targetType => 'target',
604 ];
605
606 $activityContactTypes = [$sourceType];
607
608 if (!empty($returns['target_contact_name']) || !empty($returns['target_contact_id'])) {
609 $activityContactTypes[] = $targetType;
610 }
611 if (!empty($returns['assignee_contact_name']) || (!empty($returns['assignee_contact_id']))) {
612 $activityContactTypes[] = $assigneeType;
613 }
614 $activityContactParams = [
615 'activity_id' => ['IN' => array_keys($activities)],
616 'return' => [
617 'activity_id',
618 'record_type_id',
619 'contact_id.display_name',
620 'contact_id.sort_name',
621 'contact_id',
622 ],
623 'options' => ['limit' => 0],
624 'check_permissions' => !empty($params['check_permissions']),
625 ];
626 if (count($activityContactTypes) < 3) {
627 $activityContactParams['record_type_id'] = ['IN' => $activityContactTypes];
628 }
629 $activityContacts = civicrm_api3('ActivityContact', 'get', $activityContactParams)['values'];
630 foreach ($activityContacts as $activityContact) {
631 $contactID = $activityContact['contact_id'];
632 $recordType = $typeMap[$activityContact['record_type_id']];
633 if (in_array($recordType, ['target', 'assignee'])) {
634 $activities[$activityContact['activity_id']][$recordType . '_contact_id'][] = $contactID;
635 $activities[$activityContact['activity_id']][$recordType . '_contact_name'][$contactID] = $activityContact['contact_id.display_name'] ?? '';
636 $activities[$activityContact['activity_id']][$recordType . '_contact_sort_name'][$contactID] = $activityContact['contact_id.sort_name'] ?? '';
637 }
638 else {
639 $activities[$activityContact['activity_id']]['source_contact_id'] = $contactID;
640 $activities[$activityContact['activity_id']]['source_contact_name'] = $activityContact['contact_id.display_name'] ?? '';
641 $activities[$activityContact['activity_id']]['source_contact_sort_name'] = $activityContact['contact_id.sort_name'] ?? '';
642 }
643 }
644 }
645
646 /**
647 * Delete a specified Activity.
648 *
649 * @param array $params
650 * Array holding 'id' of activity to be deleted.
651 *
652 * @throws API_Exception
653 *
654 * @return array
655 * API result array
656 */
657 function civicrm_api3_activity_delete($params) {
658
659 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
660 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
661 }
662 else {
663 throw new API_Exception('Could not delete Activity: ' . (int) $params['id']);
664 }
665 }
666
667 /**
668 * Check for required params.
669 *
670 * @param array $params
671 * Associated array of fields.
672 *
673 * @throws API_Exception
674 * @throws Exception
675 * @return array
676 * array with errors
677 */
678 function _civicrm_api3_activity_check_params(&$params) {
679 $activityIds = [
680 'activity' => $params['id'] ?? NULL,
681 'parent' => $params['parent_id'] ?? NULL,
682 'original' => $params['original_id'] ?? NULL,
683 ];
684
685 foreach ($activityIds as $id => $value) {
686 if ($value &&
687 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
688 ) {
689 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
690 }
691 }
692 // this should be handled by wrapper layer & probably the api would already manage it
693 //correctly by doing pseudoconstant validation
694 // needs testing
695 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
696 $activityName = $params['activity_name'] ?? NULL;
697 $activityName = ucfirst($activityName);
698 $activityLabel = $params['activity_label'] ?? NULL;
699 if ($activityLabel) {
700 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
701 }
702
703 $activityTypeId = $params['activity_type_id'] ?? NULL;
704
705 if ($activityName || $activityLabel) {
706 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
707
708 if (!$activityTypeIdInList) {
709 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
710 throw new Exception($errorString);
711 }
712 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
713 throw new API_Exception('Mismatch in Activity');
714 }
715 $params['activity_type_id'] = $activityTypeIdInList;
716 }
717 elseif ($activityTypeId &&
718 !array_key_exists($activityTypeId, $activityTypes)
719 ) {
720 throw new API_Exception('Invalid Activity Type ID');
721 }
722
723 // check for activity duration minutes
724 // this should be validated @ the wrapper layer not here
725 // needs testing
726 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
727 throw new API_Exception('Invalid Activity Duration (in minutes)');
728 }
729
730 return NULL;
731 }
732
733 /**
734 * Get parameters for activity list.
735 *
736 * @see _civicrm_api3_generic_getlist_params
737 *
738 * @param array $request
739 * API request.
740 */
741 function _civicrm_api3_activity_getlist_params(&$request) {
742 $fieldsToReturn = [
743 'activity_date_time',
744 'activity_type_id',
745 'subject',
746 'source_contact_id',
747 $request['id_field'],
748 $request['label_field'],
749 ];
750 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
751 $request['params']['options']['sort'] = 'activity_date_time DESC';
752 $request['params'] += [
753 'is_current_revision' => 1,
754 'is_deleted' => 0,
755 ];
756 }
757
758 /**
759 * Get output for activity list.
760 *
761 * @see _civicrm_api3_generic_getlist_output
762 *
763 * @param array $result
764 * @param array $request
765 *
766 * @return array
767 */
768 function _civicrm_api3_activity_getlist_output($result, $request) {
769 $output = [];
770 if (!empty($result['values'])) {
771 foreach ($result['values'] as $row) {
772 $data = [
773 'id' => $row[$request['id_field']],
774 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
775 'description' => [
776 CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
777 ],
778 ];
779 if (!empty($row['activity_date_time'])) {
780 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
781 }
782 if (!empty($row['source_contact_id'])) {
783 $data['description'][] = ts('By %1', [
784 1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
785 ]);
786 }
787 // Add repeating info
788 $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_activity');
789 $data['extra']['is_recur'] = FALSE;
790 if ($repeat) {
791 $data['suffix'] = ts('(%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]);
792 $data['extra']['is_recur'] = TRUE;
793 }
794 $output[] = $data;
795 }
796 }
797 return $output;
798 }