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