CRM-13072 standardise note BAO & API
[civicrm-core.git] / api / v3 / Job.php
CommitLineData
6a488035
TO
1<?php
2// $Id$
3
4/*
5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
11 | |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
20 | |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
28*/
29
30/**
31 * new version of civicrm apis. See blog post at
32 * http://civicrm.org/node/131
33 * @todo Write sth
34 *
35 * @package CiviCRM_APIv3
36 * @subpackage API_Job
37 * @copyright CiviCRM LLC (c) 2004-2013
38 * $Id: Contact.php 30879 2010-11-22 15:45:55Z shot $
39 *
40 */
41
42/**
43 * Include common API util functions
44 */
45require_once 'api/v3/utils.php';
46
47/**
48 * Adjust metadata for "Create" action
49 *
50 * The metadata is used for setting defaults, documentation & validation
51 * @param array $params array or parameters determined by getfields
52 */
53function _civicrm_api3_job_create_spec(&$params) {
54 $params['run_frequency']['api.required'] = 1;
55 $params['name']['api.required'] = 1;
56 $params['api_entity']['api.required'] = 1;
57 $params['api_action']['api.required'] = 1;
58
59 $params['domain_id']['api.default'] = CRM_Core_Config::domainID();
60 $params['is_active']['api.default'] = 1;
61}
62
63/**
64 * Function to create scheduled job
65 *
66 * @param array $params Associative array of property name/value pairs to insert in new job.
67 *
68 * @return success or error
69 * {@getfields Job_create}
70 * @access public
71 * {@schema Core/Job.xml}
72 */
73function civicrm_api3_job_create($params) {
6a488035
TO
74 if (isset($params['id']) && !CRM_Utils_Rule::integer($params['id'])) {
75 return civicrm_api3_create_error('Invalid value for job ID');
76 }
77
78 $dao = CRM_Core_BAO_Job::create($params);
79
80 $result = array();
81 _civicrm_api3_object_to_array($dao, $result[$dao->id]);
82 return civicrm_api3_create_success($result, $params, 'job', 'create', $dao);
83}
84
85/**
86 * Retrieve one or more job
87 * @param array input parameters
88 * @return array api result array
89 * {@getfields email_get}
90 * @access public
91 */
92function civicrm_api3_job_get($params) {
93 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
94}
95
96/**
97 * Delete a job
98 *
99 * @param int $id
100 *
101 * @return array API Result Array
102 * {@getfields Job_delete}
103 * @static void
104 * @access public
105 */
106function civicrm_api3_job_delete($params) {
6a488035
TO
107 if ($params['id'] != NULL && !CRM_Utils_Rule::integer($params['id'])) {
108 return civicrm_api3_create_error('Invalid value for job ID');
109 }
110
111 $result = CRM_Core_BAO_Job::del($params['id']);
112 if (!$result) {
113 return civicrm_api3_create_error('Could not delete job');
114 }
115 return civicrm_api3_create_success($result, $params, 'job', 'delete');
116}
117
118/**
119 * Dumb wrapper to execute scheduled jobs. Always creates success - errors
120 * and results are handled in the job log.
121 *
122 * @param array $params (reference ) input parameters
123 *
124 * @return array API Result Array
125 *
126 * @static void
127 * @access public
128 *
129 */
130function civicrm_api3_job_execute($params) {
6a488035
TO
131 $facility = new CRM_Core_JobManager();
132 $facility->execute(FALSE);
133
134 // always creates success - results are handled elsewhere
135 return civicrm_api3_create_success();
136}
137
138/**
139 * Adjust Metadata for Execute action
140 *
141 * @param array $params array or parameters determined by getfields
142 */
143function _civicrm_api3_job_execute_spec(&$params) {
144}
145
146/**
147 * Geocode group of contacts based on given params
148 *
149 * @param array $params (reference ) input parameters
150 *
151 * @return array API Result Array
152 * {@getfields contact_geocode}
153 *
154 * @static void
155 * @access public
156 *
157 *
158 */
159function civicrm_api3_job_geocode($params) {
6a488035
TO
160 $gc = new CRM_Utils_Address_BatchUpdate($params);
161
162
163 $result = $gc->run();
164
165 if ($result['is_error'] == 0) {
166 return civicrm_api3_create_success($result['messages']);
167 }
168 else {
169 return civicrm_api3_create_error($result['messages']);
170 }
171}
172/**
173 * First check on Code documentation
174 */
175function _civicrm_api3_job_geocode_spec(&$params) {
176 $params['start'] = array('title' => 'Start Date');
177 $params['end'] = array('title' => 'End Date');
178 $params['geocoding'] = array('title' => 'Is this for GeoCoding? (I think this is a 1,0 field?)');
179 $params['parse'] = array('title' => 'Is this for parsing? (I think this is a 1,0 field?)');
180 $params['throttle'] = array('title' => 'Throttle? (no idea what you enter in this field)');
181}
182
183/**
184 * Send the scheduled reminders for all contacts (either for activities or events)
185 *
186 * @param array $params (reference ) input parameters
187 * now - the time to use, in YmdHis format
188 * - makes testing a bit simpler since we can simulate past/future time
189 *
190 * @return boolean true if success, else false
191 * @static void
192 * @access public
193 *
194 */
195function civicrm_api3_job_send_reminder($params) {
39fefc30
KJ
196 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
197 if (!$lock->isAcquired()) {
198 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
199 }
200
6a488035 201 $result = CRM_Core_BAO_ActionSchedule::processQueue(CRM_Utils_Array::value('now', $params));
39fefc30 202 $lock->release();
6a488035
TO
203
204 if ($result['is_error'] == 0) {
205 return civicrm_api3_create_success();
206 }
207 else {
208 return civicrm_api3_create_error($result['messages']);
209 }
210}
211
212/**
213 * Execute a specific report instance and send the output via email
214 *
215 * @param array $params (reference ) input parameters
216 * sendmail - Boolean - should email be sent?, required
217 * instanceId - Integer - the report instance ID
218 * resetVal - Integer - should we reset form state (always true)?
219 *
220 * @return boolean true if success, else false
221 * @static void
222 * @access public
223 *
224 */
225function civicrm_api3_job_mail_report($params) {
6a488035
TO
226 $result = CRM_Report_Utils_Report::processReport($params);
227
228 if ($result['is_error'] == 0) {
229 // this should be handling by throwing exceptions but can't remove until we can test that.
230 return civicrm_api3_create_success();
231 }
232 else {
233 return civicrm_api3_create_error($result['messages']);
234 }
235}
236
237/**
238 *
239 * This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
240 * IMPORTANT: You must first create valid option value before using via admin interface.
241 * Check option lists for Email Greetings, Postal Greetings and Addressee
242 *
243 * id - Integer - greetings option group
244 *
245 * @return boolean true if success, else false
246 * @static
247 * @access public
248 *
249 */
250function civicrm_api3_job_update_greeting($params) {
251
252 if (isset($params['ct']) && isset($params['gt'])) {
253 $ct = $gt = array();
254 $ct = explode(',', $params['ct']);
255 $gt = explode(',', $params['gt']);
256 foreach ($ct as $ctKey => $ctValue) {
257 foreach ($gt as $gtKey => $gtValue) {
258 $params['ct'] = trim($ctValue);
259 $params['gt'] = trim($gtValue);
260 $result[] = CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
261 }
262 }
263 }
264 else {
265 $result = CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
266 }
267
268 foreach ($result as $resultKey => $resultValue) {
269 if ($resultValue['is_error'] == 0) {
270 //really we should rely on the exception mechanism here - but we need to test that before removing this line
271 return civicrm_api3_create_success();
272 }
273 else {
274 return civicrm_api3_create_error($resultValue['messages']);
275 }
276 }
277}
278
279/**
280 * Adjust Metadata for Get action
281*
282* The metadata is used for setting defaults, documentation & validation
283* @param array $params array or parameters determined by getfields
284*/
285function _civicrm_api3_job_update_greeting_spec(&$params) {
286 $params['ct'] = array(
287 'api.required' => 1,
288 'title' => 'Contact Type',
289 'type' => CRM_Utils_Type::T_STRING,
290 );
291 $params['gt'] = array(
292 'api.required' => 1,
293 'title' => 'Greeting Type',
294 'type' => CRM_Utils_Type::T_STRING,
295 );
296}
297
298/**
299 * Mass update pledge statuses
300 *
301 * @param array $params (reference ) input parameters
302 *
303 * @return boolean true if success, else false
304 * @static
305 * @access public
306 *
307 */
308function civicrm_api3_job_process_pledge($params) {
309 // *** Uncomment the next line if you want automated reminders to be sent
310 // $params['send_reminders'] = true;
311 $result = CRM_Pledge_BAO_Pledge::updatePledgeStatus($params);
312
313 if ($result['is_error'] == 0) {
314 // experiment: detailed execution log is a result here
315 return civicrm_api3_create_success($result['messages']);
316 }
317 else {
318 return civicrm_api3_create_error($result['error_message']);
319 }
320}
321
322/**
323 * Process mail queue
324 *
325 * @param array $params
326 *
327 * @return array
328 */
329function civicrm_api3_job_process_mailing($params) {
330
331 if (!CRM_Mailing_BAO_Mailing::processQueue()) {
332 return civicrm_api3_create_error('Process Queue failed');
333 }
334 else {
335 $values = array();
336 return civicrm_api3_create_success($values, $params, 'mailing', 'process');
337 }
338}
339
340/**
341 * Process sms queue
342 *
343 * @param array $params
344 *
345 * @return array
346 */
347function civicrm_api3_job_process_sms($params) {
6a488035
TO
348 if (!CRM_Mailing_BAO_Mailing::processQueue('sms')) {
349 return civicrm_api3_create_error('Process Queue failed');
350 }
351 else {
352 $values = array();
353 return civicrm_api3_create_success($values, $params, 'mailing', 'process');
354 }
355}
39fefc30 356
6a488035
TO
357/**
358 * Job to get mail responses from civimailing
359 */
360function civicrm_api3_job_fetch_bounces($params) {
39fefc30 361 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
6a488035
TO
362 if (!$lock->isAcquired()) {
363 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
364 }
365 if (!CRM_Utils_Mail_EmailProcessor::processBounces()) {
39fefc30 366 $lock->release();
6a488035
TO
367 return civicrm_api3_create_error('Process Bounces failed');
368 }
6a488035 369 $lock->release();
39fefc30
KJ
370
371 // FIXME: processBounces doesn't return true/false on success/failure
372 $values = array();
6a488035
TO
373 return civicrm_api3_create_success($values, $params, 'mailing', 'bounces');
374}
375
376/**
377 * Job to get mail and create activities
378 */
379function civicrm_api3_job_fetch_activities($params) {
39fefc30 380 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
6a488035
TO
381 if (!$lock->isAcquired()) {
382 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
383 }
39fefc30
KJ
384
385 try {
386 CRM_Utils_Mail_EmailProcessor::processActivities();
387 $values = array( );
6a488035 388 $lock->release();
39fefc30
KJ
389 return civicrm_api3_create_success($values, $params,'mailing','activities');
390 } catch (Exception $e) {
6a488035
TO
391 $lock->release();
392 return civicrm_api3_create_error('Process Activities failed');
393 }
394}
395
396/**
397 * Process participant statuses
398 *
399 * @param array $params (reference ) input parameters
400 *
401 * @return array (reference ) array of properties, if error an array with an error id and error message
402 * @access public
403 */
404function civicrm_api3_job_process_participant($params) {
6a488035
TO
405 $result = CRM_Event_BAO_ParticipantStatusType::process($params);
406
407 if (!$result['is_error']) {
408 return civicrm_api3_create_success(implode("\r\r", $result['messages']));
409 }
410 else {
411 return civicrm_api3_create_error('Error while processing participant statuses');
412 }
413}
414
415
416/**
417 * This api checks and updates the status of all membership records for a given domain using the calc_membership_status and
418 * update_contact_membership APIs.
419 *
420 * IMPORTANT:
421 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
422 *
423 * @param array $params input parameters NOT USED
424 *
425 * @return boolean true if success, else false
426 * @static void
427 * @access public
428 */
429function civicrm_api3_job_process_membership($params) {
39fefc30
KJ
430 $lock = new CRM_Core_Lock('civimail.job.updateMembership');
431 if (!$lock->isAcquired()) {
432 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
433 }
434
6a488035 435 $result = CRM_Member_BAO_Membership::updateAllMembershipStatus();
39fefc30 436 $lock->release();
6a488035
TO
437
438 if ($result['is_error'] == 0) {
439 return civicrm_api3_create_success($result['messages']);
440 }
441 else {
442 return civicrm_api3_create_error($result['messages']);
443 }
444}
445
446/**
447 * This api checks and updates the status of all survey respondants.
448 *
449 * @param array $params (reference ) input parameters
450 *
451 * @return boolean true if success, else false
452 * @static void
453 * @access public
454 */
455function civicrm_api3_job_process_respondent($params) {
6a488035
TO
456 $result = CRM_Campaign_BAO_Survey::releaseRespondent($params);
457
458 if ($result['is_error'] == 0) {
459 return civicrm_api3_create_success();
460 }
461 else {
462 return civicrm_api3_create_error($result['messages']);
463 }
464}
465
466/**
467 * Merges given pair of duplicate contacts.
468 *
469 * @param array $params input parameters
470 *
471 * Allowed @params array keys are:
472 * {int $rgid rule group id}
473 * {int $gid group id}
474 * {string mode helps decide how to behave when there are conflicts.
475 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
476 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
477 *
478 * @return array API Result Array
479 *
480 * @static void
481 * @access public
482 */
483function civicrm_api3_job_process_batch_merge($params) {
484 $rgid = CRM_Utils_Array::value('rgid', $params);
485 $gid = CRM_Utils_Array::value('gid', $params);
486
487 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
488 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
489
6a488035
TO
490 $result = CRM_Dedupe_Merger::batchMerge($rgid, $gid, $mode, $autoFlip);
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 * Runs handlePaymentCron method in the specified payment processor
502 *
503 * @param array $params input parameters
504 *
505 * Expected @params array keys are:
506 * {string 'processor_name' - the name of the payment processor, eg: Sagepay}
507 *
508 * @access public
509 */
510function civicrm_api3_job_run_payment_cron($params) {
511
6a488035
TO
512 // live mode
513 CRM_Core_Payment::handlePaymentMethod(
514 'PaymentCron',
515 array_merge(
516 $params,
517 array(
518 'caller' => 'api',
519 )
520 )
521 );
522
523 // test mode
524 CRM_Core_Payment::handlePaymentMethod(
525 'PaymentCron',
526 array_merge(
527 $params,
528 array(
529 'mode' => 'test',
530 )
531 )
532 );
533}
534
535/**
536 * This api cleans up all the old session entries and temp tables. We recommend that sites run this on an hourly basis
537 *
538 * @param array $params (reference ) - sends in various config parameters to decide what needs to be cleaned
539 *
540 * @return boolean true if success, else false
541 * @static void
542 * @access public
543 */
544function civicrm_api3_job_cleanup( $params ) {
6a488035
TO
545 $session = CRM_Utils_Array::value( 'session' , $params, true );
546 $tempTable = CRM_Utils_Array::value( 'tempTables', $params, true );
547 $jobLog = CRM_Utils_Array::value( 'jobLog' , $params, true );
548 $prevNext = CRM_Utils_Array::value( 'prevNext' , $params, true );
549 $dbCache = CRM_Utils_Array::value( 'dbCache' , $params, false );
550 $memCache = CRM_Utils_Array::value( 'memCache' , $params, false );
551
552 if ( $session || $tempTable || $prevNext ) {
6a488035
TO
553 CRM_Core_BAO_Cache::cleanup( $session, $tempTable, $prevNext );
554 }
555
556 if ( $jobLog ) {
557 CRM_Core_BAO_Job::cleanup( );
558 }
559
560 if ( $dbCache ) {
561 CRM_Core_Config::clearDBCache( );
562 }
563
564 if ( $memCache ) {
565 CRM_Utils_System::flushCache( );
566 }
567}
568
569/**
570 * Set expired relationships to disabled.
571 *
572 */
573function civicrm_api3_job_disable_expired_relationships($params) {
574 $result = CRM_Contact_BAO_Relationship::disableExpiredRelationships();
575 if ($result) {
576 return civicrm_api3_create_success();
577 }
578 else {
579 return civicrm_api3_create_error('Failed to disable all expired relationships.');
580 }
581}
582
583/**
584 * This api reloads all the smart groups. If the org has a large number of smart groups
585 * it is recommended that they use the limit clause to limit the number of smart groups
586 * evaluated on a per job basis. Might also help to increase the smartGroupCacheTimeout
587 * and use the cache
588 */
589function civicrm_api3_job_group_rebuild( $params ) {
39fefc30
KJ
590 $lock = new CRM_Core_Lock('civimail.job.groupRebuild');
591 if (!$lock->isAcquired()) {
592 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
593 }
594
6a488035
TO
595 $limit = CRM_Utils_Array::value( 'limit', $params, 0 );
596
597 CRM_Contact_BAO_GroupContactCache::loadAll(null, $limit);
39fefc30
KJ
598 $lock->release();
599
f9e16e9a 600 return civicrm_api3_create_success();
6a488035 601}