Merge pull request #8384 from rohankatkar/CRM_18406
[civicrm-core.git] / api / v3 / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
47 if (empty($params['id'])) {
48 // an update does not require any mandatory parameters
49 civicrm_api3_verify_one_mandatory($params,
50 NULL,
51 array(
52 'activity_name',
53 'activity_type_id',
54 'activity_label',
55 )
56 );
57 }
58
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
70 // processing for custom data
71 $values = $activityArray = array();
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
85 $case_id = '';
86 $createRevision = FALSE;
87 $oldActivityValues = array();
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 }
92 if (!empty($params['case_id'])) {
93 $case_id = $params['case_id'];
94 if (!empty($params['id'])) {
95 $oldActivityParams = array('id' => $params['id']);
96 if (!$oldActivityValues) {
97 CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
98 }
99 if (empty($oldActivityValues)) {
100 throw new API_Exception(ts("Unable to locate existing activity."));
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()) {
107 if (is_object($activityDAO)) {
108 $activityDAO->free();
109 }
110 throw new API_Exception(ts("Unable to revision existing case activity."));
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 {
153 throw new API_Exception(ts("Unable to create new revision of case activity."));
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]);
168 return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
169 }
170 }
171
172 /**
173 * Specify Meta data for create.
174 *
175 * Note that this data is retrievable via the getfields function and is used for pre-filling defaults and
176 * ensuring mandatory requirements are met.
177 *
178 * @param array $params
179 * Array of parameters determined by getfields.
180 */
181 function _civicrm_api3_activity_create_spec(&$params) {
182
183 // Default for source_contact_id = currently logged in user.
184 $params['source_contact_id']['api.default'] = 'user_contact_id';
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 );
214
215 $params['case_id'] = array(
216 'name' => 'case_id',
217 'title' => 'Case ID',
218 'description' => 'For creating an activity as part of a case.',
219 'type' => 1,
220 'FKClassName' => 'CRM_Case_DAO_Case',
221 'FKApiName' => 'Case',
222 );
223
224 }
225
226 /**
227 * Gets a CiviCRM activity according to parameters.
228 *
229 * @param array $params
230 * Array per getfields documentation.
231 *
232 * @return array API result array
233 * API result array
234 *
235 * @throws \API_Exception
236 * @throws \CiviCRM_API3_Exception
237 * @throws \Civi\API\Exception\UnauthorizedException
238 */
239 function civicrm_api3_activity_get($params) {
240 if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('view all activities')) {
241 // In absence of view all activities permission it's possible to see a specific activity by ACL.
242 // Note still allowing view all activities to override ACLs is based on the 'don't change too much
243 // if you are not sure principle' and it could be argued that the ACLs should always be applied.
244 if (empty($params['id']) || !empty($params['contact_id'])) {
245 // We fall back to the original blunt permissions if we don't have an id to check or we are about
246 // to go to the weird place that the legacy 'contact_id' parameter takes us to.
247 throw new \Civi\API\Exception\UnauthorizedException(
248 "Cannot access activities. Required permission: 'view all activities''"
249 );
250 }
251
252 if (!CRM_Activity_BAO_Activity::checkPermission($params['id'], CRM_Core_Action::VIEW)) {
253 throw new \Civi\API\Exception\UnauthorizedException(
254 'You do not have permission to view this activity'
255 );
256 }
257 }
258
259 if (!empty($params['contact_id'])) {
260 $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']);
261 // BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write
262 // happens it won't get missed.
263 foreach ($activities as $key => $activityArray) {
264 $activities[$key]['id'] = $key;
265 }
266 }
267 else {
268 $sql = CRM_Utils_SQL_Select::fragment();
269 $options = civicrm_api3('ActivityContact', 'getoptions', array('field' => 'record_type_id'));
270 $options = $options['values'];
271 $activityContactOptions = array(
272 'target_contact_id' => array_search('Activity Targets', $options),
273 'source_contact_id' => array_search('Activity Source', $options),
274 'assignee_contact_id' => array_search('Activity Assignees', $options),
275 );
276 foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
277 if (!empty($params[$activityContactName])) {
278 // If the intent is to have multiple joins -- one for each relation -- then you would
279 // need different table aliases. Consider replacing 'ac' and passing in a '!alias' param,
280 // with a different value for each relation.
281 $sql->join(
282 'activity_' . $activityContactName,
283 'LEFT JOIN civicrm_activity_contact ac ON a.id = ac.activity_id AND ac.record_type_id = #typeId',
284 array('typeId' => $activityContactValue)
285 );
286 $sql->where('ac.contact_id IN (#cid)', array(
287 'cid' => $params[$activityContactName],
288 ));
289 }
290 }
291 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $sql);
292 }
293 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
294 if ($options['is_count']) {
295 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
296 }
297
298 $activities = _civicrm_api3_activity_get_formatResult($params, $activities);
299 //legacy custom data get - so previous formatted response is still returned too
300 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
301 }
302
303 /**
304 * Given a list of activities, append any extra data requested about the activities.
305 *
306 * @note Called by civicrm-core and CiviHR
307 *
308 * @param array $params
309 * API request parameters.
310 * @param array $activities
311 *
312 * @return array
313 * new activities list
314 */
315 function _civicrm_api3_activity_get_formatResult($params, $activities) {
316 $returns = CRM_Utils_Array::value('return', $params, array());
317 if (!is_array($returns)) {
318 $returns = str_replace(' ', '', $returns);
319 $returns = explode(',', $returns);
320 }
321 $returns = array_fill_keys($returns, 1);
322
323 foreach ($params as $n => $v) {
324 if (substr($n, 0, 7) == 'return.') {
325 $returnkey = substr($n, 7);
326 $returns[$returnkey] = $v;
327 }
328 }
329
330 $returns['source_contact_id'] = 1;
331 foreach ($returns as $n => $v) {
332 switch ($n) {
333 case 'assignee_contact_id':
334 foreach ($activities as $key => $activityArray) {
335 $activities[$key]['assignee_contact_id'] = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($activityArray['id']);
336 }
337 break;
338
339 case 'target_contact_id':
340 foreach ($activities as $key => $activityArray) {
341 $activities[$key]['target_contact_id'] = CRM_Activity_BAO_ActivityTarget::retrieveTargetIdsByActivityId($activityArray['id']);
342 }
343 break;
344
345 case 'source_contact_id':
346 foreach ($activities as $key => $activityArray) {
347 $activities[$key]['source_contact_id'] = CRM_Activity_BAO_Activity::getSourceContactID($activityArray['id']);
348 }
349 break;
350
351 default:
352 if (substr($n, 0, 6) == 'custom') {
353 $returnProperties[$n] = $v;
354 }
355 }
356 }
357 if (!empty($activities) && (!empty($returnProperties) || !empty($params['contact_id']))) {
358 foreach ($activities as $activityId => $values) {
359 //@todo - should possibly load activity type id if not loaded (update with id)
360 _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));
361 }
362 }
363 return $activities;
364 }
365
366
367 /**
368 * Delete a specified Activity.
369 *
370 * @param array $params
371 * Array holding 'id' of activity to be deleted.
372 *
373 * @throws API_Exception
374 *
375 * @return array
376 * API result array
377 */
378 function civicrm_api3_activity_delete($params) {
379
380 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
381 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
382 }
383 else {
384 throw new API_Exception('Could not delete Activity');
385 }
386 }
387
388 /**
389 * Check for required params.
390 *
391 * @param array $params
392 * Associated array of fields.
393 *
394 * @throws API_Exception
395 * @throws Exception
396 * @return array
397 * array with errors
398 */
399 function _civicrm_api3_activity_check_params(&$params) {
400
401 $contactIDFields = array_intersect_key($params,
402 array(
403 'source_contact_id' => 1,
404 'assignee_contact_id' => 1,
405 'target_contact_id' => 1,
406 )
407 );
408
409 // this should be handled by wrapper layer & probably the api would already manage it
410 //correctly by doing post validation - ie. a failure should result in a roll-back = an error
411 // needs testing
412 if (!empty($contactIDFields)) {
413 $contactIds = array();
414 foreach ($contactIDFields as $fieldname => $contactfield) {
415 if (empty($contactfield)) {
416 continue;
417 }
418 if (is_array($contactfield)) {
419 foreach ($contactfield as $contactkey => $contactvalue) {
420 $contactIds[$contactvalue] = $contactvalue;
421 }
422 }
423 else {
424 $contactIds[$contactfield] = $contactfield;
425 }
426 }
427
428 $sql = '
429 SELECT count(*)
430 FROM civicrm_contact
431 WHERE id IN (' . implode(', ', $contactIds) . ' )';
432 if (count($contactIds) != CRM_Core_DAO::singleValueQuery($sql)) {
433 throw new API_Exception('Invalid Contact Id');
434 }
435 }
436
437 $activityIds = array(
438 'activity' => CRM_Utils_Array::value('id', $params),
439 'parent' => CRM_Utils_Array::value('parent_id', $params),
440 'original' => CRM_Utils_Array::value('original_id', $params),
441 );
442
443 foreach ($activityIds as $id => $value) {
444 if ($value &&
445 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
446 ) {
447 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
448 }
449 }
450 // this should be handled by wrapper layer & probably the api would already manage it
451 //correctly by doing pseudoconstant validation
452 // needs testing
453 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
454 $activityName = CRM_Utils_Array::value('activity_name', $params);
455 $activityName = ucfirst($activityName);
456 $activityLabel = CRM_Utils_Array::value('activity_label', $params);
457 if ($activityLabel) {
458 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
459 }
460
461 $activityTypeId = CRM_Utils_Array::value('activity_type_id', $params);
462
463 if ($activityName || $activityLabel) {
464 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
465
466 if (!$activityTypeIdInList) {
467 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
468 throw new Exception($errorString);
469 }
470 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
471 throw new API_Exception('Mismatch in Activity');
472 }
473 $params['activity_type_id'] = $activityTypeIdInList;
474 }
475 elseif ($activityTypeId &&
476 !array_key_exists($activityTypeId, $activityTypes)
477 ) {
478 throw new API_Exception('Invalid Activity Type ID');
479 }
480
481 // check for activity duration minutes
482 // this should be validated @ the wrapper layer not here
483 // needs testing
484 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
485 throw new API_Exception('Invalid Activity Duration (in minutes)');
486 }
487
488 //if adding a new activity & date_time not set make it now
489 // this should be managed by the wrapper layer & setting ['api.default'] in speces
490 // needs testing
491 if (empty($params['id']) && empty($params['activity_date_time'])) {
492 $params['activity_date_time'] = CRM_Utils_Date::processDate(date('Y-m-d H:i:s'));
493 }
494
495 return NULL;
496 }
497
498 /**
499 * Get parameters for activity list.
500 *
501 * @see _civicrm_api3_generic_getlist_params
502 *
503 * @param array $request
504 * API request.
505 */
506 function _civicrm_api3_activity_getlist_params(&$request) {
507 $fieldsToReturn = array(
508 'activity_date_time',
509 'activity_type_id',
510 'subject',
511 'source_contact_id',
512 );
513 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
514 $request['params']['options']['sort'] = 'activity_date_time DESC';
515 $request['params'] += array(
516 'is_current_revision' => 1,
517 'is_deleted' => 0,
518 );
519 }
520
521 /**
522 * Get output for activity list.
523 *
524 * @see _civicrm_api3_generic_getlist_output
525 *
526 * @param array $result
527 * @param array $request
528 *
529 * @return array
530 */
531 function _civicrm_api3_activity_getlist_output($result, $request) {
532 $output = array();
533 if (!empty($result['values'])) {
534 foreach ($result['values'] as $row) {
535 $data = array(
536 'id' => $row[$request['id_field']],
537 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
538 'description' => array(
539 CRM_Core_Pseudoconstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
540 ),
541 );
542 if (!empty($row['activity_date_time'])) {
543 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
544 }
545 if (!empty($row['source_contact_id'])) {
546 $data['description'][] = ts('By %1', array(
547 1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
548 ));
549 }
550 // Add repeating info
551 $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_activity');
552 $data['extra']['is_recur'] = FALSE;
553 if ($repeat) {
554 $data['suffix'] = ts('(%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
555 $data['extra']['is_recur'] = TRUE;
556 }
557 $output[] = $data;
558 }
559 }
560 return $output;
561 }