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