CRM-15905 fix - API: problem sorting contacts on ID
[civicrm-core.git] / api / v3 / Activity.php
CommitLineData
6a488035
TO
1<?php
2// $Id$
3
4/*
5 +--------------------------------------------------------------------+
39de6fd5 6 | CiviCRM version 4.6 |
6a488035 7 +--------------------------------------------------------------------+
731a0992 8 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
11 | |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
20 | |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
28 */
29
30/**
31 * File for the CiviCRM APIv3 activity functions
32 *
33 * @package CiviCRM_APIv3
34 * @subpackage API_Activity
731a0992 35 * @copyright CiviCRM LLC (c) 2004-2014
6a488035 36 * @version $Id: Activity.php 30486 2010-11-02 16:12:09Z shot $
6a488035
TO
37 */
38
39
40/**
61fe4988 41 * Creates or updates an Activity.
6a488035 42 *
cf470720 43 * @param array $params
61fe4988 44 * Array per getfields documentation.
6a488035 45 *
77b97be7 46 * @throws API_Exception
a6c01b45 47 * @return array
61fe4988 48 * Array containing 'is_error' to denote success or failure and details of the created activity.
6a488035
TO
49 */
50function civicrm_api3_activity_create($params) {
51
a7488080 52 if (empty($params['id'])) {
6a488035
TO
53 // an update does not require any mandatory parameters
54 civicrm_api3_verify_one_mandatory($params,
55 NULL,
56 array(
7cdbcb16
TO
57 'activity_name',
58 'activity_type_id',
59 'activity_label',
6a488035
TO
60 )
61 );
62 }
63
6a488035
TO
64 // check for various error and required conditions
65 // note that almost all the processing in there should be managed by the wrapper layer
66 // & should be removed - needs testing
67 $errors = _civicrm_api3_activity_check_params($params);
68
69 // this should not be required as should throw exception rather than return errors -
70 //needs testing
71 if (!empty($errors)) {
72 return $errors;
73 }
74
6a488035 75 // processing for custom data
10114f2d 76 $values = $activityArray = array();
6a488035
TO
77 _civicrm_api3_custom_format_params($params, $values, 'Activity');
78
79 if (!empty($values['custom'])) {
80 $params['custom'] = $values['custom'];
81 }
82
83 // this should be set as a default rather than hard coded
84 // needs testing
85 $params['skipRecentView'] = TRUE;
86
87 // If this is a case activity, see if there is an existing activity
88 // and set it as an old revision. Also retrieve details we'll need.
89 // this handling should all be moved to the BAO layer
7cdbcb16
TO
90 $case_id = '';
91 $createRevision = FALSE;
6a488035 92 $oldActivityValues = array();
e96d5fa3
CW
93 // Lookup case id if not supplied
94 if (!isset($params['case_id']) && !empty($params['id'])) {
95 $params['case_id'] = CRM_Core_DAO::singleValueQuery("SELECT case_id FROM civicrm_case_activity WHERE activity_id = " . (int) $params['id']);
96 }
a7488080 97 if (!empty($params['case_id'])) {
6a488035 98 $case_id = $params['case_id'];
a7488080 99 if (!empty($params['id'])) {
6a488035
TO
100 $oldActivityParams = array('id' => $params['id']);
101 if (!$oldActivityValues) {
102 CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
103 }
104 if (empty($oldActivityValues)) {
10114f2d 105 throw new API_Exception(ts("Unable to locate existing activity."));
6a488035
TO
106 }
107 else {
108 $activityDAO = new CRM_Activity_DAO_Activity();
109 $activityDAO->id = $params['id'];
110 $activityDAO->is_current_revision = 0;
111 if (!$activityDAO->save()) {
08007144
TO
112 if (is_object($activityDAO)) {
113 $activityDAO->free();
114 }
10114f2d 115 throw new API_Exception(ts("Unable to revision existing case activity."));
6a488035
TO
116 }
117 $createRevision = TRUE;
118 }
119 }
120 }
121
122 $deleteActivityAssignment = FALSE;
123 if (isset($params['assignee_contact_id'])) {
124 $deleteActivityAssignment = TRUE;
125 }
126
127 $deleteActivityTarget = FALSE;
128 if (isset($params['target_contact_id'])) {
129 $deleteActivityTarget = TRUE;
130 }
131
132 // this should all be handled at the BAO layer
133 $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
134 $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
135
136 if ($case_id && $createRevision) {
137 // This is very similar to the copy-to-case action.
138 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
139 $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
140 }
141 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
142 $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
143 }
144 $oldActivityValues['mode'] = 'copy';
145 $oldActivityValues['caseID'] = $case_id;
146 $oldActivityValues['activityID'] = $oldActivityValues['id'];
147 $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
148
149 $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
150 if (empty($copyToCase['error_msg'])) {
151 // now fix some things that are different from copy-to-case
152 // then fall through to the create below to update with the passed in params
153 $params['id'] = $copyToCase['newId'];
154 $params['is_auto'] = 0;
155 $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
156 }
157 else {
10114f2d 158 throw new API_Exception(ts("Unable to create new revision of case activity."));
6a488035
TO
159 }
160 }
161
162 // create activity
163 $activityBAO = CRM_Activity_BAO_Activity::create($params);
164
165 if (isset($activityBAO->id)) {
166 if ($case_id && !$createRevision) {
167 // If this is a brand new case activity we need to add this
168 $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
169 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
170 }
171
172 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
173 return civicrm_api3_create_success($activityArray, $params, 'activity', 'get', $activityBAO);
174 }
175}
11e09c59
TO
176
177/**
61fe4988
EM
178 * Specify Meta data for create.
179 *
180 * Note that this data is retrievable via the getfields function and is used for pre-filling defaults and
181 * ensuring mandatory requirements are met.
182 *
cf470720 183 * @param array $params
61fe4988 184 * Array of parameters determined by getfields.
6a488035
TO
185 */
186function _civicrm_api3_activity_create_spec(&$params) {
187
61fe4988 188 // Default for source_contact_id = currently logged in user.
6a488035
TO
189 $params['source_contact_id']['api.default'] = 'user_contact_id';
190
67744c4e
CW
191 $params['status_id']['api.aliases'] = array('activity_status');
192
6a488035
TO
193 $params['assignee_contact_id'] = array(
194 'name' => 'assignee_id',
195 'title' => 'assigned to',
196 'type' => 1,
2f3d72cf 197 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
6a488035
TO
198 );
199 $params['target_contact_id'] = array(
200 'name' => 'target_id',
201 'title' => 'Activity Target',
202 'type' => 1,
2f3d72cf 203 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
6a488035 204 );
2f3d72cf 205
206 $params['source_contact_id'] = array(
7cdbcb16
TO
207 'name' => 'source_contact_id',
208 'title' => 'Activity Source Contact',
209 'type' => 1,
210 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
211 'api.default' => 'user_contact_id',
2f3d72cf 212 );
213
6a488035
TO
214}
215
216/**
61fe4988 217 * Gets a CiviCRM activity according to parameters.
6a488035 218 *
cf470720 219 * @param array $params
61fe4988 220 * Array per getfields documentation.
6a488035
TO
221 *
222 * @return array
6a488035
TO
223 */
224function civicrm_api3_activity_get($params) {
225 if (!empty($params['contact_id'])) {
226 $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']);
61fe4988
EM
227 // BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write
228 // happens it won't get missed.
6a488035
TO
229 foreach ($activities as $key => $activityArray) {
230 $activities[$key]['id'] = $key;
231 }
232 }
233 else {
234 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE);
235 }
35671d00 236 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'activity', 'get');
22e263ad 237 if ($options['is_count']) {
e2e3c1ce
EM
238 return civicrm_api3_create_success($activities, $params, 'activity', 'get');
239 }
6a488035 240
ab5fa8f2
TO
241 $activities = _civicrm_api3_activity_get_formatResult($params, $activities);
242 //legacy custom data get - so previous formatted response is still returned too
243 return civicrm_api3_create_success($activities, $params, 'activity', 'get');
244}
245
246/**
61fe4988 247 * Given a list of activities, append any extra data requested about the activities.
ab5fa8f2
TO
248 *
249 * NOTE: Called by civicrm-core and CiviHR
250 *
cf470720
TO
251 * @param array $params
252 * API request parameters.
ab5fa8f2 253 * @param array $activities
61fe4988 254 *
a6c01b45 255 * @return array
72b3a70c 256 * new activities list
ab5fa8f2
TO
257 */
258function _civicrm_api3_activity_get_formatResult($params, $activities) {
6a488035
TO
259 $returns = CRM_Utils_Array::value('return', $params, array());
260 if (!is_array($returns)) {
261 $returns = str_replace(' ', '', $returns);
262 $returns = explode(',', $returns);
263 }
264 $returns = array_fill_keys($returns, 1);
265
266 foreach ($params as $n => $v) {
267 if (substr($n, 0, 7) == 'return.') {
268 $returnkey = substr($n, 7);
269 $returns[$returnkey] = $v;
270 }
271 }
2f3d72cf 272 $returns['source_contact_id'] = 1;
6a488035
TO
273 foreach ($returns as $n => $v) {
274 switch ($n) {
275 case 'assignee_contact_id':
276 foreach ($activities as $key => $activityArray) {
277 $activities[$key]['assignee_contact_id'] = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($activityArray['id']);
278 }
279 break;
35671d00 280
6a488035
TO
281 case 'target_contact_id':
282 foreach ($activities as $key => $activityArray) {
283 $activities[$key]['target_contact_id'] = CRM_Activity_BAO_ActivityTarget::retrieveTargetIdsByActivityId($activityArray['id']);
284 }
285 break;
35671d00 286
42d30b83
DL
287 case 'source_contact_id':
288 foreach ($activities as $key => $activityArray) {
289 $activities[$key]['source_contact_id'] = CRM_Activity_BAO_Activity::getSourceContactID($activityArray['id']);
290 }
291 break;
35671d00 292
6a488035
TO
293 default:
294 if (substr($n, 0, 6) == 'custom') {
295 $returnProperties[$n] = $v;
296 }
297 }
298 }
299 if (!empty($activities) && (!empty($returnProperties) || !empty($params['contact_id']))) {
300 foreach ($activities as $activityId => $values) {
10114f2d
EM
301 //@todo - should possibly load activity type id if not loaded (update with id)
302 _civicrm_api3_custom_data_get($activities[$activityId], 'Activity', $activityId, NULL, CRM_Utils_Array::value('activity_type_id', $values));
6a488035
TO
303 }
304 }
ab5fa8f2 305 return $activities;
6a488035
TO
306}
307
2f3d72cf 308
6a488035
TO
309/**
310 * Delete a specified Activity.
311 *
cf470720
TO
312 * @param array $params
313 * Array holding 'id' of activity to be deleted.
6a488035 314 *
10114f2d 315 * @throws API_Exception
6a488035 316 *
61fe4988 317 * @return array
6a488035
TO
318 */
319function civicrm_api3_activity_delete($params) {
320
321 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
322 return civicrm_api3_create_success(1, $params, 'activity', 'delete');
323 }
324 else {
10114f2d 325 throw new API_Exception('Could not delete activity');
6a488035
TO
326 }
327}
328
329/**
61fe4988 330 * Check for required params.
6a488035 331 *
cf470720
TO
332 * @param array $params
333 * Associated array of fields.
10114f2d
EM
334 *
335 * @throws API_Exception
336 * @throws Exception
a6c01b45 337 * @return array
72b3a70c 338 * array with errors
6a488035
TO
339 */
340function _civicrm_api3_activity_check_params(&$params) {
341
342 $contactIDFields = array_intersect_key($params,
7cdbcb16
TO
343 array(
344 'source_contact_id' => 1,
345 'assignee_contact_id' => 1,
346 'target_contact_id' => 1,
347 )
6a488035 348 );
42d30b83
DL
349
350 // this should be handled by wrapper layer & probably the api would already manage it
351 //correctly by doing post validation - ie. a failure should result in a roll-back = an error
352 // needs testing
6a488035
TO
353 if (!empty($contactIDFields)) {
354 $contactIds = array();
355 foreach ($contactIDFields as $fieldname => $contactfield) {
356 if (empty($contactfield)) {
357 continue;
358 }
359 if (is_array($contactfield)) {
360 foreach ($contactfield as $contactkey => $contactvalue) {
361 $contactIds[$contactvalue] = $contactvalue;
362 }
363 }
364 else {
365 $contactIds[$contactfield] = $contactfield;
366 }
367 }
368
6a488035
TO
369 $sql = '
370SELECT count(*)
371 FROM civicrm_contact
372 WHERE id IN (' . implode(', ', $contactIds) . ' )';
373 if (count($contactIds) != CRM_Core_DAO::singleValueQuery($sql)) {
61fe4988 374 throw new API_Exception('Invalid Contact Id');
6a488035
TO
375 }
376 }
377
35671d00 378 $activityIds = array(
7cdbcb16
TO
379 'activity' => CRM_Utils_Array::value('id', $params),
380 'parent' => CRM_Utils_Array::value('parent_id', $params),
381 'original' => CRM_Utils_Array::value('original_id', $params),
6a488035
TO
382 );
383
384 foreach ($activityIds as $id => $value) {
385 if ($value &&
386 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
387 ) {
10114f2d 388 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
6a488035
TO
389 }
390 }
391 // this should be handled by wrapper layer & probably the api would already manage it
392 //correctly by doing pseudoconstant validation
393 // needs testing
a60ed840 394 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
7cdbcb16
TO
395 $activityName = CRM_Utils_Array::value('activity_name', $params);
396 $activityName = ucfirst($activityName);
6a488035
TO
397 $activityLabel = CRM_Utils_Array::value('activity_label', $params);
398 if ($activityLabel) {
a60ed840 399 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
6a488035
TO
400 }
401
402 $activityTypeId = CRM_Utils_Array::value('activity_type_id', $params);
403
404 if ($activityName || $activityLabel) {
405 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
406
407 if (!$activityTypeIdInList) {
35671d00 408 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
6a488035
TO
409 throw new Exception($errorString);
410 }
411 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
10114f2d 412 throw new API_Exception('Mismatch in Activity');
6a488035
TO
413 }
414 $params['activity_type_id'] = $activityTypeIdInList;
415 }
416 elseif ($activityTypeId &&
417 !array_key_exists($activityTypeId, $activityTypes)
418 ) {
10114f2d 419 throw new API_Exception('Invalid Activity Type ID');
6a488035
TO
420 }
421
6a488035
TO
422 // check for activity duration minutes
423 // this should be validated @ the wrapper layer not here
424 // needs testing
425 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
10114f2d 426 throw new API_Exception('Invalid Activity Duration (in minutes)');
6a488035
TO
427 }
428
6a488035
TO
429 //if adding a new activity & date_time not set make it now
430 // this should be managed by the wrapper layer & setting ['api.default'] in speces
431 // needs testing
8cc574cf 432 if (empty($params['id']) && empty($params['activity_date_time'])) {
6a488035
TO
433 $params['activity_date_time'] = CRM_Utils_Date::processDate(date('Y-m-d H:i:s'));
434 }
435
436 return NULL;
437}
438
dabf9814 439/**
61fe4988
EM
440 * Get parameters for activity list.
441 *
7cdbcb16 442 * @see _civicrm_api3_generic_getlist_params
dabf9814 443 *
7cdbcb16
TO
444 * @param array $request
445 * API request.
dabf9814
CW
446 */
447function _civicrm_api3_activity_getlist_params(&$request) {
7cdbcb16
TO
448 $fieldsToReturn = array(
449 'activity_date_time',
450 'activity_type_id',
451 'subject',
452 'source_contact_id',
453 );
dabf9814
CW
454 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
455 $request['params']['options']['sort'] = 'activity_date_time DESC';
456 $request['params'] += array(
457 'is_current_revision' => 1,
458 'is_deleted' => 0,
459 );
460}
461
462/**
61fe4988
EM
463 * Get output for activity list.
464 *
dabf9814
CW
465 * @see _civicrm_api3_generic_getlist_output
466 *
8c6b335b
CW
467 * @param array $result
468 * @param array $request
dabf9814
CW
469 *
470 * @return array
471 */
472function _civicrm_api3_activity_getlist_output($result, $request) {
473 $output = array();
474 if (!empty($result['values'])) {
475 foreach ($result['values'] as $row) {
476 $data = array(
477 'id' => $row[$request['id_field']],
478 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
7cdbcb16
TO
479 'description' => array(
480 CRM_Core_Pseudoconstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
481 ),
dabf9814
CW
482 );
483 if (!empty($row['activity_date_time'])) {
484 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
485 }
486 if (!empty($row['source_contact_id'])) {
7cdbcb16
TO
487 $data['description'][] = ts('By %1', array(
488 1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
489 ));
dabf9814
CW
490 }
491 foreach ($request['extra'] as $field) {
492 $data['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
493 }
494 $output[] = $data;
495 }
496 }
497 return $output;
498}