3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * This api is used for working with scheduled "cron" jobs.
31 * @package CiviCRM_APIv3
35 * Adjust metadata for "Create" action.
37 * The metadata is used for setting defaults, documentation & validation.
39 * @param array $params
40 * Array of parameters determined by getfields.
42 function _civicrm_api3_job_create_spec(&$params) {
43 $params['run_frequency']['api.required'] = 1;
44 $params['name']['api.required'] = 1;
45 $params['api_entity']['api.required'] = 1;
46 $params['api_action']['api.required'] = 1;
48 $params['domain_id']['api.default'] = CRM_Core_Config
::domainID();
49 $params['is_active']['api.default'] = 1;
53 * Create scheduled job.
55 * @param array $params
56 * Associative array of property name/value pairs to insert in new job.
60 function civicrm_api3_job_create($params) {
61 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params, 'Job');
65 * Adjust metadata for clone spec action.
69 function _civicrm_api3_job_clone_spec(&$spec) {
70 $spec['id']['title'] = 'Job ID to clone';
71 $spec['id']['type'] = CRM_Utils_Type
::T_INT
;
72 $spec['id']['api.required'] = 1;
73 $spec['is_active']['title'] = 'Job is Active?';
74 $spec['is_active']['type'] = CRM_Utils_Type
::T_BOOLEAN
;
75 $spec['is_active']['api.required'] = 0;
81 * @param array $params
84 * @throws \API_Exception
85 * @throws \CiviCRM_API3_Exception
87 function civicrm_api3_job_clone($params) {
88 if (empty($params['id'])) {
89 throw new API_Exception("Mandatory key(s) missing from params array: id field is required");
93 $params['last_run'] = 'null';
94 $params['scheduled_run_date'] = 'null';
95 $newJobDAO = CRM_Core_BAO_Job
::copy($id, $params);
96 return civicrm_api3('Job', 'get', ['id' => $newJobDAO->id
]);
100 * Retrieve one or more job.
102 * @param array $params
107 function civicrm_api3_job_get($params) {
108 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__
), $params);
114 * @param array $params
116 function civicrm_api3_job_delete($params) {
117 _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__
), $params);
121 * Dumb wrapper to execute scheduled jobs.
123 * Always creates success - errors and results are handled in the job log.
125 * @param array $params
126 * input parameters (unused).
131 function civicrm_api3_job_execute($params) {
133 $facility = new CRM_Core_JobManager();
134 $facility->execute(FALSE);
136 // Always creates success - results are handled elsewhere.
137 return civicrm_api3_create_success(1, $params, 'Job');
141 * Adjust Metadata for Execute action.
143 * @param array $params
144 * Array of parameters determined by getfields.
146 function _civicrm_api3_job_execute_spec(&$params) {
150 * Geocode group of contacts based on given params.
152 * @param array $params
158 function civicrm_api3_job_geocode($params) {
159 $gc = new CRM_Utils_Address_BatchUpdate($params);
161 $result = $gc->run();
163 if ($result['is_error'] == 0) {
164 return civicrm_api3_create_success($result['messages']);
167 return civicrm_api3_create_error($result['messages']);
172 * First check on Code documentation.
174 * @param array $params
176 function _civicrm_api3_job_geocode_spec(&$params) {
178 'title' => 'Starting Contact ID',
179 'type' => CRM_Utils_Type
::T_INT
,
182 'title' => 'Ending Contact ID',
183 'type' => CRM_Utils_Type
::T_INT
,
185 $params['geocoding'] = [
186 'title' => 'Geocode address?',
187 'type' => CRM_Utils_Type
::T_BOOLEAN
,
190 'title' => 'Parse street address?',
191 'type' => CRM_Utils_Type
::T_BOOLEAN
,
193 $params['throttle'] = [
194 'title' => 'Throttle?',
195 'description' => 'If enabled, geo-codes at a slow rate',
196 'type' => CRM_Utils_Type
::T_BOOLEAN
,
201 * Send the scheduled reminders for all contacts (either for activities or events).
203 * @param array $params
204 * (reference ) input parameters.
205 * now - the time to use, in YmdHis format
206 * - makes testing a bit simpler since we can simulate past/future time
210 function civicrm_api3_job_send_reminder($params) {
211 //note that $params['rowCount' can be overridden by one of the preferred syntaxes ($options['limit'] = x
212 //It's not clear whether than syntax can be passed in via the UI config - but this keeps the pre 4.4.4 behaviour
213 // in that case (ie. makes it non-configurable via the UI). Another approach would be to set a default of 0
214 // in the _spec function - but since that is a deprecated value it seems more contentious than this approach
215 $params['rowCount'] = 0;
216 $lock = Civi
::lockManager()->acquire('worker.core.ActionSchedule');
217 if (!$lock->isAcquired()) {
218 return civicrm_api3_create_error('Could not acquire lock, another ActionSchedule process is running');
221 $result = CRM_Core_BAO_ActionSchedule
::processQueue(CRM_Utils_Array
::value('now', $params), $params);
224 if ($result['is_error'] == 0) {
225 return civicrm_api3_create_success();
228 return civicrm_api3_create_error($result['messages']);
233 * Adjust metadata for "send_reminder" action.
235 * The metadata is used for setting defaults, documentation & validation.
237 * @param array $params
238 * Array of parameters determined by getfields.
240 function _civicrm_api3_job_send_reminder(&$params) {
241 //@todo this function will now take all fields in action_schedule as params
242 // as it is calling the api fn to set the filters - update getfields to reflect
244 'type' => CRM_Utils_Type
::T_INT
,
245 'title' => 'Action Schedule ID',
250 * Execute a specific report instance and send the output via email.
252 * @param array $params
253 * (reference ) input parameters.
254 * sendmail - Boolean - should email be sent?, required
255 * instanceId - Integer - the report instance ID
256 * resetVal - Integer - should we reset form state (always true)?
260 function civicrm_api3_job_mail_report($params) {
261 $result = CRM_Report_Utils_Report
::processReport($params);
263 if ($result['is_error'] == 0) {
264 // this should be handling by throwing exceptions but can't remove until we can test that.
265 return civicrm_api3_create_success();
268 return civicrm_api3_create_error($result['messages']);
273 * This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
275 * IMPORTANT: You must first create valid option value before using via admin interface.
276 * Check option lists for Email Greetings, Postal Greetings and Addressee
278 * @todo - is this here by mistake or should it be added to _spec function :id - Integer - greetings option group.
280 * @param array $params
284 function civicrm_api3_job_update_greeting($params) {
285 if (isset($params['ct']) && isset($params['gt'])) {
286 $ct = explode(',', $params['ct']);
287 $gt = explode(',', $params['gt']);
288 foreach ($ct as $ctKey => $ctValue) {
289 foreach ($gt as $gtKey => $gtValue) {
290 $params['ct'] = trim($ctValue);
291 $params['gt'] = trim($gtValue);
292 CRM_Contact_BAO_Contact_Utils
::updateGreeting($params);
297 CRM_Contact_BAO_Contact_Utils
::updateGreeting($params);
299 return civicrm_api3_create_success();
303 * Adjust Metadata for Get action.
305 * The metadata is used for setting defaults, documentation & validation.
307 * @param array $params
308 * Array of parameters determined by getfields.
310 function _civicrm_api3_job_update_greeting_spec(&$params) {
313 'title' => 'Contact Type',
314 'type' => CRM_Utils_Type
::T_STRING
,
318 'title' => 'Greeting Type',
319 'type' => CRM_Utils_Type
::T_STRING
,
324 * Mass update pledge statuses.
326 * @param array $params
330 function civicrm_api3_job_process_pledge($params) {
331 // *** Uncomment the next line if you want automated reminders to be sent
332 // $params['send_reminders'] = true;
333 $result = CRM_Pledge_BAO_Pledge
::updatePledgeStatus($params);
335 if ($result['is_error'] == 0) {
336 // experiment: detailed execution log is a result here
337 return civicrm_api3_create_success($result['messages']);
340 return civicrm_api3_create_error($result['error_message']);
345 * Process mail queue.
347 * @param array $params
351 function civicrm_api3_job_process_mailing($params) {
352 $mailsProcessedOrig = CRM_Mailing_BAO_MailingJob
::$mailsProcessed;
355 CRM_Core_BAO_Setting
::isAPIJobAllowedToRun($params);
357 catch (Exception
$e) {
358 return civicrm_api3_create_error($e->getMessage());
361 if (!CRM_Mailing_BAO_Mailing
::processQueue()) {
362 return civicrm_api3_create_error('Process Queue failed');
366 'processed' => CRM_Mailing_BAO_MailingJob
::$mailsProcessed - $mailsProcessedOrig,
368 return civicrm_api3_create_success($values, $params, 'Job', 'process_mailing');
375 * @param array $params
379 function civicrm_api3_job_process_sms($params) {
380 $mailsProcessedOrig = CRM_Mailing_BAO_MailingJob
::$mailsProcessed;
382 if (!CRM_Mailing_BAO_Mailing
::processQueue('sms')) {
383 return civicrm_api3_create_error('Process Queue failed');
387 'processed' => CRM_Mailing_BAO_MailingJob
::$mailsProcessed - $mailsProcessedOrig,
389 return civicrm_api3_create_success($values, $params, 'Job', 'process_sms');
394 * Job to get mail responses from civiMailing.
396 * @param array $params
400 function civicrm_api3_job_fetch_bounces($params) {
401 $lock = Civi
::lockManager()->acquire('worker.mailing.EmailProcessor');
402 if (!$lock->isAcquired()) {
403 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
405 CRM_Utils_Mail_EmailProcessor
::processBounces($params['is_create_activities']);
408 return civicrm_api3_create_success(1, $params, 'Job', 'fetch_bounces');
412 * Metadata for bounce function.
414 * @param array $params
416 function _civicrm_api3_job_fetch_bounces_spec(&$params) {
417 $params['is_create_activities'] = [
419 'type' => CRM_Utils_Type
::T_BOOLEAN
,
420 'title' => ts('Create activities for replies?'),
425 * Job to get mail and create activities.
427 * @param array $params
431 function civicrm_api3_job_fetch_activities($params) {
432 $lock = Civi
::lockManager()->acquire('worker.mailing.EmailProcessor');
433 if (!$lock->isAcquired()) {
434 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
438 CRM_Utils_Mail_EmailProcessor
::processActivities();
441 return civicrm_api3_create_success($values, $params, 'Job', 'fetch_activities');
443 catch (Exception
$e) {
445 return civicrm_api3_create_error($e->getMessage());
450 * Process participant statuses.
452 * @param array $params
456 * array of properties, if error an array with an error id and error message
458 function civicrm_api3_job_process_participant($params) {
459 $result = CRM_Event_BAO_ParticipantStatusType
::process($params);
461 if (!$result['is_error']) {
462 return civicrm_api3_create_success(implode("\r\r", $result['messages']));
465 return civicrm_api3_create_error('Error while processing participant statuses');
470 * This api checks and updates the status of all membership records for a given domain.
472 * The function uses the calc_membership_status and update_contact_membership APIs.
475 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
477 * @param array $params
478 * Input parameters NOT USED.
481 * true if success, else false
483 function civicrm_api3_job_process_membership($params) {
484 $lock = Civi
::lockManager()->acquire('worker.member.UpdateMembership');
485 if (!$lock->isAcquired()) {
486 return civicrm_api3_create_error('Could not acquire lock, another Membership Processing process is running');
489 $result = CRM_Member_BAO_Membership
::updateAllMembershipStatus();
492 if ($result['is_error'] == 0) {
493 return civicrm_api3_create_success($result['messages'], $params, 'Job', 'process_membership');
496 return civicrm_api3_create_error($result['messages']);
501 * This api checks and updates the status of all survey respondents.
503 * @param array $params
504 * (reference ) input parameters.
507 * true if success, else false
509 function civicrm_api3_job_process_respondent($params) {
510 $result = CRM_Campaign_BAO_Survey
::releaseRespondent($params);
512 if ($result['is_error'] == 0) {
513 return civicrm_api3_create_success();
516 return civicrm_api3_create_error($result['messages']);
521 * Merges given pair of duplicate contacts.
523 * @param array $params
528 * @throws \CiviCRM_API3_Exception
530 function civicrm_api3_job_process_batch_merge($params) {
531 $rule_group_id = CRM_Utils_Array
::value('rule_group_id', $params);
532 if (!$rule_group_id) {
533 $rule_group_id = civicrm_api3('RuleGroup', 'getvalue', [
534 'contact_type' => 'Individual',
535 'used' => 'Unsupervised',
537 'options' => ['limit' => 1],
540 $rgid = CRM_Utils_Array
::value('rgid', $params);
541 $gid = CRM_Utils_Array
::value('gid', $params);
542 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
544 $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']);
546 return civicrm_api3_create_success($result, $params);
550 * Metadata for batch merge function.
554 function _civicrm_api3_job_process_batch_merge_spec(&$params) {
555 $params['rule_group_id'] = [
556 'title' => 'Dedupe rule group id, defaults to Contact Unsupervised rule',
557 'type' => CRM_Utils_Type
::T_INT
,
558 'api.aliases' => ['rgid'],
561 'title' => 'group id',
562 'type' => CRM_Utils_Type
::T_INT
,
566 '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.',
567 'type' => CRM_Utils_Type
::T_STRING
,
569 $params['auto_flip'] = [
570 'title' => 'Auto Flip',
571 'description' => 'let the api decide which contact to retain and which to delete?',
572 'type' => CRM_Utils_Type
::T_BOOLEAN
,
574 $params['search_limit'] = [
575 'title' => ts('Number of contacts to look for matches for.'),
576 'type' => CRM_Utils_Type
::T_INT
,
577 'api.default' => (int) Civi
::settings()->get('dedupe_default_limit'),
583 * Runs handlePaymentCron method in the specified payment processor.
585 * @param array $params
588 * Expected @params array keys are: INCORRECTLY DOCUMENTED AND SHOULD BE IN THE _spec function
589 * for retrieval via getfields.
590 * {string 'processor_name' - the name of the payment processor, eg: Sagepay}
592 function civicrm_api3_job_run_payment_cron($params) {
595 CRM_Core_Payment
::handlePaymentMethod(
606 CRM_Core_Payment
::handlePaymentMethod(
618 * This api cleans up all the old session entries and temp tables.
620 * We recommend that sites run this on an hourly basis.
622 * @param array $params
623 * Sends in various config parameters to decide what needs to be cleaned.
625 function civicrm_api3_job_cleanup($params) {
626 $session = CRM_Utils_Array
::value('session', $params, TRUE);
627 $tempTable = CRM_Utils_Array
::value('tempTables', $params, TRUE);
628 $jobLog = CRM_Utils_Array
::value('jobLog', $params, TRUE);
629 $expired = CRM_Utils_Array
::value('expiredDbCache', $params, TRUE);
630 $prevNext = CRM_Utils_Array
::value('prevNext', $params, TRUE);
631 $dbCache = CRM_Utils_Array
::value('dbCache', $params, FALSE);
632 $memCache = CRM_Utils_Array
::value('memCache', $params, FALSE);
633 $tplCache = CRM_Utils_Array
::value('tplCache', $params, FALSE);
634 $wordRplc = CRM_Utils_Array
::value('wordRplc', $params, FALSE);
636 if ($session ||
$tempTable ||
$prevNext ||
$expired) {
637 CRM_Core_BAO_Cache
::cleanup($session, $tempTable, $prevNext, $expired);
641 CRM_Core_BAO_Job
::cleanup();
645 $config = CRM_Core_Config
::singleton();
646 $config->cleanup(1, FALSE);
650 CRM_Core_Config
::clearDBCache();
654 CRM_Utils_System
::flushCache();
658 CRM_Core_BAO_WordReplacement
::rebuild();
663 * Set expired relationships to disabled.
665 * @param array $params
668 * @throws \API_Exception
670 function civicrm_api3_job_disable_expired_relationships($params) {
671 $result = CRM_Contact_BAO_Relationship
::disableExpiredRelationships();
673 throw new API_Exception('Failed to disable all expired relationships.');
675 return civicrm_api3_create_success(1, $params, 'Job', 'disable_expired_relationships');
679 * This api reloads all the smart groups.
681 * If the org has a large number of smart groups it is recommended that they use the limit clause
682 * to limit the number of smart groups evaluated on a per job basis.
684 * Might also help to increase the smartGroupCacheTimeout and use the cache.
686 * @param array $params
689 * @throws \API_Exception
691 function civicrm_api3_job_group_rebuild($params) {
692 $lock = Civi
::lockManager()->acquire('worker.core.GroupRebuild');
693 if (!$lock->isAcquired()) {
694 throw new API_Exception('Could not acquire lock, another GroupRebuild process is running');
697 $limit = CRM_Utils_Array
::value('limit', $params, 0);
699 CRM_Contact_BAO_GroupContactCache
::loadAll(NULL, $limit);
702 return civicrm_api3_create_success();
706 * Flush smart groups caches.
708 * This job purges aged smart group cache data (based on the timeout value). Sites can decide whether they want this
709 * job and / or the group cache rebuild job to run. In some cases performance is better when old caches are cleared out
710 * prior to any attempt to rebuild them. Also, many sites are very happy to have caches built on demand, provided the
711 * user is not having to wait for deadlocks to clear when invalidating them.
713 * @param array $params
716 * @throws \API_Exception
718 function civicrm_api3_job_group_cache_flush($params) {
719 CRM_Contact_BAO_GroupContactCache
::deterministicCacheFlush();
720 return civicrm_api3_create_success();
724 * Check for CiviCRM software updates.
726 * Anonymous site statistics are sent back to civicrm.org during this check.
728 function civicrm_api3_job_version_check() {
729 $vc = new CRM_Utils_VersionCheck();
731 return civicrm_api3_create_success();