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