Merge pull request #18950 from MegaphoneJon/event-44
[civicrm-core.git] / api / v3 / Activity.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
a30c801b 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
a30c801b
TO
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 |
6a488035
TO
9 +--------------------------------------------------------------------+
10 */
11
12/**
244bbdd8 13 * This api exposes CiviCRM Activity records.
6a488035
TO
14 *
15 * @package CiviCRM_APIv3
6a488035
TO
16 */
17
6a488035 18/**
61fe4988 19 * Creates or updates an Activity.
6a488035 20 *
cf470720 21 * @param array $params
c28e1768 22 * Array per getfields documentation.
6a488035 23 *
77b97be7 24 * @throws API_Exception
a6c01b45 25 * @return array
00f8641b 26 * API result array
6a488035
TO
27 */
28function civicrm_api3_activity_create($params) {
c16b4619 29 $isNew = empty($params['id']);
6a488035 30
a7488080 31 if (empty($params['id'])) {
6a488035
TO
32 // an update does not require any mandatory parameters
33 civicrm_api3_verify_one_mandatory($params,
34 NULL,
cf8f0fff 35 [
7cdbcb16
TO
36 'activity_name',
37 'activity_type_id',
38 'activity_label',
cf8f0fff 39 ]
6a488035
TO
40 );
41 }
42
6a488035
TO
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
6a488035 54 // processing for custom data
cf8f0fff 55 $values = $activityArray = [];
6a488035
TO
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
7cdbcb16
TO
69 $case_id = '';
70 $createRevision = FALSE;
cf8f0fff 71 $oldActivityValues = [];
e96d5fa3
CW
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 }
a7488080 76 if (!empty($params['case_id'])) {
6a488035 77 $case_id = $params['case_id'];
c16b4619 78 if (!empty($params['id']) && Civi::settings()->get('civicaseActivityRevisions')) {
cf8f0fff 79 $oldActivityParams = ['id' => $params['id']];
6a488035
TO
80 if (!$oldActivityValues) {
81 CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
82 }
83 if (empty($oldActivityValues)) {
10114f2d 84 throw new API_Exception(ts("Unable to locate existing activity."));
6a488035
TO
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()) {
10114f2d 91 throw new API_Exception(ts("Unable to revision existing case activity."));
6a488035
TO
92 }
93 $createRevision = TRUE;
94 }
95 }
96 }
97
6a488035
TO
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 {
10114f2d 120 throw new API_Exception(ts("Unable to create new revision of case activity."));
6a488035
TO
121 }
122 }
123
124 // create activity
125 $activityBAO = CRM_Activity_BAO_Activity::create($params);
126
127 if (isset($activityBAO->id)) {
c16b4619 128 if ($case_id && $isNew && !$createRevision) {
18e0f096
CW
129 // If this is a brand new case activity, add to case(s)
130 foreach ((array) $case_id as $singleCaseId) {
cf8f0fff 131 $caseActivityParams = ['activity_id' => $activityBAO->id, 'case_id' => $singleCaseId];
18e0f096
CW
132 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
133 }
6a488035
TO
134 }
135
136 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
244bbdd8 137 return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
6a488035
TO
138 }
139}
11e09c59
TO
140
141/**
61fe4988
EM
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 *
cf470720 147 * @param array $params
c28e1768 148 * Array of parameters determined by getfields.
6a488035
TO
149 */
150function _civicrm_api3_activity_create_spec(&$params) {
151
cf8f0fff 152 $params['status_id']['api.aliases'] = ['activity_status'];
67744c4e 153
cf8f0fff 154 $params['assignee_contact_id'] = [
6a488035 155 'name' => 'assignee_id',
0a24dc9a
CW
156 'title' => 'Activity Assignee',
157 'description' => 'Contact(s) assigned to this activity.',
6a488035 158 'type' => 1,
7e61908b 159 'FKClassName' => 'CRM_Contact_DAO_Contact',
0a24dc9a 160 'FKApiName' => 'Contact',
cf8f0fff
CW
161 ];
162 $params['target_contact_id'] = [
6a488035
TO
163 'name' => 'target_id',
164 'title' => 'Activity Target',
0a24dc9a 165 'description' => 'Contact(s) participating in this activity.',
6a488035 166 'type' => 1,
7e61908b 167 'FKClassName' => 'CRM_Contact_DAO_Contact',
0a24dc9a 168 'FKApiName' => 'Contact',
cf8f0fff 169 ];
2f3d72cf 170
cf8f0fff 171 $params['source_contact_id'] = [
7cdbcb16
TO
172 'name' => 'source_contact_id',
173 'title' => 'Activity Source Contact',
0a24dc9a 174 'description' => 'Person who created this activity. Defaults to current user.',
7cdbcb16 175 'type' => 1,
7e61908b 176 'FKClassName' => 'CRM_Contact_DAO_Contact',
7cdbcb16 177 'api.default' => 'user_contact_id',
0a24dc9a 178 'FKApiName' => 'Contact',
c442f1b6 179 'api.required' => TRUE,
cf8f0fff 180 ];
0a24dc9a 181
cf8f0fff 182 $params['case_id'] = [
0a24dc9a
CW
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',
cf8f0fff 189 ];
2f3d72cf 190
a06c30f5 191 $params['activity_date_time']['api.default'] = 'now';
2c9e83fa 192
6a488035
TO
193}
194
1196e086
CW
195/**
196 * Specify Metadata for get.
197 *
198 * @param array $params
199 */
200function _civicrm_api3_activity_get_spec(&$params) {
cf8f0fff 201 $params['tag_id'] = [
1196e086
CW
202 'title' => 'Tags',
203 'description' => 'Find activities with specified tags.',
760ac501 204 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
205 'FKClassName' => 'CRM_Core_DAO_Tag',
206 'FKApiName' => 'Tag',
40875a91 207 'supports_joins' => TRUE,
cf8f0fff
CW
208 ];
209 $params['file_id'] = [
40875a91
CW
210 'title' => 'Attached Files',
211 'description' => 'Find activities with attached files.',
760ac501 212 'type' => CRM_Utils_Type::T_INT,
40875a91
CW
213 'FKClassName' => 'CRM_Core_DAO_File',
214 'FKApiName' => 'File',
cf8f0fff
CW
215 ];
216 $params['case_id'] = [
1196e086
CW
217 'title' => 'Cases',
218 'description' => 'Find activities within specified cases.',
760ac501 219 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
220 'FKClassName' => 'CRM_Case_DAO_Case',
221 'FKApiName' => 'Case',
2c9e4446 222 'supports_joins' => TRUE,
cf8f0fff
CW
223 ];
224 $params['contact_id'] = [
526e0834
CW
225 'title' => 'Activity Contact ID',
226 'description' => 'Find activities involving this contact (as target, source, OR assignee).',
760ac501 227 'type' => CRM_Utils_Type::T_INT,
526e0834
CW
228 'FKClassName' => 'CRM_Contact_DAO_Contact',
229 'FKApiName' => 'Contact',
cf8f0fff
CW
230 ];
231 $params['target_contact_id'] = [
1196e086
CW
232 'title' => 'Target Contact ID',
233 'description' => 'Find activities with specified target contact.',
760ac501 234 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
235 'FKClassName' => 'CRM_Contact_DAO_Contact',
236 'FKApiName' => 'Contact',
cf8f0fff
CW
237 ];
238 $params['source_contact_id'] = [
1196e086
CW
239 'title' => 'Source Contact ID',
240 'description' => 'Find activities with specified source contact.',
760ac501 241 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
242 'FKClassName' => 'CRM_Contact_DAO_Contact',
243 'FKApiName' => 'Contact',
cf8f0fff
CW
244 ];
245 $params['assignee_contact_id'] = [
1196e086
CW
246 'title' => 'Assignee Contact ID',
247 'description' => 'Find activities with specified assignee contact.',
760ac501 248 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
249 'FKClassName' => 'CRM_Contact_DAO_Contact',
250 'FKApiName' => 'Contact',
cf8f0fff
CW
251 ];
252 $params['is_overdue'] = [
760ac501
CW
253 'title' => 'Is Activity Overdue',
254 'description' => 'Incomplete activities with a past date.',
255 'type' => CRM_Utils_Type::T_BOOLEAN,
cf8f0fff 256 ];
1196e086
CW
257}
258
6a488035 259/**
61fe4988 260 * Gets a CiviCRM activity according to parameters.
6a488035 261 *
cf470720 262 * @param array $params
61fe4988 263 * Array per getfields documentation.
6a488035 264 *
7c31ae57 265 * @return array
00f8641b 266 * API result array
bbd2743b 267 *
268 * @throws \API_Exception
269 * @throws \CiviCRM_API3_Exception
270 * @throws \Civi\API\Exception\UnauthorizedException
6a488035
TO
271 */
272function civicrm_api3_activity_get($params) {
760ac501 273 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
526e0834 274 $sql = CRM_Utils_SQL_Select::fragment();
a6c2ebdc 275 _civicrm_activity_get_handleSourceContactNameOrderBy($params, $options, $sql);
d544ffcd 276
d544ffcd
CW
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);
84be264e 303 if ($options['is_count']) {
304 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
305 }
306
d544ffcd
CW
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
a6c2ebdc 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 */
327function _civicrm_activity_get_handleSourceContactNameOrderBy(&$params, &$options, $sql) {
328 $sourceContactID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
4a413eb6
AH
329 if (!empty($options['sort'])
330 && in_array($options['sort'], [
a6c2ebdc 331 'source_contact_name',
332 'source_contact_name desc',
4a413eb6 333 'source_contact_name asc',
a6c2ebdc 334 ])) {
335 $order = substr($options['sort'], -4) === 'desc' ? 'desc' : 'asc';
336 $sql->join(
337 'source_contact',
338 "LEFT JOIN
c2068a3e
TO
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]
a6c2ebdc 342 );
343 $sql->orderBy("c.display_name $order");
344 unset($options['sort'], $params['options']['sort']);
345 }
346}
347
d544ffcd
CW
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 */
356function _civicrm_api3_activity_get_extraFilters(&$params, &$sql) {
357 // Filter by activity contacts
cf8f0fff 358 $activityContactOptions = [
d544ffcd 359 'contact_id' => NULL,
550dcde8 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'),
cf8f0fff 363 ];
526e0834
CW
364 foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
365 if (!empty($params[$activityContactName])) {
526e0834 366 if (!is_array($params[$activityContactName])) {
cf8f0fff 367 $params[$activityContactName] = ['=' => $params[$activityContactName]];
526e0834
CW
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)",
cf8f0fff 372 ['#typeId' => $activityContactValue, '!clause' => $clause]
526e0834 373 );
6a488035
TO
374 }
375 }
749522a2 376
760ac501 377 // Handle is_overdue filter
d544ffcd 378 // Boolean calculated field - does not support operators
760ac501 379 if (isset($params['is_overdue'])) {
ce9d78e1 380 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
760ac501
CW
381 if ($params['is_overdue']) {
382 $sql->where('a.activity_date_time < NOW()');
ce9d78e1 383 $sql->where("a.status_id IN ($incomplete)");
760ac501
CW
384 }
385 else {
ce9d78e1 386 $sql->where("(a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete))");
760ac501
CW
387 }
388 }
389
749522a2
TO
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.
cf8f0fff
CW
394 $rels = [
395 'tag_id' => [
749522a2
TO
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',
cf8f0fff
CW
399 ],
400 'file_id' => [
749522a2
TO
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',
cf8f0fff
CW
404 ],
405 'case_id' => [
749522a2
TO
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',
cf8f0fff
CW
409 ],
410 ];
749522a2
TO
411 foreach ($rels as $filter => $relSpec) {
412 if (!empty($params[$filter])) {
413 if (!is_array($params[$filter])) {
cf8f0fff 414 $params[$filter] = ['=' => $params[$filter]];
749522a2
TO
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) {
cf8f0fff 421 $sql->where($relSpec['subquery'], ['!clause' => $clause]);
749522a2
TO
422 }
423 }
424 else {
425 $alias = 'actjoin_' . $filter;
426 $clause = \CRM_Core_DAO::createSQLFilter($alias . "." . $relSpec['column'], $params[$filter]);
427 if ($clause) {
cf8f0fff 428 $sql->join($alias, $relSpec['join'], ['!alias' => $alias, 'joinType' => $mode]);
749522a2
TO
429 $sql->where($clause);
430 }
431 }
0298287b 432 }
6a488035 433 }
ab5fa8f2
TO
434}
435
436/**
61fe4988 437 * Given a list of activities, append any extra data requested about the activities.
ab5fa8f2 438 *
b081365f 439 * @note Called by civicrm-core and CiviHR
ab5fa8f2 440 *
cf470720
TO
441 * @param array $params
442 * API request parameters.
ab5fa8f2 443 * @param array $activities
cdacd6ab 444 * @param array $options
445 * Options array (pre-processed to extract 'return' from params).
61fe4988 446 *
a6c01b45 447 * @return array
72b3a70c 448 * new activities list
ab5fa8f2 449 */
bc4b6f0f 450function _civicrm_api3_activity_get_formatResult($params, $activities, $options) {
30db5cbf
CW
451 if (!$activities) {
452 return $activities;
453 }
454
bc4b6f0f 455 $returns = $options['return'];
6a488035 456 foreach ($params as $n => $v) {
cdacd6ab 457 // @todo - the per-parsing on options should have already done this.
6a488035
TO
458 if (substr($n, 0, 7) == 'return.') {
459 $returnkey = substr($n, 7);
460 $returns[$returnkey] = $v;
461 }
462 }
0298287b 463
cdacd6ab 464 _civicrm_api3_activity_fill_activity_contact_names($activities, $params, $returns);
db6e8cb4 465
cf8f0fff
CW
466 $tagGet = ['tag_id', 'entity_id'];
467 $caseGet = $caseIds = [];
40875a91
CW
468 foreach (array_keys($returns) as $key) {
469 if (strpos($key, 'tag_id.') === 0) {
470 $tagGet[] = $key;
471 $returns['tag_id'] = 1;
472 }
2c9e4446
CW
473 if (strpos($key, 'case_id.') === 0) {
474 $caseGet[] = str_replace('case_id.', '', $key);
475 $returns['case_id'] = 1;
476 }
40875a91
CW
477 }
478
6a488035
TO
479 foreach ($returns as $n => $v) {
480 switch ($n) {
481 case 'assignee_contact_id':
6a488035 482 case 'target_contact_id':
cdacd6ab 483 foreach ($activities as &$activity) {
484 if (!isset($activity[$n])) {
485 $activity[$n] = [];
db6e8cb4 486 }
6a488035 487 }
35671d00 488
42d30b83 489 case 'source_contact_id':
42d30b83 490 break;
35671d00 491
30db5cbf 492 case 'tag_id':
cf8f0fff 493 $tags = civicrm_api3('EntityTag', 'get', [
30db5cbf 494 'entity_table' => 'civicrm_activity',
cf8f0fff 495 'entity_id' => ['IN' => array_keys($activities)],
40875a91 496 'return' => $tagGet,
cf8f0fff
CW
497 'options' => ['limit' => 0],
498 ]);
30db5cbf 499 foreach ($tags['values'] as $tag) {
40875a91
CW
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)",
cf8f0fff 508 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]]);
40875a91
CW
509 while ($dao->fetch()) {
510 $activities[$dao->entity_id]['file_id'][] = $dao->file_id;
30db5cbf
CW
511 }
512 break;
513
bc4b6f0f
CW
514 case 'case_id':
515 $dao = CRM_Core_DAO::executeQuery("SELECT activity_id, case_id FROM civicrm_case_activity WHERE activity_id IN (%1)",
cf8f0fff 516 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]]);
bc4b6f0f 517 while ($dao->fetch()) {
18e0f096 518 $activities[$dao->activity_id]['case_id'][] = $dao->case_id;
2c9e4446 519 $caseIds[$dao->case_id] = $dao->case_id;
bc4b6f0f
CW
520 }
521 break;
522
760ac501
CW
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
6a488035
TO
529 default:
530 if (substr($n, 0, 6) == 'custom') {
531 $returnProperties[$n] = $v;
532 }
2c9e4446
CW
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) {
cf8f0fff
CW
539 $cases = civicrm_api3('Case', 'get', [
540 'id' => ['IN' => $caseIds],
541 'options' => ['limit' => 0],
2c9e4446
CW
542 'check_permissions' => !empty($params['check_permissions']),
543 'return' => $caseGet,
cf8f0fff 544 ]);
2c9e4446
CW
545 foreach ($activities as &$activity) {
546 if (!empty($activity['case_id'])) {
f748c073 547 $case = $cases['values'][$activity['case_id'][0]] ?? NULL;
2c9e4446
CW
548 if ($case) {
549 foreach ($case as $key => $value) {
550 if ($key != 'id') {
551 $activity['case_id.' . $key] = $value;
552 }
553 }
554 }
555 }
6a488035
TO
556 }
557 }
526e0834 558
40875a91 559 // Legacy extras
526e0834
CW
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
30db5cbf 573 if (!empty($returnProperties) || !empty($params['contact_id'])) {
6a488035 574 foreach ($activities as $activityId => $values) {
10114f2d 575 //@todo - should possibly load activity type id if not loaded (update with id)
e9ff5391 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));
6a488035
TO
577 }
578 }
ab5fa8f2 579 return $activities;
6a488035 580}
cdacd6ab 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 */
595function _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',
7c31ae57 603 $targetType => 'target',
cdacd6ab 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',
c2ce41b6 620 'contact_id.sort_name',
7c31ae57 621 'contact_id',
cdacd6ab 622 ],
c2ce41b6 623 'options' => ['limit' => 0],
cdacd6ab 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;
2e1f50d6
CW
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'] ?? '';
cdacd6ab 637 }
638 else {
639 $activities[$activityContact['activity_id']]['source_contact_id'] = $contactID;
2e1f50d6
CW
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'] ?? '';
cdacd6ab 642 }
643 }
644}
6a488035
TO
645
646/**
647 * Delete a specified Activity.
648 *
cf470720
TO
649 * @param array $params
650 * Array holding 'id' of activity to be deleted.
6a488035 651 *
10114f2d 652 * @throws API_Exception
6a488035 653 *
61fe4988 654 * @return array
00f8641b 655 * API result array
6a488035
TO
656 */
657function civicrm_api3_activity_delete($params) {
658
659 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
244bbdd8 660 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
6a488035
TO
661 }
662 else {
df1dded9 663 throw new API_Exception('Could not delete Activity: ' . (int) $params['id']);
6a488035
TO
664 }
665}
666
667/**
61fe4988 668 * Check for required params.
6a488035 669 *
cf470720
TO
670 * @param array $params
671 * Associated array of fields.
10114f2d
EM
672 *
673 * @throws API_Exception
674 * @throws Exception
a6c01b45 675 * @return array
72b3a70c 676 * array with errors
6a488035
TO
677 */
678function _civicrm_api3_activity_check_params(&$params) {
cf8f0fff 679 $activityIds = [
6b409353
CW
680 'activity' => $params['id'] ?? NULL,
681 'parent' => $params['parent_id'] ?? NULL,
682 'original' => $params['original_id'] ?? NULL,
cf8f0fff 683 ];
6a488035
TO
684
685 foreach ($activityIds as $id => $value) {
686 if ($value &&
687 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
688 ) {
10114f2d 689 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
6a488035
TO
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
a60ed840 695 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
f748c073 696 $activityName = $params['activity_name'] ?? NULL;
7cdbcb16 697 $activityName = ucfirst($activityName);
f748c073 698 $activityLabel = $params['activity_label'] ?? NULL;
6a488035 699 if ($activityLabel) {
a60ed840 700 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
6a488035
TO
701 }
702
f748c073 703 $activityTypeId = $params['activity_type_id'] ?? NULL;
6a488035
TO
704
705 if ($activityName || $activityLabel) {
706 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
707
708 if (!$activityTypeIdInList) {
35671d00 709 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
6a488035
TO
710 throw new Exception($errorString);
711 }
712 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
10114f2d 713 throw new API_Exception('Mismatch in Activity');
6a488035
TO
714 }
715 $params['activity_type_id'] = $activityTypeIdInList;
716 }
717 elseif ($activityTypeId &&
718 !array_key_exists($activityTypeId, $activityTypes)
719 ) {
10114f2d 720 throw new API_Exception('Invalid Activity Type ID');
6a488035
TO
721 }
722
6a488035
TO
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'])) {
10114f2d 727 throw new API_Exception('Invalid Activity Duration (in minutes)');
6a488035
TO
728 }
729
6a488035
TO
730 return NULL;
731}
732
dabf9814 733/**
61fe4988
EM
734 * Get parameters for activity list.
735 *
7cdbcb16 736 * @see _civicrm_api3_generic_getlist_params
dabf9814 737 *
7cdbcb16
TO
738 * @param array $request
739 * API request.
dabf9814
CW
740 */
741function _civicrm_api3_activity_getlist_params(&$request) {
cf8f0fff 742 $fieldsToReturn = [
7cdbcb16
TO
743 'activity_date_time',
744 'activity_type_id',
745 'subject',
746 'source_contact_id',
cf8f0fff 747 ];
dabf9814
CW
748 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
749 $request['params']['options']['sort'] = 'activity_date_time DESC';
cf8f0fff 750 $request['params'] += [
dabf9814
CW
751 'is_current_revision' => 1,
752 'is_deleted' => 0,
cf8f0fff 753 ];
dabf9814
CW
754}
755
756/**
61fe4988
EM
757 * Get output for activity list.
758 *
dabf9814
CW
759 * @see _civicrm_api3_generic_getlist_output
760 *
8c6b335b
CW
761 * @param array $result
762 * @param array $request
dabf9814
CW
763 *
764 * @return array
765 */
766function _civicrm_api3_activity_getlist_output($result, $request) {
cf8f0fff 767 $output = [];
dabf9814
CW
768 if (!empty($result['values'])) {
769 foreach ($result['values'] as $row) {
cf8f0fff 770 $data = [
dabf9814
CW
771 'id' => $row[$request['id_field']],
772 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
cf8f0fff 773 'description' => [
4a413eb6 774 CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
cf8f0fff
CW
775 ],
776 ];
dabf9814
CW
777 if (!empty($row['activity_date_time'])) {
778 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
779 }
780 if (!empty($row['source_contact_id'])) {
cf8f0fff 781 $data['description'][] = ts('By %1', [
7cdbcb16 782 1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
cf8f0fff 783 ]);
dabf9814 784 }
8a938c69
CW
785 // Add repeating info
786 $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_activity');
787 $data['extra']['is_recur'] = FALSE;
788 if ($repeat) {
cf8f0fff 789 $data['suffix'] = ts('(%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]);
8a938c69
CW
790 $data['extra']['is_recur'] = TRUE;
791 }
dabf9814
CW
792 $output[] = $data;
793 }
794 }
795 return $output;
796}