Merge pull request #17656 from civicrm/5.27
[civicrm-core.git] / api / v3 / Job.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This api is used for working with scheduled "cron" jobs.
14 *
15 * @package CiviCRM_APIv3
16 */
17
18 /**
19 * Adjust metadata for "Create" action.
20 *
21 * The metadata is used for setting defaults, documentation & validation.
22 *
23 * @param array $params
24 * Array of parameters determined by getfields.
25 */
26 function _civicrm_api3_job_create_spec(&$params) {
27 $params['run_frequency']['api.required'] = 1;
28 $params['name']['api.required'] = 1;
29 $params['api_entity']['api.required'] = 1;
30 $params['api_action']['api.required'] = 1;
31
32 $params['domain_id']['api.default'] = CRM_Core_Config::domainID();
33 $params['is_active']['api.default'] = 1;
34 }
35
36 /**
37 * Create scheduled job.
38 *
39 * @param array $params
40 * Associative array of property name/value pairs to insert in new job.
41 *
42 * @return array
43 */
44 function civicrm_api3_job_create($params) {
45 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Job');
46 }
47
48 /**
49 * Adjust metadata for clone spec action.
50 *
51 * @param array $spec
52 */
53 function _civicrm_api3_job_clone_spec(&$spec) {
54 $spec['id']['title'] = 'Job ID to clone';
55 $spec['id']['type'] = CRM_Utils_Type::T_INT;
56 $spec['id']['api.required'] = 1;
57 $spec['is_active']['title'] = 'Job is Active?';
58 $spec['is_active']['type'] = CRM_Utils_Type::T_BOOLEAN;
59 $spec['is_active']['api.required'] = 0;
60 }
61
62 /**
63 * Clone Job.
64 *
65 * @param array $params
66 *
67 * @return array
68 * @throws \API_Exception
69 * @throws \CiviCRM_API3_Exception
70 */
71 function civicrm_api3_job_clone($params) {
72 if (empty($params['id'])) {
73 throw new API_Exception("Mandatory key(s) missing from params array: id field is required");
74 }
75 $id = $params['id'];
76 unset($params['id']);
77 $params['last_run'] = 'null';
78 $params['scheduled_run_date'] = 'null';
79 $newJobDAO = CRM_Core_BAO_Job::copy($id, $params);
80 return civicrm_api3('Job', 'get', ['id' => $newJobDAO->id]);
81 }
82
83 /**
84 * Retrieve one or more job.
85 *
86 * @param array $params
87 * input parameters
88 *
89 * @return array
90 */
91 function civicrm_api3_job_get($params) {
92 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
93 }
94
95 /**
96 * Delete a job.
97 *
98 * @param array $params
99 */
100 function civicrm_api3_job_delete($params) {
101 _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
102 }
103
104 /**
105 * Dumb wrapper to execute scheduled jobs.
106 *
107 * Always creates success - errors and results are handled in the job log.
108 *
109 * @param array $params
110 * input parameters (unused).
111 *
112 * @return array
113 * API Result Array
114 */
115 function civicrm_api3_job_execute($params) {
116
117 $facility = new CRM_Core_JobManager();
118 $facility->execute(FALSE);
119
120 // Always creates success - results are handled elsewhere.
121 return civicrm_api3_create_success(1, $params, 'Job');
122 }
123
124 /**
125 * Adjust Metadata for Execute action.
126 *
127 * @param array $params
128 * Array of parameters determined by getfields.
129 */
130 function _civicrm_api3_job_execute_spec(&$params) {
131 }
132
133 /**
134 * Geocode group of contacts based on given params.
135 *
136 * @param array $params
137 * input parameters.
138 *
139 * @return array
140 * API Result Array
141 */
142 function civicrm_api3_job_geocode($params) {
143 $gc = new CRM_Utils_Address_BatchUpdate($params);
144
145 $result = $gc->run();
146
147 if ($result['is_error'] == 0) {
148 return civicrm_api3_create_success($result['messages']);
149 }
150 else {
151 return civicrm_api3_create_error($result['messages']);
152 }
153 }
154
155 /**
156 * First check on Code documentation.
157 *
158 * @param array $params
159 */
160 function _civicrm_api3_job_geocode_spec(&$params) {
161 $params['start'] = [
162 'title' => 'Starting Contact ID',
163 'type' => CRM_Utils_Type::T_INT,
164 ];
165 $params['end'] = [
166 'title' => 'Ending Contact ID',
167 'type' => CRM_Utils_Type::T_INT,
168 ];
169 $params['geocoding'] = [
170 'title' => 'Geocode address?',
171 'type' => CRM_Utils_Type::T_BOOLEAN,
172 ];
173 $params['parse'] = [
174 'title' => 'Parse street address?',
175 'type' => CRM_Utils_Type::T_BOOLEAN,
176 ];
177 $params['throttle'] = [
178 'title' => 'Throttle?',
179 'description' => 'If enabled, geo-codes at a slow rate',
180 'type' => CRM_Utils_Type::T_BOOLEAN,
181 ];
182 }
183
184 /**
185 * Send the scheduled reminders as configured.
186 *
187 * @param array $params
188 * - now - the time to use, in YmdHis format
189 * - makes testing a bit simpler since we can simulate past/future time
190 *
191 * @return array
192 * @throws \API_Exception
193 * @throws \CRM_Core_Exception
194 * @throws \CiviCRM_API3_Exception
195 */
196 function civicrm_api3_job_send_reminder($params) {
197 //note that $params['rowCount' can be overridden by one of the preferred syntaxes ($options['limit'] = x
198 //It's not clear whether than syntax can be passed in via the UI config - but this keeps the pre 4.4.4 behaviour
199 // in that case (ie. makes it non-configurable via the UI). Another approach would be to set a default of 0
200 // in the _spec function - but since that is a deprecated value it seems more contentious than this approach
201 $params['rowCount'] = 0;
202 $lock = Civi::lockManager()->acquire('worker.core.ActionSchedule');
203 if (!$lock->isAcquired()) {
204 throw new API_Exception('Could not acquire lock, another ActionSchedule process is running');
205 }
206
207 CRM_Core_BAO_ActionSchedule::processQueue($params['now'] ?? NULL, $params);
208 $lock->release();
209 return civicrm_api3_create_success(1, $params, 'ActionSchedule', 'send_reminder');
210 }
211
212 /**
213 * Adjust metadata for "send_reminder" action.
214 *
215 * The metadata is used for setting defaults, documentation & validation.
216 *
217 * @param array $params
218 * Array of parameters determined by getfields.
219 */
220 function _civicrm_api3_job_send_reminder(&$params) {
221 //@todo this function will now take all fields in action_schedule as params
222 // as it is calling the api fn to set the filters - update getfields to reflect
223 $params['id'] = [
224 'type' => CRM_Utils_Type::T_INT,
225 'title' => 'Action Schedule ID',
226 ];
227 }
228
229 /**
230 * Execute a specific report instance and send the output via email.
231 *
232 * @param array $params
233 * (reference ) input parameters.
234 * sendmail - Boolean - should email be sent?, required
235 * instanceId - Integer - the report instance ID
236 * resetVal - Integer - should we reset form state (always true)?
237 *
238 * @return array
239 */
240 function civicrm_api3_job_mail_report($params) {
241 $result = CRM_Report_Utils_Report::processReport($params);
242
243 if ($result['is_error'] == 0) {
244 // this should be handling by throwing exceptions but can't remove until we can test that.
245 return civicrm_api3_create_success();
246 }
247 else {
248 return civicrm_api3_create_error($result['messages']);
249 }
250 }
251
252 /**
253 * This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
254 *
255 * IMPORTANT: You must first create valid option value before using via admin interface.
256 * Check option lists for Email Greetings, Postal Greetings and Addressee
257 *
258 * @todo - is this here by mistake or should it be added to _spec function :id - Integer - greetings option group.
259 *
260 * @param array $params
261 *
262 * @return array
263 */
264 function civicrm_api3_job_update_greeting($params) {
265 if (isset($params['ct']) && isset($params['gt'])) {
266 $ct = explode(',', $params['ct']);
267 $gt = explode(',', $params['gt']);
268 foreach ($ct as $ctKey => $ctValue) {
269 foreach ($gt as $gtKey => $gtValue) {
270 $params['ct'] = trim($ctValue);
271 $params['gt'] = trim($gtValue);
272 CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
273 }
274 }
275 }
276 else {
277 CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
278 }
279 return civicrm_api3_create_success();
280 }
281
282 /**
283 * Adjust Metadata for Get action.
284 *
285 * The metadata is used for setting defaults, documentation & validation.
286 *
287 * @param array $params
288 * Array of parameters determined by getfields.
289 */
290 function _civicrm_api3_job_update_greeting_spec(&$params) {
291 $params['ct'] = [
292 'api.required' => 1,
293 'title' => 'Contact Type',
294 'type' => CRM_Utils_Type::T_STRING,
295 ];
296 $params['gt'] = [
297 'api.required' => 1,
298 'title' => 'Greeting Type',
299 'type' => CRM_Utils_Type::T_STRING,
300 ];
301 }
302
303 /**
304 * Mass update pledge statuses.
305 *
306 * @param array $params
307 *
308 * @return array
309 */
310 function civicrm_api3_job_process_pledge($params) {
311 // *** Uncomment the next line if you want automated reminders to be sent
312 // $params['send_reminders'] = true;
313 $result = CRM_Pledge_BAO_Pledge::updatePledgeStatus($params);
314
315 if ($result['is_error'] == 0) {
316 // experiment: detailed execution log is a result here
317 return civicrm_api3_create_success($result['messages']);
318 }
319 else {
320 return civicrm_api3_create_error($result['error_message']);
321 }
322 }
323
324 /**
325 * Process mail queue.
326 *
327 * @param array $params
328 *
329 * @return array
330 */
331 function civicrm_api3_job_process_mailing($params) {
332 $mailsProcessedOrig = CRM_Mailing_BAO_MailingJob::$mailsProcessed;
333
334 try {
335 CRM_Core_BAO_Setting::isAPIJobAllowedToRun($params);
336 }
337 catch (Exception $e) {
338 return civicrm_api3_create_error($e->getMessage());
339 }
340
341 if (!CRM_Mailing_BAO_Mailing::processQueue()) {
342 return civicrm_api3_create_error('Process Queue failed');
343 }
344 else {
345 $values = [
346 'processed' => CRM_Mailing_BAO_MailingJob::$mailsProcessed - $mailsProcessedOrig,
347 ];
348 return civicrm_api3_create_success($values, $params, 'Job', 'process_mailing');
349 }
350 }
351
352 /**
353 * Process sms queue.
354 *
355 * @param array $params
356 *
357 * @return array
358 */
359 function civicrm_api3_job_process_sms($params) {
360 $mailsProcessedOrig = CRM_Mailing_BAO_MailingJob::$mailsProcessed;
361
362 if (!CRM_Mailing_BAO_Mailing::processQueue('sms')) {
363 return civicrm_api3_create_error('Process Queue failed');
364 }
365 else {
366 $values = [
367 'processed' => CRM_Mailing_BAO_MailingJob::$mailsProcessed - $mailsProcessedOrig,
368 ];
369 return civicrm_api3_create_success($values, $params, 'Job', 'process_sms');
370 }
371 }
372
373 /**
374 * Job to get mail responses from civiMailing.
375 *
376 * @param array $params
377 *
378 * @return array
379 */
380 function civicrm_api3_job_fetch_bounces($params) {
381 $lock = Civi::lockManager()->acquire('worker.mailing.EmailProcessor');
382 if (!$lock->isAcquired()) {
383 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
384 }
385 CRM_Utils_Mail_EmailProcessor::processBounces($params['is_create_activities']);
386 $lock->release();
387
388 return civicrm_api3_create_success(1, $params, 'Job', 'fetch_bounces');
389 }
390
391 /**
392 * Metadata for bounce function.
393 *
394 * @param array $params
395 */
396 function _civicrm_api3_job_fetch_bounces_spec(&$params) {
397 $params['is_create_activities'] = [
398 'api.default' => 0,
399 'type' => CRM_Utils_Type::T_BOOLEAN,
400 'title' => ts('Create activities for replies?'),
401 ];
402 }
403
404 /**
405 * Job to get mail and create activities.
406 *
407 * @param array $params
408 *
409 * @return array
410 */
411 function civicrm_api3_job_fetch_activities($params) {
412 $lock = Civi::lockManager()->acquire('worker.mailing.EmailProcessor');
413 if (!$lock->isAcquired()) {
414 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
415 }
416
417 try {
418 CRM_Utils_Mail_EmailProcessor::processActivities();
419 $values = [];
420 $lock->release();
421 return civicrm_api3_create_success($values, $params, 'Job', 'fetch_activities');
422 }
423 catch (Exception $e) {
424 $lock->release();
425 return civicrm_api3_create_error($e->getMessage());
426 }
427 }
428
429 /**
430 * Process participant statuses.
431 *
432 * @param array $params
433 * Input parameters.
434 *
435 * @return array
436 * array of properties, if error an array with an error id and error message
437 */
438 function civicrm_api3_job_process_participant($params) {
439 $result = CRM_Event_BAO_ParticipantStatusType::process($params);
440
441 if (!$result['is_error']) {
442 return civicrm_api3_create_success(implode("\r\r", $result['messages']));
443 }
444 else {
445 return civicrm_api3_create_error('Error while processing participant statuses');
446 }
447 }
448
449 /**
450 * This api checks and updates the status of all membership records for a given domain.
451 *
452 * The function uses the calc_membership_status and update_contact_membership APIs.
453 *
454 * IMPORTANT:
455 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
456 *
457 * @param array $params
458 * Input parameters NOT USED.
459 *
460 * @return bool
461 * true if success, else false
462 */
463 function civicrm_api3_job_process_membership($params) {
464 $lock = Civi::lockManager()->acquire('worker.member.UpdateMembership');
465 if (!$lock->isAcquired()) {
466 return civicrm_api3_create_error('Could not acquire lock, another Membership Processing process is running');
467 }
468
469 $result = CRM_Member_BAO_Membership::updateAllMembershipStatus();
470 $lock->release();
471
472 if ($result['is_error'] == 0) {
473 return civicrm_api3_create_success($result['messages'], $params, 'Job', 'process_membership');
474 }
475 else {
476 return civicrm_api3_create_error($result['messages']);
477 }
478 }
479
480 /**
481 * This api checks and updates the status of all survey respondents.
482 *
483 * @param array $params
484 * (reference ) input parameters.
485 *
486 * @return bool
487 * true if success, else false
488 */
489 function civicrm_api3_job_process_respondent($params) {
490 $result = CRM_Campaign_BAO_Survey::releaseRespondent($params);
491
492 if ($result['is_error'] == 0) {
493 return civicrm_api3_create_success();
494 }
495 else {
496 return civicrm_api3_create_error($result['messages']);
497 }
498 }
499
500 /**
501 * Merges given pair of duplicate contacts.
502 *
503 * @param array $params
504 * Input parameters.
505 *
506 * @return array
507 * API Result Array
508 * @throws \CiviCRM_API3_Exception
509 */
510 function civicrm_api3_job_process_batch_merge($params) {
511 $rule_group_id = $params['rule_group_id'] ?? NULL;
512 if (!$rule_group_id) {
513 $rule_group_id = civicrm_api3('RuleGroup', 'getvalue', [
514 'contact_type' => 'Individual',
515 'used' => 'Unsupervised',
516 'return' => 'id',
517 'options' => ['limit' => 1],
518 ]);
519 }
520 $rgid = $params['rgid'] ?? NULL;
521 $gid = $params['gid'] ?? NULL;
522 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
523
524 $result = CRM_Dedupe_Merger::batchMerge($rule_group_id, $gid, $mode, 1, 2, CRM_Utils_Array::value('criteria', $params, []), CRM_Utils_Array::value('check_permissions', $params), NULL, $params['search_limit']);
525
526 return civicrm_api3_create_success($result, $params);
527 }
528
529 /**
530 * Metadata for batch merge function.
531 *
532 * @param $params
533 */
534 function _civicrm_api3_job_process_batch_merge_spec(&$params) {
535 $params['rule_group_id'] = [
536 'title' => 'Dedupe rule group id, defaults to Contact Unsupervised rule',
537 'type' => CRM_Utils_Type::T_INT,
538 'api.aliases' => ['rgid'],
539 ];
540 $params['gid'] = [
541 'title' => 'group id',
542 'type' => CRM_Utils_Type::T_INT,
543 ];
544 $params['mode'] = [
545 'title' => 'Mode',
546 'description' => 'helps decide how to behave when there are conflicts. A \'safe\' value skips the merge if there are no conflicts. Does a force merge otherwise.',
547 'type' => CRM_Utils_Type::T_STRING,
548 ];
549 $params['auto_flip'] = [
550 'title' => 'Auto Flip',
551 'description' => 'let the api decide which contact to retain and which to delete?',
552 'type' => CRM_Utils_Type::T_BOOLEAN,
553 ];
554 $params['search_limit'] = [
555 'title' => ts('Number of contacts to look for matches for.'),
556 'type' => CRM_Utils_Type::T_INT,
557 'api.default' => (int) Civi::settings()->get('dedupe_default_limit'),
558 ];
559
560 }
561
562 /**
563 * Runs handlePaymentCron method in the specified payment processor.
564 *
565 * @param array $params
566 * Input parameters.
567 *
568 * Expected @params array keys are: INCORRECTLY DOCUMENTED AND SHOULD BE IN THE _spec function
569 * for retrieval via getfields.
570 * {string 'processor_name' - the name of the payment processor, eg: Sagepay}
571 */
572 function civicrm_api3_job_run_payment_cron($params) {
573
574 // live mode
575 CRM_Core_Payment::handlePaymentMethod(
576 'PaymentCron',
577 array_merge(
578 $params,
579 [
580 'caller' => 'api',
581 ]
582 )
583 );
584
585 // test mode
586 CRM_Core_Payment::handlePaymentMethod(
587 'PaymentCron',
588 array_merge(
589 $params,
590 [
591 'mode' => 'test',
592 ]
593 )
594 );
595 }
596
597 /**
598 * This api cleans up all the old session entries and temp tables.
599 *
600 * We recommend that sites run this on an hourly basis.
601 *
602 * @param array $params
603 * Sends in various config parameters to decide what needs to be cleaned.
604 */
605 function civicrm_api3_job_cleanup($params) {
606 $session = CRM_Utils_Array::value('session', $params, TRUE);
607 $tempTable = CRM_Utils_Array::value('tempTables', $params, TRUE);
608 $jobLog = CRM_Utils_Array::value('jobLog', $params, TRUE);
609 $expired = CRM_Utils_Array::value('expiredDbCache', $params, TRUE);
610 $prevNext = CRM_Utils_Array::value('prevNext', $params, TRUE);
611 $dbCache = CRM_Utils_Array::value('dbCache', $params, FALSE);
612 $memCache = CRM_Utils_Array::value('memCache', $params, FALSE);
613 $tplCache = CRM_Utils_Array::value('tplCache', $params, FALSE);
614 $wordRplc = CRM_Utils_Array::value('wordRplc', $params, FALSE);
615
616 if ($session || $tempTable || $prevNext || $expired) {
617 CRM_Core_BAO_Cache::cleanup($session, $tempTable, $prevNext, $expired);
618 }
619
620 if ($jobLog) {
621 CRM_Core_BAO_Job::cleanup();
622 }
623
624 if ($tplCache) {
625 $config = CRM_Core_Config::singleton();
626 $config->cleanup(1, FALSE);
627 }
628
629 if ($dbCache) {
630 CRM_Core_Config::clearDBCache();
631 }
632
633 if ($memCache) {
634 CRM_Utils_System::flushCache();
635 }
636
637 if ($wordRplc) {
638 CRM_Core_BAO_WordReplacement::rebuild();
639 }
640 }
641
642 /**
643 * Set expired relationships to disabled.
644 *
645 * @param array $params
646 *
647 * @return array
648 * @throws \API_Exception
649 */
650 function civicrm_api3_job_disable_expired_relationships($params) {
651 $result = CRM_Contact_BAO_Relationship::disableExpiredRelationships();
652 if (!$result) {
653 throw new API_Exception('Failed to disable all expired relationships.');
654 }
655 return civicrm_api3_create_success(1, $params, 'Job', 'disable_expired_relationships');
656 }
657
658 /**
659 * This api reloads all the smart groups.
660 *
661 * If the org has a large number of smart groups it is recommended that they use the limit clause
662 * to limit the number of smart groups evaluated on a per job basis.
663 *
664 * Might also help to increase the smartGroupCacheTimeout and use the cache.
665 *
666 * @param array $params
667 *
668 * @return array
669 * @throws \API_Exception
670 */
671 function civicrm_api3_job_group_rebuild($params) {
672 $lock = Civi::lockManager()->acquire('worker.core.GroupRebuild');
673 if (!$lock->isAcquired()) {
674 throw new API_Exception('Could not acquire lock, another GroupRebuild process is running');
675 }
676
677 $limit = $params['limit'] ?? 0;
678
679 CRM_Contact_BAO_GroupContactCache::loadAll(NULL, $limit);
680 $lock->release();
681
682 return civicrm_api3_create_success();
683 }
684
685 /**
686 * Flush smart groups caches.
687 *
688 * This job purges aged smart group cache data (based on the timeout value). Sites can decide whether they want this
689 * job and / or the group cache rebuild job to run. In some cases performance is better when old caches are cleared out
690 * prior to any attempt to rebuild them. Also, many sites are very happy to have caches built on demand, provided the
691 * user is not having to wait for deadlocks to clear when invalidating them.
692 *
693 * @param array $params
694 *
695 * @return array
696 * @throws \API_Exception
697 */
698 function civicrm_api3_job_group_cache_flush($params) {
699 CRM_Contact_BAO_GroupContactCache::deterministicCacheFlush();
700 return civicrm_api3_create_success();
701 }
702
703 /**
704 * Check for CiviCRM software updates.
705 *
706 * Anonymous site statistics are sent back to civicrm.org during this check.
707 */
708 function civicrm_api3_job_version_check() {
709 $vc = new CRM_Utils_VersionCheck();
710 $vc->fetch();
711 return civicrm_api3_create_success();
712 }