Merge pull request #3971 from davecivicrm/CRM-15121
[civicrm-core.git] / api / v3 / Job.php
1 <?php
2 // $Id$
3
4 /*
5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.5 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
38 * $Id: Contact.php 30879 2010-11-22 15:45:55Z shot $
39 *
40 */
41
42 /**
43 * Adjust metadata for "Create" action
44 *
45 * The metadata is used for setting defaults, documentation & validation
46 * @param array $params array or parameters determined by getfields
47 */
48 function _civicrm_api3_job_create_spec(&$params) {
49 $params['run_frequency']['api.required'] = 1;
50 $params['name']['api.required'] = 1;
51 $params['api_entity']['api.required'] = 1;
52 $params['api_action']['api.required'] = 1;
53
54 $params['domain_id']['api.default'] = CRM_Core_Config::domainID();
55 $params['is_active']['api.default'] = 1;
56 }
57
58 /**
59 * Function to create scheduled job
60 *
61 * @param array $params Associative array of property name/value pairs to insert in new job.
62 *
63 * @return success or error
64 * {@getfields Job_create}
65 * @access public
66 * {@schema Core/Job.xml}
67 */
68 function civicrm_api3_job_create($params) {
69 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
70 }
71
72 /**
73 * Retrieve one or more job
74 * @param array input parameters
75 * @return array api result array
76 * {@getfields email_get}
77 * @access public
78 */
79 function civicrm_api3_job_get($params) {
80 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
81 }
82
83 /**
84 * Delete a job
85 *
86 * @param $params
87 *
88 * @internal param int $id
89 *
90 * @return array API Result Array
91 * {@getfields Job_delete}
92 * @static void
93 * @access public
94 */
95 function civicrm_api3_job_delete($params) {
96 _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
97 }
98
99 /**
100 * Dumb wrapper to execute scheduled jobs. Always creates success - errors
101 * and results are handled in the job log.
102 *
103 * @param array $params (reference ) input parameters
104 *
105 * @return array API Result Array
106 *
107 * @static void
108 * @access public
109 *
110 */
111 function civicrm_api3_job_execute($params) {
112 $facility = new CRM_Core_JobManager();
113 $facility->execute(FALSE);
114
115 // always creates success - results are handled elsewhere
116 return civicrm_api3_create_success();
117 }
118
119 /**
120 * Adjust Metadata for Execute action
121 *
122 * @param array $params array or parameters determined by getfields
123 */
124 function _civicrm_api3_job_execute_spec(&$params) {
125 }
126
127 /**
128 * Geocode group of contacts based on given params
129 *
130 * @param array $params (reference ) input parameters
131 *
132 * @return array API Result Array
133 * {@getfields contact_geocode}
134 *
135 * @static void
136 * @access public
137 *
138 *
139 */
140 function civicrm_api3_job_geocode($params) {
141 $gc = new CRM_Utils_Address_BatchUpdate($params);
142
143
144 $result = $gc->run();
145
146 if ($result['is_error'] == 0) {
147 return civicrm_api3_create_success($result['messages']);
148 }
149 else {
150 return civicrm_api3_create_error($result['messages']);
151 }
152 }
153 /**
154 * First check on Code documentation
155 */
156 function _civicrm_api3_job_geocode_spec(&$params) {
157 $params['start'] = array('title' => 'Start Date');
158 $params['end'] = array('title' => 'End Date');
159 $params['geocoding'] = array('title' => 'Geocode address?');
160 $params['parse'] = array('title' => 'Parse street address?');
161 $params['throttle'] = array('title' => 'Throttle? if enabled, geocodes at a slow rate');
162 }
163
164 /**
165 * Send the scheduled reminders for all contacts (either for activities or events)
166 *
167 * @param array $params (reference ) input parameters
168 * now - the time to use, in YmdHis format
169 * - makes testing a bit simpler since we can simulate past/future time
170 *
171 * @return boolean true if success, else false
172 * @static void
173 * @access public
174 *
175 */
176 function civicrm_api3_job_send_reminder($params) {
177 //note that $params['rowCount' can be overridden by one of the preferred syntaxes ($options['limit'] = x
178 //It's not clear whether than syntax can be passed in via the UI config - but this keeps the pre 4.4.4 behaviour
179 // in that case (ie. makes it unconfigurable via the UI). Another approach would be to set a default of 0
180 // in the _spec function - but since that is a deprecated value it seems more contentious than this approach
181 $params['rowCount'] = 0;
182 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
183 if (!$lock->isAcquired()) {
184 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
185 }
186
187 $result = CRM_Core_BAO_ActionSchedule::processQueue(CRM_Utils_Array::value('now', $params), $params);
188 $lock->release();
189
190 if ($result['is_error'] == 0) {
191 return civicrm_api3_create_success();
192 }
193 else {
194 return civicrm_api3_create_error($result['messages']);
195 }
196 }
197 /**
198 * Adjust metadata for "send_reminder" action
199 *
200 * The metadata is used for setting defaults, documentation & validation
201 * @param array $params array or parameters determined by getfields
202 */
203 function _civicrm_api3_job_send_reminder(&$params) {
204 //@todo this function will now take all fields in action_schedule as params
205 // as it is calling the api fn to set the filters - update getfields to reflect
206 $params['id'] = array(
207 'type' => CRM_Utils_Type::T_INT,
208 'title' => 'Action Schedule ID'
209 );
210 }
211 /**
212 * Execute a specific report instance and send the output via email
213 *
214 * @param array $params (reference ) input parameters
215 * sendmail - Boolean - should email be sent?, required
216 * instanceId - Integer - the report instance ID
217 * resetVal - Integer - should we reset form state (always true)?
218 *
219 * @return boolean true if success, else false
220 * @static void
221 * @access public
222 *
223 */
224 function civicrm_api3_job_mail_report($params) {
225 $result = CRM_Report_Utils_Report::processReport($params);
226
227 if ($result['is_error'] == 0) {
228 // this should be handling by throwing exceptions but can't remove until we can test that.
229 return civicrm_api3_create_success();
230 }
231 else {
232 return civicrm_api3_create_error($result['messages']);
233 }
234 }
235
236 /**
237 *
238 * This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
239 * IMPORTANT: You must first create valid option value before using via admin interface.
240 * Check option lists for Email Greetings, Postal Greetings and Addressee
241 *
242 * id - Integer - greetings option group
243 *
244 * @param $params
245 *
246 * @return boolean true if success, else false
247 * @static
248 * @access public
249 */
250 function 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 */
285 function _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 */
308 function 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 */
329 function 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 */
347 function civicrm_api3_job_process_sms($params) {
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 }
356
357 /**
358 * Job to get mail responses from civimailing
359 */
360 function civicrm_api3_job_fetch_bounces($params) {
361 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
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()) {
366 $lock->release();
367 return civicrm_api3_create_error('Process Bounces failed');
368 }
369 $lock->release();
370
371 // FIXME: processBounces doesn't return true/false on success/failure
372 $values = array();
373 return civicrm_api3_create_success($values, $params, 'mailing', 'bounces');
374 }
375
376 /**
377 * Job to get mail and create activities
378 */
379 function civicrm_api3_job_fetch_activities($params) {
380 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
381 if (!$lock->isAcquired()) {
382 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
383 }
384
385 try {
386 CRM_Utils_Mail_EmailProcessor::processActivities();
387 $values = array( );
388 $lock->release();
389 return civicrm_api3_create_success($values, $params,'mailing','activities');
390 } catch (Exception $e) {
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 */
404 function civicrm_api3_job_process_participant($params) {
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 */
429 function civicrm_api3_job_process_membership($params) {
430 $lock = new CRM_Core_Lock('civimail.job.updateMembership');
431 if (!$lock->isAcquired()) {
432 return civicrm_api3_create_error('Could not acquire lock, another Membership Processing process is running');
433 }
434
435 $result = CRM_Member_BAO_Membership::updateAllMembershipStatus();
436 $lock->release();
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 */
455 function civicrm_api3_job_process_respondent($params) {
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 */
483 function 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
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 */
510 function civicrm_api3_job_run_payment_cron($params) {
511
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 */
544 function civicrm_api3_job_cleanup( $params ) {
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 ) {
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 */
573 function 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 */
589 function civicrm_api3_job_group_rebuild( $params ) {
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
595 $limit = CRM_Utils_Array::value( 'limit', $params, 0 );
596
597 CRM_Contact_BAO_GroupContactCache::loadAll(null, $limit);
598 $lock->release();
599
600 return civicrm_api3_create_success();
601 }