Merge pull request #5901 from colemanw/CRM-16557
[civicrm-core.git] / api / v3 / Activity.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
61fe4988 43 * Array containing 'is_error' to denote success or failure and details of the created activity.
6a488035
TO
44 */
45function civicrm_api3_activity_create($params) {
46
a7488080 47 if (empty($params['id'])) {
6a488035
TO
48 // an update does not require any mandatory parameters
49 civicrm_api3_verify_one_mandatory($params,
50 NULL,
51 array(
7cdbcb16
TO
52 'activity_name',
53 'activity_type_id',
54 'activity_label',
6a488035
TO
55 )
56 );
57 }
58
6a488035
TO
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
6a488035 70 // processing for custom data
10114f2d 71 $values = $activityArray = array();
6a488035
TO
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
7cdbcb16
TO
85 $case_id = '';
86 $createRevision = FALSE;
6a488035 87 $oldActivityValues = array();
e96d5fa3
CW
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 }
a7488080 92 if (!empty($params['case_id'])) {
6a488035 93 $case_id = $params['case_id'];
a7488080 94 if (!empty($params['id'])) {
6a488035
TO
95 $oldActivityParams = array('id' => $params['id']);
96 if (!$oldActivityValues) {
97 CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
98 }
99 if (empty($oldActivityValues)) {
10114f2d 100 throw new API_Exception(ts("Unable to locate existing activity."));
6a488035
TO
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()) {
08007144
TO
107 if (is_object($activityDAO)) {
108 $activityDAO->free();
109 }
10114f2d 110 throw new API_Exception(ts("Unable to revision existing case activity."));
6a488035
TO
111 }
112 $createRevision = TRUE;
113 }
114 }
115 }
116
117 $deleteActivityAssignment = FALSE;
118 if (isset($params['assignee_contact_id'])) {
119 $deleteActivityAssignment = TRUE;
120 }
121
122 $deleteActivityTarget = FALSE;
123 if (isset($params['target_contact_id'])) {
124 $deleteActivityTarget = TRUE;
125 }
126
127 // this should all be handled at the BAO layer
128 $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
129 $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
130
131 if ($case_id && $createRevision) {
132 // This is very similar to the copy-to-case action.
133 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
134 $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
135 }
136 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
137 $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
138 }
139 $oldActivityValues['mode'] = 'copy';
140 $oldActivityValues['caseID'] = $case_id;
141 $oldActivityValues['activityID'] = $oldActivityValues['id'];
142 $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
143
144 $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
145 if (empty($copyToCase['error_msg'])) {
146 // now fix some things that are different from copy-to-case
147 // then fall through to the create below to update with the passed in params
148 $params['id'] = $copyToCase['newId'];
149 $params['is_auto'] = 0;
150 $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
151 }
152 else {
10114f2d 153 throw new API_Exception(ts("Unable to create new revision of case activity."));
6a488035
TO
154 }
155 }
156
157 // create activity
158 $activityBAO = CRM_Activity_BAO_Activity::create($params);
159
160 if (isset($activityBAO->id)) {
161 if ($case_id && !$createRevision) {
162 // If this is a brand new case activity we need to add this
163 $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
164 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
165 }
166
167 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
244bbdd8 168 return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
6a488035
TO
169 }
170}
11e09c59
TO
171
172/**
61fe4988
EM
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 *
cf470720 178 * @param array $params
c28e1768 179 * Array of parameters determined by getfields.
6a488035
TO
180 */
181function _civicrm_api3_activity_create_spec(&$params) {
182
61fe4988 183 // Default for source_contact_id = currently logged in user.
6a488035
TO
184 $params['source_contact_id']['api.default'] = 'user_contact_id';
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',
190 'title' => 'assigned to',
191 'type' => 1,
2f3d72cf 192 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
6a488035
TO
193 );
194 $params['target_contact_id'] = array(
195 'name' => 'target_id',
196 'title' => 'Activity Target',
197 'type' => 1,
2f3d72cf 198 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
6a488035 199 );
2f3d72cf 200
201 $params['source_contact_id'] = array(
7cdbcb16
TO
202 'name' => 'source_contact_id',
203 'title' => 'Activity Source Contact',
204 'type' => 1,
205 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
206 'api.default' => 'user_contact_id',
2f3d72cf 207 );
208
6a488035
TO
209}
210
211/**
61fe4988 212 * Gets a CiviCRM activity according to parameters.
6a488035 213 *
cf470720 214 * @param array $params
61fe4988 215 * Array per getfields documentation.
6a488035
TO
216 *
217 * @return array
6a488035
TO
218 */
219function civicrm_api3_activity_get($params) {
220 if (!empty($params['contact_id'])) {
221 $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']);
61fe4988
EM
222 // BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write
223 // happens it won't get missed.
6a488035
TO
224 foreach ($activities as $key => $activityArray) {
225 $activities[$key]['id'] = $key;
226 }
227 }
228 else {
229 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE);
230 }
244bbdd8 231 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
22e263ad 232 if ($options['is_count']) {
244bbdd8 233 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
e2e3c1ce 234 }
6a488035 235
ab5fa8f2
TO
236 $activities = _civicrm_api3_activity_get_formatResult($params, $activities);
237 //legacy custom data get - so previous formatted response is still returned too
244bbdd8 238 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
ab5fa8f2
TO
239}
240
241/**
61fe4988 242 * Given a list of activities, append any extra data requested about the activities.
ab5fa8f2 243 *
b081365f 244 * @note Called by civicrm-core and CiviHR
ab5fa8f2 245 *
cf470720
TO
246 * @param array $params
247 * API request parameters.
ab5fa8f2 248 * @param array $activities
61fe4988 249 *
a6c01b45 250 * @return array
72b3a70c 251 * new activities list
ab5fa8f2
TO
252 */
253function _civicrm_api3_activity_get_formatResult($params, $activities) {
6a488035
TO
254 $returns = CRM_Utils_Array::value('return', $params, array());
255 if (!is_array($returns)) {
256 $returns = str_replace(' ', '', $returns);
257 $returns = explode(',', $returns);
258 }
259 $returns = array_fill_keys($returns, 1);
260
261 foreach ($params as $n => $v) {
262 if (substr($n, 0, 7) == 'return.') {
263 $returnkey = substr($n, 7);
264 $returns[$returnkey] = $v;
265 }
266 }
2f3d72cf 267 $returns['source_contact_id'] = 1;
6a488035
TO
268 foreach ($returns as $n => $v) {
269 switch ($n) {
270 case 'assignee_contact_id':
271 foreach ($activities as $key => $activityArray) {
272 $activities[$key]['assignee_contact_id'] = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($activityArray['id']);
273 }
274 break;
35671d00 275
6a488035
TO
276 case 'target_contact_id':
277 foreach ($activities as $key => $activityArray) {
278 $activities[$key]['target_contact_id'] = CRM_Activity_BAO_ActivityTarget::retrieveTargetIdsByActivityId($activityArray['id']);
279 }
280 break;
35671d00 281
42d30b83
DL
282 case 'source_contact_id':
283 foreach ($activities as $key => $activityArray) {
284 $activities[$key]['source_contact_id'] = CRM_Activity_BAO_Activity::getSourceContactID($activityArray['id']);
285 }
286 break;
35671d00 287
6a488035
TO
288 default:
289 if (substr($n, 0, 6) == 'custom') {
290 $returnProperties[$n] = $v;
291 }
292 }
293 }
294 if (!empty($activities) && (!empty($returnProperties) || !empty($params['contact_id']))) {
295 foreach ($activities as $activityId => $values) {
10114f2d
EM
296 //@todo - should possibly load activity type id if not loaded (update with id)
297 _civicrm_api3_custom_data_get($activities[$activityId], 'Activity', $activityId, NULL, CRM_Utils_Array::value('activity_type_id', $values));
6a488035
TO
298 }
299 }
ab5fa8f2 300 return $activities;
6a488035
TO
301}
302
2f3d72cf 303
6a488035
TO
304/**
305 * Delete a specified Activity.
306 *
cf470720
TO
307 * @param array $params
308 * Array holding 'id' of activity to be deleted.
6a488035 309 *
10114f2d 310 * @throws API_Exception
6a488035 311 *
61fe4988 312 * @return array
6a488035
TO
313 */
314function civicrm_api3_activity_delete($params) {
315
316 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
244bbdd8 317 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
6a488035
TO
318 }
319 else {
244bbdd8 320 throw new API_Exception('Could not delete Activity');
6a488035
TO
321 }
322}
323
324/**
61fe4988 325 * Check for required params.
6a488035 326 *
cf470720
TO
327 * @param array $params
328 * Associated array of fields.
10114f2d
EM
329 *
330 * @throws API_Exception
331 * @throws Exception
a6c01b45 332 * @return array
72b3a70c 333 * array with errors
6a488035
TO
334 */
335function _civicrm_api3_activity_check_params(&$params) {
336
337 $contactIDFields = array_intersect_key($params,
7cdbcb16
TO
338 array(
339 'source_contact_id' => 1,
340 'assignee_contact_id' => 1,
341 'target_contact_id' => 1,
342 )
6a488035 343 );
42d30b83
DL
344
345 // this should be handled by wrapper layer & probably the api would already manage it
346 //correctly by doing post validation - ie. a failure should result in a roll-back = an error
347 // needs testing
6a488035
TO
348 if (!empty($contactIDFields)) {
349 $contactIds = array();
350 foreach ($contactIDFields as $fieldname => $contactfield) {
351 if (empty($contactfield)) {
352 continue;
353 }
354 if (is_array($contactfield)) {
355 foreach ($contactfield as $contactkey => $contactvalue) {
356 $contactIds[$contactvalue] = $contactvalue;
357 }
358 }
359 else {
360 $contactIds[$contactfield] = $contactfield;
361 }
362 }
363
6a488035
TO
364 $sql = '
365SELECT count(*)
366 FROM civicrm_contact
367 WHERE id IN (' . implode(', ', $contactIds) . ' )';
368 if (count($contactIds) != CRM_Core_DAO::singleValueQuery($sql)) {
61fe4988 369 throw new API_Exception('Invalid Contact Id');
6a488035
TO
370 }
371 }
372
35671d00 373 $activityIds = array(
7cdbcb16
TO
374 'activity' => CRM_Utils_Array::value('id', $params),
375 'parent' => CRM_Utils_Array::value('parent_id', $params),
376 'original' => CRM_Utils_Array::value('original_id', $params),
6a488035
TO
377 );
378
379 foreach ($activityIds as $id => $value) {
380 if ($value &&
381 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
382 ) {
10114f2d 383 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
6a488035
TO
384 }
385 }
386 // this should be handled by wrapper layer & probably the api would already manage it
387 //correctly by doing pseudoconstant validation
388 // needs testing
a60ed840 389 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
7cdbcb16
TO
390 $activityName = CRM_Utils_Array::value('activity_name', $params);
391 $activityName = ucfirst($activityName);
6a488035
TO
392 $activityLabel = CRM_Utils_Array::value('activity_label', $params);
393 if ($activityLabel) {
a60ed840 394 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
6a488035
TO
395 }
396
397 $activityTypeId = CRM_Utils_Array::value('activity_type_id', $params);
398
399 if ($activityName || $activityLabel) {
400 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
401
402 if (!$activityTypeIdInList) {
35671d00 403 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
6a488035
TO
404 throw new Exception($errorString);
405 }
406 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
10114f2d 407 throw new API_Exception('Mismatch in Activity');
6a488035
TO
408 }
409 $params['activity_type_id'] = $activityTypeIdInList;
410 }
411 elseif ($activityTypeId &&
412 !array_key_exists($activityTypeId, $activityTypes)
413 ) {
10114f2d 414 throw new API_Exception('Invalid Activity Type ID');
6a488035
TO
415 }
416
6a488035
TO
417 // check for activity duration minutes
418 // this should be validated @ the wrapper layer not here
419 // needs testing
420 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
10114f2d 421 throw new API_Exception('Invalid Activity Duration (in minutes)');
6a488035
TO
422 }
423
6a488035
TO
424 //if adding a new activity & date_time not set make it now
425 // this should be managed by the wrapper layer & setting ['api.default'] in speces
426 // needs testing
8cc574cf 427 if (empty($params['id']) && empty($params['activity_date_time'])) {
6a488035
TO
428 $params['activity_date_time'] = CRM_Utils_Date::processDate(date('Y-m-d H:i:s'));
429 }
430
431 return NULL;
432}
433
dabf9814 434/**
61fe4988
EM
435 * Get parameters for activity list.
436 *
7cdbcb16 437 * @see _civicrm_api3_generic_getlist_params
dabf9814 438 *
7cdbcb16
TO
439 * @param array $request
440 * API request.
dabf9814
CW
441 */
442function _civicrm_api3_activity_getlist_params(&$request) {
7cdbcb16
TO
443 $fieldsToReturn = array(
444 'activity_date_time',
445 'activity_type_id',
446 'subject',
447 'source_contact_id',
448 );
dabf9814
CW
449 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
450 $request['params']['options']['sort'] = 'activity_date_time DESC';
451 $request['params'] += array(
452 'is_current_revision' => 1,
453 'is_deleted' => 0,
454 );
455}
456
457/**
61fe4988
EM
458 * Get output for activity list.
459 *
dabf9814
CW
460 * @see _civicrm_api3_generic_getlist_output
461 *
8c6b335b
CW
462 * @param array $result
463 * @param array $request
dabf9814
CW
464 *
465 * @return array
466 */
467function _civicrm_api3_activity_getlist_output($result, $request) {
468 $output = array();
469 if (!empty($result['values'])) {
470 foreach ($result['values'] as $row) {
471 $data = array(
472 'id' => $row[$request['id_field']],
473 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
7cdbcb16
TO
474 'description' => array(
475 CRM_Core_Pseudoconstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
476 ),
dabf9814
CW
477 );
478 if (!empty($row['activity_date_time'])) {
479 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
480 }
481 if (!empty($row['source_contact_id'])) {
7cdbcb16
TO
482 $data['description'][] = ts('By %1', array(
483 1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
484 ));
dabf9814 485 }
8a938c69
CW
486 // Add repeating info
487 $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_activity');
488 $data['extra']['is_recur'] = FALSE;
489 if ($repeat) {
490 $data['suffix'] = ts('(%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
491 $data['extra']['is_recur'] = TRUE;
492 }
dabf9814
CW
493 $output[] = $data;
494 }
495 }
496 return $output;
497}