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