CRM-21052 - Activity.create API - Abide by setting `civicaseActivityRevisions`
[civicrm-core.git] / api / v3 / Activity.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
81621fee 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
1f4ea726 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
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/**
244bbdd8 29 * This api exposes CiviCRM Activity records.
6a488035
TO
30 *
31 * @package CiviCRM_APIv3
6a488035
TO
32 */
33
34
35/**
61fe4988 36 * Creates or updates an Activity.
6a488035 37 *
cf470720 38 * @param array $params
c28e1768 39 * Array per getfields documentation.
6a488035 40 *
77b97be7 41 * @throws API_Exception
a6c01b45 42 * @return array
00f8641b 43 * API result array
6a488035
TO
44 */
45function civicrm_api3_activity_create($params) {
c16b4619 46 $isNew = empty($params['id']);
6a488035 47
a7488080 48 if (empty($params['id'])) {
6a488035
TO
49 // an update does not require any mandatory parameters
50 civicrm_api3_verify_one_mandatory($params,
51 NULL,
52 array(
7cdbcb16
TO
53 'activity_name',
54 'activity_type_id',
55 'activity_label',
6a488035
TO
56 )
57 );
58 }
59
6a488035
TO
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
6a488035 71 // processing for custom data
10114f2d 72 $values = $activityArray = array();
6a488035
TO
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
7cdbcb16
TO
86 $case_id = '';
87 $createRevision = FALSE;
6a488035 88 $oldActivityValues = array();
e96d5fa3
CW
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 }
a7488080 93 if (!empty($params['case_id'])) {
6a488035 94 $case_id = $params['case_id'];
c16b4619 95 if (!empty($params['id']) && Civi::settings()->get('civicaseActivityRevisions')) {
6a488035
TO
96 $oldActivityParams = array('id' => $params['id']);
97 if (!$oldActivityValues) {
98 CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
99 }
100 if (empty($oldActivityValues)) {
10114f2d 101 throw new API_Exception(ts("Unable to locate existing activity."));
6a488035
TO
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()) {
08007144
TO
108 if (is_object($activityDAO)) {
109 $activityDAO->free();
110 }
10114f2d 111 throw new API_Exception(ts("Unable to revision existing case activity."));
6a488035
TO
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 {
10114f2d 154 throw new API_Exception(ts("Unable to create new revision of case activity."));
6a488035
TO
155 }
156 }
157
158 // create activity
159 $activityBAO = CRM_Activity_BAO_Activity::create($params);
160
161 if (isset($activityBAO->id)) {
c16b4619 162 if ($case_id && $isNew && !$createRevision) {
18e0f096
CW
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 }
6a488035
TO
168 }
169
170 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
244bbdd8 171 return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
6a488035
TO
172 }
173}
11e09c59
TO
174
175/**
61fe4988
EM
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 *
cf470720 181 * @param array $params
c28e1768 182 * Array of parameters determined by getfields.
6a488035
TO
183 */
184function _civicrm_api3_activity_create_spec(&$params) {
185
67744c4e
CW
186 $params['status_id']['api.aliases'] = array('activity_status');
187
6a488035
TO
188 $params['assignee_contact_id'] = array(
189 'name' => 'assignee_id',
0a24dc9a
CW
190 'title' => 'Activity Assignee',
191 'description' => 'Contact(s) assigned to this activity.',
6a488035 192 'type' => 1,
7e61908b 193 'FKClassName' => 'CRM_Contact_DAO_Contact',
0a24dc9a 194 'FKApiName' => 'Contact',
6a488035
TO
195 );
196 $params['target_contact_id'] = array(
197 'name' => 'target_id',
198 'title' => 'Activity Target',
0a24dc9a 199 'description' => 'Contact(s) participating in this activity.',
6a488035 200 'type' => 1,
7e61908b 201 'FKClassName' => 'CRM_Contact_DAO_Contact',
0a24dc9a 202 'FKApiName' => 'Contact',
6a488035 203 );
2f3d72cf 204
205 $params['source_contact_id'] = array(
7cdbcb16
TO
206 'name' => 'source_contact_id',
207 'title' => 'Activity Source Contact',
0a24dc9a 208 'description' => 'Person who created this activity. Defaults to current user.',
7cdbcb16 209 'type' => 1,
7e61908b 210 'FKClassName' => 'CRM_Contact_DAO_Contact',
7cdbcb16 211 'api.default' => 'user_contact_id',
0a24dc9a 212 'FKApiName' => 'Contact',
c442f1b6 213 'api.required' => TRUE,
0a24dc9a
CW
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',
2f3d72cf 223 );
224
6a488035
TO
225}
226
1196e086
CW
227/**
228 * Specify Metadata for get.
229 *
230 * @param array $params
231 */
232function _civicrm_api3_activity_get_spec(&$params) {
233 $params['tag_id'] = array(
1196e086
CW
234 'title' => 'Tags',
235 'description' => 'Find activities with specified tags.',
760ac501 236 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
237 'FKClassName' => 'CRM_Core_DAO_Tag',
238 'FKApiName' => 'Tag',
40875a91
CW
239 'supports_joins' => TRUE,
240 );
241 $params['file_id'] = array(
242 'title' => 'Attached Files',
243 'description' => 'Find activities with attached files.',
760ac501 244 'type' => CRM_Utils_Type::T_INT,
40875a91
CW
245 'FKClassName' => 'CRM_Core_DAO_File',
246 'FKApiName' => 'File',
1196e086
CW
247 );
248 $params['case_id'] = array(
1196e086
CW
249 'title' => 'Cases',
250 'description' => 'Find activities within specified cases.',
760ac501 251 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
252 'FKClassName' => 'CRM_Case_DAO_Case',
253 'FKApiName' => 'Case',
254 );
526e0834
CW
255 $params['contact_id'] = array(
256 'title' => 'Activity Contact ID',
257 'description' => 'Find activities involving this contact (as target, source, OR assignee).',
760ac501 258 'type' => CRM_Utils_Type::T_INT,
526e0834
CW
259 'FKClassName' => 'CRM_Contact_DAO_Contact',
260 'FKApiName' => 'Contact',
261 );
1196e086 262 $params['target_contact_id'] = array(
1196e086
CW
263 'title' => 'Target Contact ID',
264 'description' => 'Find activities with specified target contact.',
760ac501 265 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
266 'FKClassName' => 'CRM_Contact_DAO_Contact',
267 'FKApiName' => 'Contact',
268 );
269 $params['source_contact_id'] = array(
1196e086
CW
270 'title' => 'Source Contact ID',
271 'description' => 'Find activities with specified source contact.',
760ac501 272 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
273 'FKClassName' => 'CRM_Contact_DAO_Contact',
274 'FKApiName' => 'Contact',
275 );
276 $params['assignee_contact_id'] = array(
1196e086
CW
277 'title' => 'Assignee Contact ID',
278 'description' => 'Find activities with specified assignee contact.',
760ac501 279 'type' => CRM_Utils_Type::T_INT,
1196e086
CW
280 'FKClassName' => 'CRM_Contact_DAO_Contact',
281 'FKApiName' => 'Contact',
282 );
760ac501
CW
283 $params['is_overdue'] = array(
284 'title' => 'Is Activity Overdue',
285 'description' => 'Incomplete activities with a past date.',
286 'type' => CRM_Utils_Type::T_BOOLEAN,
287 );
1196e086
CW
288}
289
6a488035 290/**
61fe4988 291 * Gets a CiviCRM activity according to parameters.
6a488035 292 *
cf470720 293 * @param array $params
61fe4988 294 * Array per getfields documentation.
6a488035 295 *
bbd2743b 296 * @return array API result array
00f8641b 297 * API result array
bbd2743b 298 *
299 * @throws \API_Exception
300 * @throws \CiviCRM_API3_Exception
301 * @throws \Civi\API\Exception\UnauthorizedException
6a488035
TO
302 */
303function civicrm_api3_activity_get($params) {
760ac501 304 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
526e0834 305 $sql = CRM_Utils_SQL_Select::fragment();
d544ffcd 306
3c9d67b0 307 if (empty($params['target_contact_id']) && empty($params['source_contact_id'])
308 && empty($params['assignee_contact_id']) &&
309 !empty($params['check_permissions']) && !CRM_Core_Permission::check('view all activities')
310 && !CRM_Core_Permission::check('view all contacts')
311 ) {
312 // Force join on the activity contact table.
313 // @todo get this & other acl filters to work, remove check further down.
314 //$params['contact_id'] = array('IS NOT NULL' => TRUE);
315 }
316
d544ffcd
CW
317 _civicrm_api3_activity_get_extraFilters($params, $sql);
318
319 // Handle is_overdue sort
320 if (!empty($options['sort'])) {
321 $sort = explode(', ', $options['sort']);
322
323 foreach ($sort as $index => &$sortString) {
324 // Get sort field and direction
325 list($sortField, $dir) = array_pad(explode(' ', $sortString), 2, 'ASC');
326 if ($sortField == 'is_overdue') {
327 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
328 $sql->orderBy("IF((a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete)), 0, 1) $dir", NULL, $index);
329 // Replace the sort with a placeholder which will be ignored by sql
330 $sortString = '(1)';
331 }
332 }
333 $params['options']['sort'] = implode(', ', $sort);
334 }
335
336 // Ensure there's enough data for calculating is_overdue
337 if (!empty($options['return']['is_overdue']) && (empty($options['return']['status_id']) || empty($options['return']['activity_date_time']))) {
338 $options['return']['status_id'] = $options['return']['activity_date_time'] = 1;
339 $params['return'] = array_keys($options['return']);
340 }
341
342 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $sql);
343 if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('view all activities')) {
344 // @todo get this to work at the query level - see contact_id join above.
345 foreach ($activities as $activity) {
346 if (!CRM_Activity_BAO_Activity::checkPermission($activity['id'], CRM_Core_Action::VIEW)) {
347 unset($activities[$activity['id']]);
348 }
349 }
350 }
351 if ($options['is_count']) {
352 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
353 }
354
355 $activities = _civicrm_api3_activity_get_formatResult($params, $activities, $options);
356 //legacy custom data get - so previous formatted response is still returned too
357 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
358}
359
360/**
361 * Support filters beyond what basic_get can do.
362 *
363 * @param array $params
364 * @param CRM_Utils_SQL_Select $sql
365 * @throws \CiviCRM_API3_Exception
366 * @throws \Exception
367 */
368function _civicrm_api3_activity_get_extraFilters(&$params, &$sql) {
369 // Filter by activity contacts
370 $recordTypes = civicrm_api3('ActivityContact', 'getoptions', array('field' => 'record_type_id'));
371 $recordTypes = $recordTypes['values'];
372 $activityContactOptions = array(
373 'contact_id' => NULL,
374 'target_contact_id' => array_search('Activity Targets', $recordTypes),
375 'source_contact_id' => array_search('Activity Source', $recordTypes),
376 'assignee_contact_id' => array_search('Activity Assignees', $recordTypes),
377 );
526e0834
CW
378 foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
379 if (!empty($params[$activityContactName])) {
526e0834
CW
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 );
6a488035
TO
388 }
389 }
749522a2 390
760ac501 391 // Handle is_overdue filter
d544ffcd 392 // Boolean calculated field - does not support operators
760ac501 393 if (isset($params['is_overdue'])) {
ce9d78e1 394 $incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
760ac501
CW
395 if ($params['is_overdue']) {
396 $sql->where('a.activity_date_time < NOW()');
ce9d78e1 397 $sql->where("a.status_id IN ($incomplete)");
760ac501
CW
398 }
399 else {
ce9d78e1 400 $sql->where("(a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete))");
760ac501
CW
401 }
402 }
403
749522a2
TO
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 }
0298287b 446 }
6a488035 447 }
ab5fa8f2
TO
448}
449
450/**
61fe4988 451 * Given a list of activities, append any extra data requested about the activities.
ab5fa8f2 452 *
b081365f 453 * @note Called by civicrm-core and CiviHR
ab5fa8f2 454 *
cf470720
TO
455 * @param array $params
456 * API request parameters.
ab5fa8f2 457 * @param array $activities
61fe4988 458 *
a6c01b45 459 * @return array
72b3a70c 460 * new activities list
ab5fa8f2 461 */
bc4b6f0f 462function _civicrm_api3_activity_get_formatResult($params, $activities, $options) {
30db5cbf
CW
463 if (!$activities) {
464 return $activities;
465 }
466
bc4b6f0f 467 $returns = $options['return'];
6a488035
TO
468 foreach ($params as $n => $v) {
469 if (substr($n, 0, 7) == 'return.') {
470 $returnkey = substr($n, 7);
471 $returns[$returnkey] = $v;
472 }
473 }
0298287b 474
2f3d72cf 475 $returns['source_contact_id'] = 1;
db6e8cb4
CW
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
40875a91
CW
483 $tagGet = array('tag_id', 'entity_id');
484 foreach (array_keys($returns) as $key) {
485 if (strpos($key, 'tag_id.') === 0) {
486 $tagGet[] = $key;
487 $returns['tag_id'] = 1;
488 }
489 }
490
6a488035
TO
491 foreach ($returns as $n => $v) {
492 switch ($n) {
493 case 'assignee_contact_id':
494 foreach ($activities as $key => $activityArray) {
db6e8cb4
CW
495 $cids = $activities[$key]['assignee_contact_id'] = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($activityArray['id']);
496 if ($cids && !empty($returns['assignee_contact_name'])) {
497 foreach ($cids as $cid) {
498 $activities[$key]['assignee_contact_name'][$cid] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
499 }
500 }
6a488035
TO
501 }
502 break;
35671d00 503
6a488035
TO
504 case 'target_contact_id':
505 foreach ($activities as $key => $activityArray) {
db6e8cb4
CW
506 $cids = $activities[$key]['target_contact_id'] = CRM_Activity_BAO_ActivityTarget::retrieveTargetIdsByActivityId($activityArray['id']);
507 if ($cids && !empty($returns['target_contact_name'])) {
508 foreach ($cids as $cid) {
509 $activities[$key]['target_contact_name'][$cid] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
510 }
511 }
6a488035
TO
512 }
513 break;
35671d00 514
42d30b83
DL
515 case 'source_contact_id':
516 foreach ($activities as $key => $activityArray) {
db6e8cb4
CW
517 $cid = $activities[$key]['source_contact_id'] = CRM_Activity_BAO_Activity::getSourceContactID($activityArray['id']);
518 if ($cid && !empty($returns['source_contact_name'])) {
519 $activities[$key]['source_contact_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
520 }
42d30b83
DL
521 }
522 break;
35671d00 523
30db5cbf
CW
524 case 'tag_id':
525 $tags = civicrm_api3('EntityTag', 'get', array(
526 'entity_table' => 'civicrm_activity',
527 'entity_id' => array('IN' => array_keys($activities)),
40875a91 528 'return' => $tagGet,
30db5cbf
CW
529 'options' => array('limit' => 0),
530 ));
531 foreach ($tags['values'] as $tag) {
40875a91
CW
532 $key = (int) $tag['entity_id'];
533 unset($tag['entity_id'], $tag['id']);
534 $activities[$key]['tag_id'][$tag['tag_id']] = $tag;
535 }
536 break;
537
538 case 'file_id':
539 $dao = CRM_Core_DAO::executeQuery("SELECT entity_id, file_id FROM civicrm_entity_file WHERE entity_table = 'civicrm_activity' AND entity_id IN (%1)",
540 array(1 => array(implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)));
541 while ($dao->fetch()) {
542 $activities[$dao->entity_id]['file_id'][] = $dao->file_id;
30db5cbf
CW
543 }
544 break;
545
bc4b6f0f
CW
546 case 'case_id':
547 $dao = CRM_Core_DAO::executeQuery("SELECT activity_id, case_id FROM civicrm_case_activity WHERE activity_id IN (%1)",
548 array(1 => array(implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)));
549 while ($dao->fetch()) {
18e0f096 550 $activities[$dao->activity_id]['case_id'][] = $dao->case_id;
bc4b6f0f
CW
551 }
552 break;
553
760ac501
CW
554 case 'is_overdue':
555 foreach ($activities as $key => $activityArray) {
556 $activities[$key]['is_overdue'] = (int) CRM_Activity_BAO_Activity::isOverdue($activityArray);
557 }
558 break;
559
6a488035
TO
560 default:
561 if (substr($n, 0, 6) == 'custom') {
562 $returnProperties[$n] = $v;
563 }
564 }
565 }
526e0834 566
40875a91 567 // Legacy extras
526e0834
CW
568 if (!empty($params['contact_id'])) {
569 $statusOptions = CRM_Activity_BAO_Activity::buildOptions('status_id', 'get');
570 $typeOptions = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
571 foreach ($activities as $key => &$activityArray) {
572 if (!empty($activityArray['status_id'])) {
573 $activityArray['status'] = $statusOptions[$activityArray['status_id']];
574 }
575 if (!empty($activityArray['activity_type_id'])) {
576 $activityArray['activity_name'] = $typeOptions[$activityArray['activity_type_id']];
577 }
578 }
579 }
580
30db5cbf 581 if (!empty($returnProperties) || !empty($params['contact_id'])) {
6a488035 582 foreach ($activities as $activityId => $values) {
10114f2d 583 //@todo - should possibly load activity type id if not loaded (update with id)
e9ff5391 584 _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));
6a488035
TO
585 }
586 }
ab5fa8f2 587 return $activities;
6a488035
TO
588}
589
2f3d72cf 590
6a488035
TO
591/**
592 * Delete a specified Activity.
593 *
cf470720
TO
594 * @param array $params
595 * Array holding 'id' of activity to be deleted.
6a488035 596 *
10114f2d 597 * @throws API_Exception
6a488035 598 *
61fe4988 599 * @return array
00f8641b 600 * API result array
6a488035
TO
601 */
602function civicrm_api3_activity_delete($params) {
603
604 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
244bbdd8 605 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
6a488035
TO
606 }
607 else {
244bbdd8 608 throw new API_Exception('Could not delete Activity');
6a488035
TO
609 }
610}
611
612/**
61fe4988 613 * Check for required params.
6a488035 614 *
cf470720
TO
615 * @param array $params
616 * Associated array of fields.
10114f2d
EM
617 *
618 * @throws API_Exception
619 * @throws Exception
a6c01b45 620 * @return array
72b3a70c 621 * array with errors
6a488035
TO
622 */
623function _civicrm_api3_activity_check_params(&$params) {
35671d00 624 $activityIds = array(
7cdbcb16
TO
625 'activity' => CRM_Utils_Array::value('id', $params),
626 'parent' => CRM_Utils_Array::value('parent_id', $params),
627 'original' => CRM_Utils_Array::value('original_id', $params),
6a488035
TO
628 );
629
630 foreach ($activityIds as $id => $value) {
631 if ($value &&
632 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
633 ) {
10114f2d 634 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
6a488035
TO
635 }
636 }
637 // this should be handled by wrapper layer & probably the api would already manage it
638 //correctly by doing pseudoconstant validation
639 // needs testing
a60ed840 640 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
7cdbcb16
TO
641 $activityName = CRM_Utils_Array::value('activity_name', $params);
642 $activityName = ucfirst($activityName);
6a488035
TO
643 $activityLabel = CRM_Utils_Array::value('activity_label', $params);
644 if ($activityLabel) {
a60ed840 645 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
6a488035
TO
646 }
647
648 $activityTypeId = CRM_Utils_Array::value('activity_type_id', $params);
649
650 if ($activityName || $activityLabel) {
651 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
652
653 if (!$activityTypeIdInList) {
35671d00 654 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
6a488035
TO
655 throw new Exception($errorString);
656 }
657 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
10114f2d 658 throw new API_Exception('Mismatch in Activity');
6a488035
TO
659 }
660 $params['activity_type_id'] = $activityTypeIdInList;
661 }
662 elseif ($activityTypeId &&
663 !array_key_exists($activityTypeId, $activityTypes)
664 ) {
10114f2d 665 throw new API_Exception('Invalid Activity Type ID');
6a488035
TO
666 }
667
6a488035
TO
668 // check for activity duration minutes
669 // this should be validated @ the wrapper layer not here
670 // needs testing
671 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
10114f2d 672 throw new API_Exception('Invalid Activity Duration (in minutes)');
6a488035
TO
673 }
674
6a488035
TO
675 //if adding a new activity & date_time not set make it now
676 // this should be managed by the wrapper layer & setting ['api.default'] in speces
677 // needs testing
8cc574cf 678 if (empty($params['id']) && empty($params['activity_date_time'])) {
6a488035
TO
679 $params['activity_date_time'] = CRM_Utils_Date::processDate(date('Y-m-d H:i:s'));
680 }
681
682 return NULL;
683}
684
dabf9814 685/**
61fe4988
EM
686 * Get parameters for activity list.
687 *
7cdbcb16 688 * @see _civicrm_api3_generic_getlist_params
dabf9814 689 *
7cdbcb16
TO
690 * @param array $request
691 * API request.
dabf9814
CW
692 */
693function _civicrm_api3_activity_getlist_params(&$request) {
7cdbcb16
TO
694 $fieldsToReturn = array(
695 'activity_date_time',
696 'activity_type_id',
697 'subject',
698 'source_contact_id',
699 );
dabf9814
CW
700 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
701 $request['params']['options']['sort'] = 'activity_date_time DESC';
702 $request['params'] += array(
703 'is_current_revision' => 1,
704 'is_deleted' => 0,
705 );
706}
707
708/**
61fe4988
EM
709 * Get output for activity list.
710 *
dabf9814
CW
711 * @see _civicrm_api3_generic_getlist_output
712 *
8c6b335b
CW
713 * @param array $result
714 * @param array $request
dabf9814
CW
715 *
716 * @return array
717 */
718function _civicrm_api3_activity_getlist_output($result, $request) {
719 $output = array();
720 if (!empty($result['values'])) {
721 foreach ($result['values'] as $row) {
722 $data = array(
723 'id' => $row[$request['id_field']],
724 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
7cdbcb16
TO
725 'description' => array(
726 CRM_Core_Pseudoconstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
727 ),
dabf9814
CW
728 );
729 if (!empty($row['activity_date_time'])) {
730 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
731 }
732 if (!empty($row['source_contact_id'])) {
7cdbcb16
TO
733 $data['description'][] = ts('By %1', array(
734 1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
735 ));
dabf9814 736 }
8a938c69
CW
737 // Add repeating info
738 $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_activity');
739 $data['extra']['is_recur'] = FALSE;
740 if ($repeat) {
741 $data['suffix'] = ts('(%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
742 $data['extra']['is_recur'] = TRUE;
743 }
dabf9814
CW
744 $output[] = $data;
745 }
746 }
747 return $output;
748}