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