Merge pull request #15727 from civicrm/5.19
[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 _civicrm_activity_get_handleSourceContactNameOrderBy($params, $options, $sql);
304
305 _civicrm_api3_activity_get_extraFilters($params, $sql);
306
307 // Handle is_overdue sort
308 if (!empty($options['sort'])) {
309 $sort = explode(', ', $options['sort']);
310
311 foreach ($sort as $index => &$sortString) {
312 // Get sort field and direction
313 list($sortField, $dir) = array_pad(explode(' ', $sortString), 2, 'ASC');
314 if ($sortField == 'is_overdue') {
315 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
316 $sql->orderBy("IF((a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete)), 0, 1) $dir", NULL, $index);
317 // Replace the sort with a placeholder which will be ignored by sql
318 $sortString = '(1)';
319 }
320 }
321 $params['options']['sort'] = implode(', ', $sort);
322 }
323
324 // Ensure there's enough data for calculating is_overdue
325 if (!empty($options['return']['is_overdue']) && (empty($options['return']['status_id']) || empty($options['return']['activity_date_time']))) {
326 $options['return']['status_id'] = $options['return']['activity_date_time'] = 1;
327 $params['return'] = array_keys($options['return']);
328 }
329
330 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $sql);
331 if ($options['is_count']) {
332 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
333 }
334
335 $activities = _civicrm_api3_activity_get_formatResult($params, $activities, $options);
336 //legacy custom data get - so previous formatted response is still returned too
337 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
338 }
339
340 /**
341 * Handle source_contact_name as a sort parameter.
342 *
343 * This is passed from the activity selector - e.g search results or contact tab.
344 *
345 * It's a non-standard handling but this api already handles variations on handling source_contact
346 * as a filter & as a field so it's in keeping with that. Source contact has a one-one relationship
347 * with activity table.
348 *
349 * Test coverage in CRM_Activity_BAO_ActivtiyTest::testGetActivitiesforContactSummaryWithSortOptions
350 *
351 * @param array $params
352 * @param array $options
353 * @param CRM_Utils_SQL_Select $sql
354 */
355 function _civicrm_activity_get_handleSourceContactNameOrderBy(&$params, &$options, $sql) {
356 $sourceContactID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
357 if (!empty($options['sort'])
358 && in_array($options['sort'], [
359 'source_contact_name',
360 'source_contact_name desc',
361 'source_contact_name asc',
362 ])) {
363 $order = substr($options['sort'], -4) === 'desc' ? 'desc' : 'asc';
364 $sql->join(
365 'source_contact',
366 "LEFT JOIN
367 civicrm_activity_contact ac ON (ac.activity_id = a.id AND record_type_id = #sourceContactID)
368 LEFT JOIN civicrm_contact c ON c.id = ac.contact_id",
369 ['sourceContactID' => $sourceContactID]
370 );
371 $sql->orderBy("c.display_name $order");
372 unset($options['sort'], $params['options']['sort']);
373 }
374 }
375
376 /**
377 * Support filters beyond what basic_get can do.
378 *
379 * @param array $params
380 * @param CRM_Utils_SQL_Select $sql
381 * @throws \CiviCRM_API3_Exception
382 * @throws \Exception
383 */
384 function _civicrm_api3_activity_get_extraFilters(&$params, &$sql) {
385 // Filter by activity contacts
386 $activityContactOptions = [
387 'contact_id' => NULL,
388 'target_contact_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets'),
389 'source_contact_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'),
390 'assignee_contact_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Assignees'),
391 ];
392 foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
393 if (!empty($params[$activityContactName])) {
394 if (!is_array($params[$activityContactName])) {
395 $params[$activityContactName] = ['=' => $params[$activityContactName]];
396 }
397 $clause = \CRM_Core_DAO::createSQLFilter('contact_id', $params[$activityContactName]);
398 $typeClause = $activityContactValue ? 'record_type_id = #typeId AND ' : '';
399 $sql->where("a.id IN (SELECT activity_id FROM civicrm_activity_contact WHERE $typeClause !clause)",
400 ['#typeId' => $activityContactValue, '!clause' => $clause]
401 );
402 }
403 }
404
405 // Handle is_overdue filter
406 // Boolean calculated field - does not support operators
407 if (isset($params['is_overdue'])) {
408 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
409 if ($params['is_overdue']) {
410 $sql->where('a.activity_date_time < NOW()');
411 $sql->where("a.status_id IN ($incomplete)");
412 }
413 else {
414 $sql->where("(a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete))");
415 }
416 }
417
418 // Define how to handle filters on some related entities.
419 // Subqueries are nice in (a) avoiding duplicates and (b) when the result
420 // list is expected to be bite-sized. Joins are nice (a) with larger
421 // datasets and (b) checking for non-existent relations.
422 $rels = [
423 'tag_id' => [
424 'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_activity" AND !clause)',
425 'join' => '!joinType civicrm_entity_tag !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
426 'column' => 'tag_id',
427 ],
428 'file_id' => [
429 'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_file WHERE entity_table = "civicrm_activity" AND !clause)',
430 'join' => '!joinType civicrm_entity_file !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
431 'column' => 'file_id',
432 ],
433 'case_id' => [
434 'subquery' => 'a.id IN (SELECT activity_id FROM civicrm_case_activity WHERE !clause)',
435 'join' => '!joinType civicrm_case_activity !alias ON (!alias.activity_id = a.id)',
436 'column' => 'case_id',
437 ],
438 ];
439 foreach ($rels as $filter => $relSpec) {
440 if (!empty($params[$filter])) {
441 if (!is_array($params[$filter])) {
442 $params[$filter] = ['=' => $params[$filter]];
443 }
444 // $mode is one of ('LEFT JOIN', 'INNER JOIN', 'SUBQUERY')
445 $mode = isset($params[$filter]['IS NULL']) ? 'LEFT JOIN' : 'SUBQUERY';
446 if ($mode === 'SUBQUERY') {
447 $clause = \CRM_Core_DAO::createSQLFilter($relSpec['column'], $params[$filter]);
448 if ($clause) {
449 $sql->where($relSpec['subquery'], ['!clause' => $clause]);
450 }
451 }
452 else {
453 $alias = 'actjoin_' . $filter;
454 $clause = \CRM_Core_DAO::createSQLFilter($alias . "." . $relSpec['column'], $params[$filter]);
455 if ($clause) {
456 $sql->join($alias, $relSpec['join'], ['!alias' => $alias, 'joinType' => $mode]);
457 $sql->where($clause);
458 }
459 }
460 }
461 }
462 }
463
464 /**
465 * Given a list of activities, append any extra data requested about the activities.
466 *
467 * @note Called by civicrm-core and CiviHR
468 *
469 * @param array $params
470 * API request parameters.
471 * @param array $activities
472 * @param array $options
473 * Options array (pre-processed to extract 'return' from params).
474 *
475 * @return array
476 * new activities list
477 */
478 function _civicrm_api3_activity_get_formatResult($params, $activities, $options) {
479 if (!$activities) {
480 return $activities;
481 }
482
483 $returns = $options['return'];
484 foreach ($params as $n => $v) {
485 // @todo - the per-parsing on options should have already done this.
486 if (substr($n, 0, 7) == 'return.') {
487 $returnkey = substr($n, 7);
488 $returns[$returnkey] = $v;
489 }
490 }
491
492 _civicrm_api3_activity_fill_activity_contact_names($activities, $params, $returns);
493
494 $tagGet = ['tag_id', 'entity_id'];
495 $caseGet = $caseIds = [];
496 foreach (array_keys($returns) as $key) {
497 if (strpos($key, 'tag_id.') === 0) {
498 $tagGet[] = $key;
499 $returns['tag_id'] = 1;
500 }
501 if (strpos($key, 'case_id.') === 0) {
502 $caseGet[] = str_replace('case_id.', '', $key);
503 $returns['case_id'] = 1;
504 }
505 }
506
507 foreach ($returns as $n => $v) {
508 switch ($n) {
509 case 'assignee_contact_id':
510 case 'target_contact_id':
511 foreach ($activities as &$activity) {
512 if (!isset($activity[$n])) {
513 $activity[$n] = [];
514 }
515 }
516
517 case 'source_contact_id':
518 break;
519
520 case 'tag_id':
521 $tags = civicrm_api3('EntityTag', 'get', [
522 'entity_table' => 'civicrm_activity',
523 'entity_id' => ['IN' => array_keys($activities)],
524 'return' => $tagGet,
525 'options' => ['limit' => 0],
526 ]);
527 foreach ($tags['values'] as $tag) {
528 $key = (int) $tag['entity_id'];
529 unset($tag['entity_id'], $tag['id']);
530 $activities[$key]['tag_id'][$tag['tag_id']] = $tag;
531 }
532 break;
533
534 case 'file_id':
535 $dao = CRM_Core_DAO::executeQuery("SELECT entity_id, file_id FROM civicrm_entity_file WHERE entity_table = 'civicrm_activity' AND entity_id IN (%1)",
536 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]]);
537 while ($dao->fetch()) {
538 $activities[$dao->entity_id]['file_id'][] = $dao->file_id;
539 }
540 break;
541
542 case 'case_id':
543 $dao = CRM_Core_DAO::executeQuery("SELECT activity_id, case_id FROM civicrm_case_activity WHERE activity_id IN (%1)",
544 [1 => [implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]]);
545 while ($dao->fetch()) {
546 $activities[$dao->activity_id]['case_id'][] = $dao->case_id;
547 $caseIds[$dao->case_id] = $dao->case_id;
548 }
549 break;
550
551 case 'is_overdue':
552 foreach ($activities as $key => $activityArray) {
553 $activities[$key]['is_overdue'] = (int) CRM_Activity_BAO_Activity::isOverdue($activityArray);
554 }
555 break;
556
557 default:
558 if (substr($n, 0, 6) == 'custom') {
559 $returnProperties[$n] = $v;
560 }
561 }
562 }
563
564 // Fetch case fields via the join syntax
565 // Note this is limited to the first case if the activity belongs to more than one
566 if ($caseGet && $caseIds) {
567 $cases = civicrm_api3('Case', 'get', [
568 'id' => ['IN' => $caseIds],
569 'options' => ['limit' => 0],
570 'check_permissions' => !empty($params['check_permissions']),
571 'return' => $caseGet,
572 ]);
573 foreach ($activities as &$activity) {
574 if (!empty($activity['case_id'])) {
575 $case = CRM_Utils_Array::value($activity['case_id'][0], $cases['values']);
576 if ($case) {
577 foreach ($case as $key => $value) {
578 if ($key != 'id') {
579 $activity['case_id.' . $key] = $value;
580 }
581 }
582 }
583 }
584 }
585 }
586
587 // Legacy extras
588 if (!empty($params['contact_id'])) {
589 $statusOptions = CRM_Activity_BAO_Activity::buildOptions('status_id', 'get');
590 $typeOptions = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
591 foreach ($activities as $key => &$activityArray) {
592 if (!empty($activityArray['status_id'])) {
593 $activityArray['status'] = $statusOptions[$activityArray['status_id']];
594 }
595 if (!empty($activityArray['activity_type_id'])) {
596 $activityArray['activity_name'] = $typeOptions[$activityArray['activity_type_id']];
597 }
598 }
599 }
600
601 if (!empty($returnProperties) || !empty($params['contact_id'])) {
602 foreach ($activities as $activityId => $values) {
603 //@todo - should possibly load activity type id if not loaded (update with id)
604 _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));
605 }
606 }
607 return $activities;
608 }
609
610 /**
611 * Append activity contact details to activity results.
612 *
613 * Adds id & name of activity contacts to results array if check_permissions
614 * does not block access to them.
615 *
616 * For historical reasons source_contact_id is always added & is not an array.
617 * The others are added depending on requested return params.
618 *
619 * @param array $activities
620 * @param array $params
621 * @param array $returns
622 */
623 function _civicrm_api3_activity_fill_activity_contact_names(&$activities, $params, $returns) {
624 $contactTypes = array_flip(CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate'));
625 $assigneeType = $contactTypes['Activity Assignees'];
626 $targetType = $contactTypes['Activity Targets'];
627 $sourceType = $contactTypes['Activity Source'];
628 $typeMap = [
629 $assigneeType => 'assignee',
630 $sourceType => 'source',
631 $targetType => 'target',
632 ];
633
634 $activityContactTypes = [$sourceType];
635
636 if (!empty($returns['target_contact_name']) || !empty($returns['target_contact_id'])) {
637 $activityContactTypes[] = $targetType;
638 }
639 if (!empty($returns['assignee_contact_name']) || (!empty($returns['assignee_contact_id']))) {
640 $activityContactTypes[] = $assigneeType;
641 }
642 $activityContactParams = [
643 'activity_id' => ['IN' => array_keys($activities)],
644 'return' => [
645 'activity_id',
646 'record_type_id',
647 'contact_id.display_name',
648 'contact_id.sort_name',
649 'contact_id',
650 ],
651 'options' => ['limit' => 0],
652 'check_permissions' => !empty($params['check_permissions']),
653 ];
654 if (count($activityContactTypes) < 3) {
655 $activityContactParams['record_type_id'] = ['IN' => $activityContactTypes];
656 }
657 $activityContacts = civicrm_api3('ActivityContact', 'get', $activityContactParams)['values'];
658 foreach ($activityContacts as $activityContact) {
659 $contactID = $activityContact['contact_id'];
660 $recordType = $typeMap[$activityContact['record_type_id']];
661 if (in_array($recordType, ['target', 'assignee'])) {
662 $activities[$activityContact['activity_id']][$recordType . '_contact_id'][] = $contactID;
663 $activities[$activityContact['activity_id']][$recordType . '_contact_name'][$contactID] = isset($activityContact['contact_id.display_name']) ? $activityContact['contact_id.display_name'] : '';
664 $activities[$activityContact['activity_id']][$recordType . '_contact_sort_name'][$contactID] = isset($activityContact['contact_id.sort_name']) ? $activityContact['contact_id.sort_name'] : '';
665 }
666 else {
667 $activities[$activityContact['activity_id']]['source_contact_id'] = $contactID;
668 $activities[$activityContact['activity_id']]['source_contact_name'] = isset($activityContact['contact_id.display_name']) ? $activityContact['contact_id.display_name'] : '';
669 $activities[$activityContact['activity_id']]['source_contact_sort_name'] = isset($activityContact['contact_id.sort_name']) ? $activityContact['contact_id.sort_name'] : '';
670 }
671 }
672 }
673
674 /**
675 * Delete a specified Activity.
676 *
677 * @param array $params
678 * Array holding 'id' of activity to be deleted.
679 *
680 * @throws API_Exception
681 *
682 * @return array
683 * API result array
684 */
685 function civicrm_api3_activity_delete($params) {
686
687 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
688 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
689 }
690 else {
691 throw new API_Exception('Could not delete Activity: ' . (int) $params['id']);
692 }
693 }
694
695 /**
696 * Check for required params.
697 *
698 * @param array $params
699 * Associated array of fields.
700 *
701 * @throws API_Exception
702 * @throws Exception
703 * @return array
704 * array with errors
705 */
706 function _civicrm_api3_activity_check_params(&$params) {
707 $activityIds = [
708 'activity' => CRM_Utils_Array::value('id', $params),
709 'parent' => CRM_Utils_Array::value('parent_id', $params),
710 'original' => CRM_Utils_Array::value('original_id', $params),
711 ];
712
713 foreach ($activityIds as $id => $value) {
714 if ($value &&
715 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
716 ) {
717 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
718 }
719 }
720 // this should be handled by wrapper layer & probably the api would already manage it
721 //correctly by doing pseudoconstant validation
722 // needs testing
723 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
724 $activityName = CRM_Utils_Array::value('activity_name', $params);
725 $activityName = ucfirst($activityName);
726 $activityLabel = CRM_Utils_Array::value('activity_label', $params);
727 if ($activityLabel) {
728 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
729 }
730
731 $activityTypeId = CRM_Utils_Array::value('activity_type_id', $params);
732
733 if ($activityName || $activityLabel) {
734 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
735
736 if (!$activityTypeIdInList) {
737 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
738 throw new Exception($errorString);
739 }
740 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
741 throw new API_Exception('Mismatch in Activity');
742 }
743 $params['activity_type_id'] = $activityTypeIdInList;
744 }
745 elseif ($activityTypeId &&
746 !array_key_exists($activityTypeId, $activityTypes)
747 ) {
748 throw new API_Exception('Invalid Activity Type ID');
749 }
750
751 // check for activity duration minutes
752 // this should be validated @ the wrapper layer not here
753 // needs testing
754 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
755 throw new API_Exception('Invalid Activity Duration (in minutes)');
756 }
757
758 //if adding a new activity & date_time not set make it now
759 // this should be managed by the wrapper layer & setting ['api.default'] in speces
760 // needs testing
761 if (empty($params['id']) && empty($params['activity_date_time'])) {
762 $params['activity_date_time'] = CRM_Utils_Date::processDate(date('Y-m-d H:i:s'));
763 }
764
765 return NULL;
766 }
767
768 /**
769 * Get parameters for activity list.
770 *
771 * @see _civicrm_api3_generic_getlist_params
772 *
773 * @param array $request
774 * API request.
775 */
776 function _civicrm_api3_activity_getlist_params(&$request) {
777 $fieldsToReturn = [
778 'activity_date_time',
779 'activity_type_id',
780 'subject',
781 'source_contact_id',
782 ];
783 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
784 $request['params']['options']['sort'] = 'activity_date_time DESC';
785 $request['params'] += [
786 'is_current_revision' => 1,
787 'is_deleted' => 0,
788 ];
789 }
790
791 /**
792 * Get output for activity list.
793 *
794 * @see _civicrm_api3_generic_getlist_output
795 *
796 * @param array $result
797 * @param array $request
798 *
799 * @return array
800 */
801 function _civicrm_api3_activity_getlist_output($result, $request) {
802 $output = [];
803 if (!empty($result['values'])) {
804 foreach ($result['values'] as $row) {
805 $data = [
806 'id' => $row[$request['id_field']],
807 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
808 'description' => [
809 CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
810 ],
811 ];
812 if (!empty($row['activity_date_time'])) {
813 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
814 }
815 if (!empty($row['source_contact_id'])) {
816 $data['description'][] = ts('By %1', [
817 1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
818 ]);
819 }
820 // Add repeating info
821 $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_activity');
822 $data['extra']['is_recur'] = FALSE;
823 if ($repeat) {
824 $data['suffix'] = ts('(%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]);
825 $data['extra']['is_recur'] = TRUE;
826 }
827 $output[] = $data;
828 }
829 }
830 return $output;
831 }