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