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