3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 * This api exposes CiviCRM Activity records.
15 * @package CiviCRM_APIv3
19 * Creates or updates an Activity.
21 * @param array $params
22 * Array per getfields documentation.
24 * @throws API_Exception
28 function civicrm_api3_activity_create($params) {
29 $isNew = empty($params['id']);
31 if (empty($params['id'])) {
32 // an update does not require any mandatory parameters
33 civicrm_api3_verify_one_mandatory($params,
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);
48 // this should not be required as should throw exception rather than return errors -
50 if (!empty($errors)) {
54 // processing for custom data
55 $values = $activityArray = [];
56 _civicrm_api3_custom_format_params($params, $values, 'Activity');
58 if (!empty($values['custom'])) {
59 $params['custom'] = $values['custom'];
62 // this should be set as a default rather than hard coded
64 $params['skipRecentView'] = TRUE;
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
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']);
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);
83 if (empty($oldActivityValues)) {
84 throw new API_Exception(ts("Unable to locate existing activity."));
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."));
93 $createRevision = TRUE;
98 $deleteActivityAssignment = FALSE;
99 if (isset($params['assignee_contact_id'])) {
100 $deleteActivityAssignment = TRUE;
103 $deleteActivityTarget = FALSE;
104 if (isset($params['target_contact_id'])) {
105 $deleteActivityTarget = TRUE;
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);
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']));
117 if (!CRM_Utils_Array
::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
118 $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
120 $oldActivityValues['mode'] = 'copy';
121 $oldActivityValues['caseID'] = $case_id;
122 $oldActivityValues['activityID'] = $oldActivityValues['id'];
123 $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
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'];
134 throw new API_Exception(ts("Unable to create new revision of case activity."));
139 $activityBAO = CRM_Activity_BAO_Activity
::create($params);
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);
150 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id
]);
151 return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
156 * Specify Meta data for create.
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.
161 * @param array $params
162 * Array of parameters determined by getfields.
164 function _civicrm_api3_activity_create_spec(&$params) {
166 $params['status_id']['api.aliases'] = ['activity_status'];
168 $params['assignee_contact_id'] = [
169 'name' => 'assignee_id',
170 'title' => 'Activity Assignee',
171 'description' => 'Contact(s) assigned to this activity.',
173 'FKClassName' => 'CRM_Contact_DAO_Contact',
174 'FKApiName' => 'Contact',
176 $params['target_contact_id'] = [
177 'name' => 'target_id',
178 'title' => 'Activity Target',
179 'description' => 'Contact(s) participating in this activity.',
181 'FKClassName' => 'CRM_Contact_DAO_Contact',
182 'FKApiName' => 'Contact',
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.',
190 'FKClassName' => 'CRM_Contact_DAO_Contact',
191 'api.default' => 'user_contact_id',
192 'FKApiName' => 'Contact',
193 'api.required' => TRUE,
196 $params['case_id'] = [
198 'title' => 'Case ID',
199 'description' => 'For creating an activity as part of a case.',
201 'FKClassName' => 'CRM_Case_DAO_Case',
202 'FKApiName' => 'Case',
208 * Specify Metadata for get.
210 * @param array $params
212 function _civicrm_api3_activity_get_spec(&$params) {
213 $params['tag_id'] = [
215 'description' => 'Find activities with specified tags.',
216 'type' => CRM_Utils_Type
::T_INT
,
217 'FKClassName' => 'CRM_Core_DAO_Tag',
218 'FKApiName' => 'Tag',
219 'supports_joins' => TRUE,
221 $params['file_id'] = [
222 'title' => 'Attached Files',
223 'description' => 'Find activities with attached files.',
224 'type' => CRM_Utils_Type
::T_INT
,
225 'FKClassName' => 'CRM_Core_DAO_File',
226 'FKApiName' => 'File',
228 $params['case_id'] = [
230 'description' => 'Find activities within specified cases.',
231 'type' => CRM_Utils_Type
::T_INT
,
232 'FKClassName' => 'CRM_Case_DAO_Case',
233 'FKApiName' => 'Case',
234 'supports_joins' => TRUE,
236 $params['contact_id'] = [
237 'title' => 'Activity Contact ID',
238 'description' => 'Find activities involving this contact (as target, source, OR assignee).',
239 'type' => CRM_Utils_Type
::T_INT
,
240 'FKClassName' => 'CRM_Contact_DAO_Contact',
241 'FKApiName' => 'Contact',
243 $params['target_contact_id'] = [
244 'title' => 'Target Contact ID',
245 'description' => 'Find activities with specified target contact.',
246 'type' => CRM_Utils_Type
::T_INT
,
247 'FKClassName' => 'CRM_Contact_DAO_Contact',
248 'FKApiName' => 'Contact',
250 $params['source_contact_id'] = [
251 'title' => 'Source Contact ID',
252 'description' => 'Find activities with specified source contact.',
253 'type' => CRM_Utils_Type
::T_INT
,
254 'FKClassName' => 'CRM_Contact_DAO_Contact',
255 'FKApiName' => 'Contact',
257 $params['assignee_contact_id'] = [
258 'title' => 'Assignee Contact ID',
259 'description' => 'Find activities with specified assignee contact.',
260 'type' => CRM_Utils_Type
::T_INT
,
261 'FKClassName' => 'CRM_Contact_DAO_Contact',
262 'FKApiName' => 'Contact',
264 $params['is_overdue'] = [
265 'title' => 'Is Activity Overdue',
266 'description' => 'Incomplete activities with a past date.',
267 'type' => CRM_Utils_Type
::T_BOOLEAN
,
272 * Gets a CiviCRM activity according to parameters.
274 * @param array $params
275 * Array per getfields documentation.
280 * @throws \API_Exception
281 * @throws \CiviCRM_API3_Exception
282 * @throws \Civi\API\Exception\UnauthorizedException
284 function civicrm_api3_activity_get($params) {
285 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
286 $sql = CRM_Utils_SQL_Select
::fragment();
287 _civicrm_activity_get_handleSourceContactNameOrderBy($params, $options, $sql);
289 _civicrm_api3_activity_get_extraFilters($params, $sql);
291 // Handle is_overdue sort
292 if (!empty($options['sort'])) {
293 $sort = explode(', ', $options['sort']);
295 foreach ($sort as $index => &$sortString) {
296 // Get sort field and direction
297 list($sortField, $dir) = array_pad(explode(' ', $sortString), 2, 'ASC');
298 if ($sortField == 'is_overdue') {
299 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::INCOMPLETE
)));
300 $sql->orderBy("IF((a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete)), 0, 1) $dir", NULL, $index);
301 // Replace the sort with a placeholder which will be ignored by sql
305 $params['options']['sort'] = implode(', ', $sort);
308 // Ensure there's enough data for calculating is_overdue
309 if (!empty($options['return']['is_overdue']) && (empty($options['return']['status_id']) ||
empty($options['return']['activity_date_time']))) {
310 $options['return']['status_id'] = $options['return']['activity_date_time'] = 1;
311 $params['return'] = array_keys($options['return']);
314 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__
), $params, FALSE, 'Activity', $sql);
315 if ($options['is_count']) {
316 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
319 $activities = _civicrm_api3_activity_get_formatResult($params, $activities, $options);
320 //legacy custom data get - so previous formatted response is still returned too
321 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
325 * Handle source_contact_name as a sort parameter.
327 * This is passed from the activity selector - e.g search results or contact tab.
329 * It's a non-standard handling but this api already handles variations on handling source_contact
330 * as a filter & as a field so it's in keeping with that. Source contact has a one-one relationship
331 * with activity table.
333 * Test coverage in CRM_Activity_BAO_ActivtiyTest::testGetActivitiesforContactSummaryWithSortOptions
335 * @param array $params
336 * @param array $options
337 * @param CRM_Utils_SQL_Select $sql
339 function _civicrm_activity_get_handleSourceContactNameOrderBy(&$params, &$options, $sql) {
340 $sourceContactID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
341 if (!empty($options['sort'])
342 && in_array($options['sort'], [
343 'source_contact_name',
344 'source_contact_name desc',
345 'source_contact_name asc',
347 $order = substr($options['sort'], -4) === 'desc' ?
'desc' : 'asc';
351 civicrm_activity_contact ac ON (ac.activity_id = a.id AND record_type_id = #sourceContactID)
352 LEFT JOIN civicrm_contact c ON c.id = ac.contact_id",
353 ['sourceContactID' => $sourceContactID]
355 $sql->orderBy("c.display_name $order");
356 unset($options['sort'], $params['options']['sort']);
361 * Support filters beyond what basic_get can do.
363 * @param array $params
364 * @param CRM_Utils_SQL_Select $sql
365 * @throws \CiviCRM_API3_Exception
368 function _civicrm_api3_activity_get_extraFilters(&$params, &$sql) {
369 // Filter by activity contacts
370 $activityContactOptions = [
371 'contact_id' => NULL,
372 'target_contact_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets'),
373 'source_contact_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'),
374 'assignee_contact_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Assignees'),
376 foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
377 if (!empty($params[$activityContactName])) {
378 if (!is_array($params[$activityContactName])) {
379 $params[$activityContactName] = ['=' => $params[$activityContactName]];
381 $clause = \CRM_Core_DAO
::createSQLFilter('contact_id', $params[$activityContactName]);
382 $typeClause = $activityContactValue ?
'record_type_id = #typeId AND ' : '';
383 $sql->where("a.id IN (SELECT activity_id FROM civicrm_activity_contact WHERE $typeClause !clause)",
384 ['#typeId' => $activityContactValue, '!clause' => $clause]
389 // Handle is_overdue filter
390 // Boolean calculated field - does not support operators
391 if (isset($params['is_overdue'])) {
392 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::INCOMPLETE
)));
393 if ($params['is_overdue']) {
394 $sql->where('a.activity_date_time < NOW()');
395 $sql->where("a.status_id IN ($incomplete)");
398 $sql->where("(a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete))");
402 // Define how to handle filters on some related entities.
403 // Subqueries are nice in (a) avoiding duplicates and (b) when the result
404 // list is expected to be bite-sized. Joins are nice (a) with larger
405 // datasets and (b) checking for non-existent relations.
408 'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_activity" AND !clause)',
409 'join' => '!joinType civicrm_entity_tag !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
410 'column' => 'tag_id',
413 'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_file WHERE entity_table = "civicrm_activity" AND !clause)',
414 'join' => '!joinType civicrm_entity_file !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
415 'column' => 'file_id',
418 'subquery' => 'a.id IN (SELECT activity_id FROM civicrm_case_activity WHERE !clause)',
419 'join' => '!joinType civicrm_case_activity !alias ON (!alias.activity_id = a.id)',
420 'column' => 'case_id',
423 foreach ($rels as $filter => $relSpec) {
424 if (!empty($params[$filter])) {
425 if (!is_array($params[$filter])) {
426 $params[$filter] = ['=' => $params[$filter]];
428 // $mode is one of ('LEFT JOIN', 'INNER JOIN', 'SUBQUERY')
429 $mode = isset($params[$filter]['IS NULL']) ?
'LEFT JOIN' : 'SUBQUERY';
430 if ($mode === 'SUBQUERY') {
431 $clause = \CRM_Core_DAO
::createSQLFilter($relSpec['column'], $params[$filter]);
433 $sql->where($relSpec['subquery'], ['!clause' => $clause]);
437 $alias = 'actjoin_' . $filter;
438 $clause = \CRM_Core_DAO
::createSQLFilter($alias . "." . $relSpec['column'], $params[$filter]);
440 $sql->join($alias, $relSpec['join'], ['!alias' => $alias, 'joinType' => $mode]);
441 $sql->where($clause);
449 * Given a list of activities, append any extra data requested about the activities.
451 * @note Called by civicrm-core and CiviHR
453 * @param array $params
454 * API request parameters.
455 * @param array $activities
456 * @param array $options
457 * Options array (pre-processed to extract 'return' from params).
460 * new activities list
462 function _civicrm_api3_activity_get_formatResult($params, $activities, $options) {
467 $returns = $options['return'];
468 foreach ($params as $n => $v) {
469 // @todo - the per-parsing on options should have already done this.
470 if (substr($n, 0, 7) == 'return.') {
471 $returnkey = substr($n, 7);
472 $returns[$returnkey] = $v;
476 _civicrm_api3_activity_fill_activity_contact_names($activities, $params, $returns);
478 $tagGet = ['tag_id', 'entity_id'];
479 $caseGet = $caseIds = [];
480 foreach (array_keys($returns) as $key) {
481 if (strpos($key, 'tag_id.') === 0) {
483 $returns['tag_id'] = 1;
485 if (strpos($key, 'case_id.') === 0) {
486 $caseGet[] = str_replace('case_id.', '', $key);
487 $returns['case_id'] = 1;
491 foreach ($returns as $n => $v) {
493 case 'assignee_contact_id':
494 case 'target_contact_id':
495 foreach ($activities as &$activity) {
496 if (!isset($activity[$n])) {
501 case 'source_contact_id':
505 $tags = civicrm_api3('EntityTag', 'get', [
506 'entity_table' => 'civicrm_activity',
507 'entity_id' => ['IN' => array_keys($activities)],
509 'options' => ['limit' => 0],
511 foreach ($tags['values'] as $tag) {
512 $key = (int) $tag['entity_id'];
513 unset($tag['entity_id'], $tag['id']);
514 $activities[$key]['tag_id'][$tag['tag_id']] = $tag;
519 $dao = CRM_Core_DAO
::executeQuery("SELECT entity_id, file_id FROM civicrm_entity_file WHERE entity_table = 'civicrm_activity' AND entity_id IN (%1)",
520 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
]]);
521 while ($dao->fetch()) {
522 $activities[$dao->entity_id
]['file_id'][] = $dao->file_id
;
527 $dao = CRM_Core_DAO
::executeQuery("SELECT activity_id, case_id FROM civicrm_case_activity WHERE activity_id IN (%1)",
528 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
]]);
529 while ($dao->fetch()) {
530 $activities[$dao->activity_id
]['case_id'][] = $dao->case_id
;
531 $caseIds[$dao->case_id
] = $dao->case_id
;
536 foreach ($activities as $key => $activityArray) {
537 $activities[$key]['is_overdue'] = (int) CRM_Activity_BAO_Activity
::isOverdue($activityArray);
542 if (substr($n, 0, 6) == 'custom') {
543 $returnProperties[$n] = $v;
548 // Fetch case fields via the join syntax
549 // Note this is limited to the first case if the activity belongs to more than one
550 if ($caseGet && $caseIds) {
551 $cases = civicrm_api3('Case', 'get', [
552 'id' => ['IN' => $caseIds],
553 'options' => ['limit' => 0],
554 'check_permissions' => !empty($params['check_permissions']),
555 'return' => $caseGet,
557 foreach ($activities as &$activity) {
558 if (!empty($activity['case_id'])) {
559 $case = $cases['values'][$activity['case_id'][0]] ??
NULL;
561 foreach ($case as $key => $value) {
563 $activity['case_id.' . $key] = $value;
572 if (!empty($params['contact_id'])) {
573 $statusOptions = CRM_Activity_BAO_Activity
::buildOptions('status_id', 'get');
574 $typeOptions = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
575 foreach ($activities as $key => &$activityArray) {
576 if (!empty($activityArray['status_id'])) {
577 $activityArray['status'] = $statusOptions[$activityArray['status_id']];
579 if (!empty($activityArray['activity_type_id'])) {
580 $activityArray['activity_name'] = $typeOptions[$activityArray['activity_type_id']];
585 if (!empty($returnProperties) ||
!empty($params['contact_id'])) {
586 foreach ($activities as $activityId => $values) {
587 //@todo - should possibly load activity type id if not loaded (update with id)
588 _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));
595 * Append activity contact details to activity results.
597 * Adds id & name of activity contacts to results array if check_permissions
598 * does not block access to them.
600 * For historical reasons source_contact_id is always added & is not an array.
601 * The others are added depending on requested return params.
603 * @param array $activities
604 * @param array $params
605 * @param array $returns
607 function _civicrm_api3_activity_fill_activity_contact_names(&$activities, $params, $returns) {
608 $contactTypes = array_flip(CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate'));
609 $assigneeType = $contactTypes['Activity Assignees'];
610 $targetType = $contactTypes['Activity Targets'];
611 $sourceType = $contactTypes['Activity Source'];
613 $assigneeType => 'assignee',
614 $sourceType => 'source',
615 $targetType => 'target',
618 $activityContactTypes = [$sourceType];
620 if (!empty($returns['target_contact_name']) ||
!empty($returns['target_contact_id'])) {
621 $activityContactTypes[] = $targetType;
623 if (!empty($returns['assignee_contact_name']) ||
(!empty($returns['assignee_contact_id']))) {
624 $activityContactTypes[] = $assigneeType;
626 $activityContactParams = [
627 'activity_id' => ['IN' => array_keys($activities)],
631 'contact_id.display_name',
632 'contact_id.sort_name',
635 'options' => ['limit' => 0],
636 'check_permissions' => !empty($params['check_permissions']),
638 if (count($activityContactTypes) < 3) {
639 $activityContactParams['record_type_id'] = ['IN' => $activityContactTypes];
641 $activityContacts = civicrm_api3('ActivityContact', 'get', $activityContactParams)['values'];
642 foreach ($activityContacts as $activityContact) {
643 $contactID = $activityContact['contact_id'];
644 $recordType = $typeMap[$activityContact['record_type_id']];
645 if (in_array($recordType, ['target', 'assignee'])) {
646 $activities[$activityContact['activity_id']][$recordType . '_contact_id'][] = $contactID;
647 $activities[$activityContact['activity_id']][$recordType . '_contact_name'][$contactID] = isset($activityContact['contact_id.display_name']) ?
$activityContact['contact_id.display_name'] : '';
648 $activities[$activityContact['activity_id']][$recordType . '_contact_sort_name'][$contactID] = isset($activityContact['contact_id.sort_name']) ?
$activityContact['contact_id.sort_name'] : '';
651 $activities[$activityContact['activity_id']]['source_contact_id'] = $contactID;
652 $activities[$activityContact['activity_id']]['source_contact_name'] = isset($activityContact['contact_id.display_name']) ?
$activityContact['contact_id.display_name'] : '';
653 $activities[$activityContact['activity_id']]['source_contact_sort_name'] = isset($activityContact['contact_id.sort_name']) ?
$activityContact['contact_id.sort_name'] : '';
659 * Delete a specified Activity.
661 * @param array $params
662 * Array holding 'id' of activity to be deleted.
664 * @throws API_Exception
669 function civicrm_api3_activity_delete($params) {
671 if (CRM_Activity_BAO_Activity
::deleteActivity($params)) {
672 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
675 throw new API_Exception('Could not delete Activity: ' . (int) $params['id']);
680 * Check for required params.
682 * @param array $params
683 * Associated array of fields.
685 * @throws API_Exception
690 function _civicrm_api3_activity_check_params(&$params) {
692 'activity' => $params['id'] ??
NULL,
693 'parent' => $params['parent_id'] ??
NULL,
694 'original' => $params['original_id'] ??
NULL,
697 foreach ($activityIds as $id => $value) {
699 !CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
701 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
704 // this should be handled by wrapper layer & probably the api would already manage it
705 //correctly by doing pseudoconstant validation
707 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
708 $activityName = $params['activity_name'] ??
NULL;
709 $activityName = ucfirst($activityName);
710 $activityLabel = $params['activity_label'] ??
NULL;
711 if ($activityLabel) {
712 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'create');
715 $activityTypeId = $params['activity_type_id'] ??
NULL;
717 if ($activityName ||
$activityLabel) {
718 $activityTypeIdInList = array_search(($activityName ?
$activityName : $activityLabel), $activityTypes);
720 if (!$activityTypeIdInList) {
721 $errorString = $activityName ?
"Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
722 throw new Exception($errorString);
724 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
725 throw new API_Exception('Mismatch in Activity');
727 $params['activity_type_id'] = $activityTypeIdInList;
729 elseif ($activityTypeId &&
730 !array_key_exists($activityTypeId, $activityTypes)
732 throw new API_Exception('Invalid Activity Type ID');
735 // check for activity duration minutes
736 // this should be validated @ the wrapper layer not here
738 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
739 throw new API_Exception('Invalid Activity Duration (in minutes)');
742 //if adding a new activity & date_time not set make it now
743 // this should be managed by the wrapper layer & setting ['api.default'] in speces
745 if (empty($params['id']) && empty($params['activity_date_time'])) {
746 $params['activity_date_time'] = CRM_Utils_Date
::processDate(date('Y-m-d H:i:s'));
753 * Get parameters for activity list.
755 * @see _civicrm_api3_generic_getlist_params
757 * @param array $request
760 function _civicrm_api3_activity_getlist_params(&$request) {
762 'activity_date_time',
767 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
768 $request['params']['options']['sort'] = 'activity_date_time DESC';
769 $request['params'] +
= [
770 'is_current_revision' => 1,
776 * Get output for activity list.
778 * @see _civicrm_api3_generic_getlist_output
780 * @param array $result
781 * @param array $request
785 function _civicrm_api3_activity_getlist_output($result, $request) {
787 if (!empty($result['values'])) {
788 foreach ($result['values'] as $row) {
790 'id' => $row[$request['id_field']],
791 'label' => $row[$request['label_field']] ?
$row[$request['label_field']] : ts('(no subject)'),
793 CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
796 if (!empty($row['activity_date_time'])) {
797 $data['description'][0] .= ': ' . CRM_Utils_Date
::customFormat($row['activity_date_time']);
799 if (!empty($row['source_contact_id'])) {
800 $data['description'][] = ts('By %1', [
801 1 => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
804 // Add repeating info
805 $repeat = CRM_Core_BAO_RecurringEntity
::getPositionAndCount($row['id'], 'civicrm_activity');
806 $data['extra']['is_recur'] = FALSE;
808 $data['suffix'] = ts('(%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]);
809 $data['extra']['is_recur'] = TRUE;