Merge pull request #4806 from civicrm/4.5
[civicrm-core.git] / api / v3 / Job.php
1 <?php
2 // $Id$
3
4 /*
5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.6 |
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 * 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 array $params
87 *
88 * @return array API Result Array
89 * {@getfields Job_delete}
90 * @static void
91 * @access public
92 */
93 function civicrm_api3_job_delete($params) {
94 _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
95 }
96
97 /**
98 * Dumb wrapper to execute scheduled jobs. Always creates success - errors
99 * and results are handled in the job log.
100 *
101 * @param array $params (reference ) input parameters
102 *
103 * @return array API Result Array
104 *
105 * @static void
106 * @access public
107 *
108 */
109 function civicrm_api3_job_execute($params) {
110 $facility = new CRM_Core_JobManager();
111 $facility->execute(FALSE);
112
113 // always creates success - results are handled elsewhere
114 return civicrm_api3_create_success();
115 }
116
117 /**
118 * Adjust Metadata for Execute action
119 *
120 * @param array $params array or parameters determined by getfields
121 */
122 function _civicrm_api3_job_execute_spec(&$params) {
123 }
124
125 /**
126 * Geocode group of contacts based on given params
127 *
128 * @param array $params (reference ) input parameters
129 *
130 * @return array API Result Array
131 * {@getfields contact_geocode}
132 *
133 * @static void
134 * @access public
135 *
136 *
137 */
138 function civicrm_api3_job_geocode($params) {
139 $gc = new CRM_Utils_Address_BatchUpdate($params);
140
141
142 $result = $gc->run();
143
144 if ($result['is_error'] == 0) {
145 return civicrm_api3_create_success($result['messages']);
146 }
147 else {
148 return civicrm_api3_create_error($result['messages']);
149 }
150 }
151
152 /**
153 * First check on Code documentation
154 *
155 * @param array $params
156 */
157 function _civicrm_api3_job_geocode_spec(&$params) {
158 $params['start'] = array('title' => 'Start Date');
159 $params['end'] = array('title' => 'End Date');
160 $params['geocoding'] = array('title' => 'Geocode address?');
161 $params['parse'] = array('title' => 'Parse street address?');
162 $params['throttle'] = array('title' => 'Throttle? if enabled, geocodes at a slow rate');
163 }
164
165 /**
166 * Send the scheduled reminders for all contacts (either for activities or events)
167 *
168 * @param array $params (reference ) input parameters
169 * now - the time to use, in YmdHis format
170 * - makes testing a bit simpler since we can simulate past/future time
171 *
172 * @return boolean true if success, else false
173 * @static void
174 * @access public
175 *
176 */
177 function civicrm_api3_job_send_reminder($params) {
178 //note that $params['rowCount' can be overridden by one of the preferred syntaxes ($options['limit'] = x
179 //It's not clear whether than syntax can be passed in via the UI config - but this keeps the pre 4.4.4 behaviour
180 // in that case (ie. makes it unconfigurable via the UI). Another approach would be to set a default of 0
181 // in the _spec function - but since that is a deprecated value it seems more contentious than this approach
182 $params['rowCount'] = 0;
183 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
184 if (!$lock->isAcquired()) {
185 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
186 }
187
188 $result = CRM_Core_BAO_ActionSchedule::processQueue(CRM_Utils_Array::value('now', $params), $params);
189 $lock->release();
190
191 if ($result['is_error'] == 0) {
192 return civicrm_api3_create_success();
193 }
194 else {
195 return civicrm_api3_create_error($result['messages']);
196 }
197 }
198 /**
199 * Adjust metadata for "send_reminder" action
200 *
201 * The metadata is used for setting defaults, documentation & validation
202 * @param array $params array or parameters determined by getfields
203 */
204 function _civicrm_api3_job_send_reminder(&$params) {
205 //@todo this function will now take all fields in action_schedule as params
206 // as it is calling the api fn to set the filters - update getfields to reflect
207 $params['id'] = array(
208 'type' => CRM_Utils_Type::T_INT,
209 'title' => 'Action Schedule ID'
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 */
225 function civicrm_api3_job_mail_report($params) {
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 * @param array $params
246 *
247 * @return boolean true if success, else false
248 * @static
249 * @access public
250 */
251 function civicrm_api3_job_update_greeting($params) {
252
253 if (isset($params['ct']) && isset($params['gt'])) {
254 $ct = $gt = array();
255 $ct = explode(',', $params['ct']);
256 $gt = explode(',', $params['gt']);
257 foreach ($ct as $ctKey => $ctValue) {
258 foreach ($gt as $gtKey => $gtValue) {
259 $params['ct'] = trim($ctValue);
260 $params['gt'] = trim($gtValue);
261 $result[] = CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
262 }
263 }
264 }
265 else {
266 $result = CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
267 }
268
269 foreach ($result as $resultKey => $resultValue) {
270 if ($resultValue['is_error'] == 0) {
271 //really we should rely on the exception mechanism here - but we need to test that before removing this line
272 return civicrm_api3_create_success();
273 }
274 else {
275 return civicrm_api3_create_error($resultValue['messages']);
276 }
277 }
278 }
279
280 /**
281 * Adjust Metadata for Get action
282 *
283 * The metadata is used for setting defaults, documentation & validation
284 * @param array $params array or parameters determined by getfields
285 */
286 function _civicrm_api3_job_update_greeting_spec(&$params) {
287 $params['ct'] = array(
288 'api.required' => 1,
289 'title' => 'Contact Type',
290 'type' => CRM_Utils_Type::T_STRING,
291 );
292 $params['gt'] = array(
293 'api.required' => 1,
294 'title' => 'Greeting Type',
295 'type' => CRM_Utils_Type::T_STRING,
296 );
297 }
298
299 /**
300 * Mass update pledge statuses
301 *
302 * @param array $params (reference ) input parameters
303 *
304 * @return boolean true if success, else false
305 * @static
306 * @access public
307 *
308 */
309 function civicrm_api3_job_process_pledge($params) {
310 // *** Uncomment the next line if you want automated reminders to be sent
311 // $params['send_reminders'] = true;
312 $result = CRM_Pledge_BAO_Pledge::updatePledgeStatus($params);
313
314 if ($result['is_error'] == 0) {
315 // experiment: detailed execution log is a result here
316 return civicrm_api3_create_success($result['messages']);
317 }
318 else {
319 return civicrm_api3_create_error($result['error_message']);
320 }
321 }
322
323 /**
324 * Process mail queue
325 *
326 * @param array $params
327 *
328 * @return array
329 */
330 function civicrm_api3_job_process_mailing($params) {
331
332 if (!CRM_Mailing_BAO_Mailing::processQueue()) {
333 return civicrm_api3_create_error('Process Queue failed');
334 }
335 else {
336 $values = array();
337 return civicrm_api3_create_success($values, $params, 'mailing', 'process');
338 }
339 }
340
341 /**
342 * Process sms queue
343 *
344 * @param array $params
345 *
346 * @return array
347 */
348 function civicrm_api3_job_process_sms($params) {
349 if (!CRM_Mailing_BAO_Mailing::processQueue('sms')) {
350 return civicrm_api3_create_error('Process Queue failed');
351 }
352 else {
353 $values = array();
354 return civicrm_api3_create_success($values, $params, 'mailing', 'process');
355 }
356 }
357
358 /**
359 * Job to get mail responses from civimailing
360 *
361 * @param array $params
362 *
363 * @return array
364 */
365 function civicrm_api3_job_fetch_bounces($params) {
366 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
367 if (!$lock->isAcquired()) {
368 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
369 }
370 if (!CRM_Utils_Mail_EmailProcessor::processBounces()) {
371 $lock->release();
372 return civicrm_api3_create_error('Process Bounces failed');
373 }
374 $lock->release();
375
376 // FIXME: processBounces doesn't return true/false on success/failure
377 $values = array();
378 return civicrm_api3_create_success($values, $params, 'mailing', 'bounces');
379 }
380
381 /**
382 * Job to get mail and create activities
383 *
384 * @param array $params
385 *
386 * @return array
387 */
388 function civicrm_api3_job_fetch_activities($params) {
389 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
390 if (!$lock->isAcquired()) {
391 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
392 }
393
394 try {
395 CRM_Utils_Mail_EmailProcessor::processActivities();
396 $values = array( );
397 $lock->release();
398 return civicrm_api3_create_success($values, $params,'mailing','activities');
399 } catch (Exception $e) {
400 $lock->release();
401 return civicrm_api3_create_error('Process Activities failed');
402 }
403 }
404
405 /**
406 * Process participant statuses
407 *
408 * @param array $params (reference ) input parameters
409 *
410 * @return array (reference ) array of properties, if error an array with an error id and error message
411 * @access public
412 */
413 function civicrm_api3_job_process_participant($params) {
414 $result = CRM_Event_BAO_ParticipantStatusType::process($params);
415
416 if (!$result['is_error']) {
417 return civicrm_api3_create_success(implode("\r\r", $result['messages']));
418 }
419 else {
420 return civicrm_api3_create_error('Error while processing participant statuses');
421 }
422 }
423
424
425 /**
426 * This api checks and updates the status of all membership records for a given domain using the calc_membership_status and
427 * update_contact_membership APIs.
428 *
429 * IMPORTANT:
430 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
431 *
432 * @param array $params input parameters NOT USED
433 *
434 * @return boolean true if success, else false
435 * @static void
436 * @access public
437 */
438 function civicrm_api3_job_process_membership($params) {
439 $lock = new CRM_Core_Lock('civimail.job.updateMembership');
440 if (!$lock->isAcquired()) {
441 return civicrm_api3_create_error('Could not acquire lock, another Membership Processing process is running');
442 }
443
444 $result = CRM_Member_BAO_Membership::updateAllMembershipStatus();
445 $lock->release();
446
447 if ($result['is_error'] == 0) {
448 return civicrm_api3_create_success($result['messages']);
449 }
450 else {
451 return civicrm_api3_create_error($result['messages']);
452 }
453 }
454
455 /**
456 * This api checks and updates the status of all survey respondants.
457 *
458 * @param array $params (reference ) input parameters
459 *
460 * @return boolean true if success, else false
461 * @static void
462 * @access public
463 */
464 function civicrm_api3_job_process_respondent($params) {
465 $result = CRM_Campaign_BAO_Survey::releaseRespondent($params);
466
467 if ($result['is_error'] == 0) {
468 return civicrm_api3_create_success();
469 }
470 else {
471 return civicrm_api3_create_error($result['messages']);
472 }
473 }
474
475 /**
476 * Merges given pair of duplicate contacts.
477 *
478 * @param array $params input parameters
479 *
480 * Allowed @params array keys are:
481 * {int $rgid rule group id}
482 * {int $gid group id}
483 * {string mode helps decide how to behave when there are conflicts.
484 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
485 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
486 *
487 * @return array API Result Array
488 *
489 * @static void
490 * @access public
491 */
492 function civicrm_api3_job_process_batch_merge($params) {
493 $rgid = CRM_Utils_Array::value('rgid', $params);
494 $gid = CRM_Utils_Array::value('gid', $params);
495
496 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
497 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
498
499 $result = CRM_Dedupe_Merger::batchMerge($rgid, $gid, $mode, $autoFlip);
500
501 if ($result['is_error'] == 0) {
502 return civicrm_api3_create_success();
503 }
504 else {
505 return civicrm_api3_create_error($result['messages']);
506 }
507 }
508
509 /**
510 * Runs handlePaymentCron method in the specified payment processor
511 *
512 * @param array $params input parameters
513 *
514 * Expected @params array keys are:
515 * {string 'processor_name' - the name of the payment processor, eg: Sagepay}
516 *
517 * @access public
518 */
519 function civicrm_api3_job_run_payment_cron($params) {
520
521 // live mode
522 CRM_Core_Payment::handlePaymentMethod(
523 'PaymentCron',
524 array_merge(
525 $params,
526 array(
527 'caller' => 'api',
528 )
529 )
530 );
531
532 // test mode
533 CRM_Core_Payment::handlePaymentMethod(
534 'PaymentCron',
535 array_merge(
536 $params,
537 array(
538 'mode' => 'test',
539 )
540 )
541 );
542 }
543
544 /**
545 * This api cleans up all the old session entries and temp tables. We recommend that sites run this on an hourly basis
546 *
547 * @param array $params (reference ) - sends in various config parameters to decide what needs to be cleaned
548 *
549 * @return boolean true if success, else false
550 * @static void
551 * @access public
552 */
553 function civicrm_api3_job_cleanup( $params ) {
554 $session = CRM_Utils_Array::value( 'session' , $params, true );
555 $tempTable = CRM_Utils_Array::value( 'tempTables', $params, true );
556 $jobLog = CRM_Utils_Array::value( 'jobLog' , $params, true );
557 $prevNext = CRM_Utils_Array::value( 'prevNext' , $params, true );
558 $dbCache = CRM_Utils_Array::value( 'dbCache' , $params, false );
559 $memCache = CRM_Utils_Array::value( 'memCache' , $params, false );
560
561 if ( $session || $tempTable || $prevNext ) {
562 CRM_Core_BAO_Cache::cleanup( $session, $tempTable, $prevNext );
563 }
564
565 if ( $jobLog ) {
566 CRM_Core_BAO_Job::cleanup( );
567 }
568
569 if ( $dbCache ) {
570 CRM_Core_Config::clearDBCache( );
571 }
572
573 if ( $memCache ) {
574 CRM_Utils_System::flushCache( );
575 }
576 }
577
578 /**
579 * Set expired relationships to disabled.
580 *
581 * @param array $params
582 *
583 * @return array
584 */
585 function civicrm_api3_job_disable_expired_relationships($params) {
586 $result = CRM_Contact_BAO_Relationship::disableExpiredRelationships();
587 if ($result) {
588 return civicrm_api3_create_success();
589 }
590 else {
591 return civicrm_api3_create_error('Failed to disable all expired relationships.');
592 }
593 }
594
595 /**
596 * This api reloads all the smart groups. If the org has a large number of smart groups
597 * it is recommended that they use the limit clause to limit the number of smart groups
598 * evaluated on a per job basis. Might also help to increase the smartGroupCacheTimeout
599 * and use the cache
600 *
601 * @param array $params
602 *
603 * @return array
604 */
605 function civicrm_api3_job_group_rebuild($params) {
606 $lock = new CRM_Core_Lock('civimail.job.groupRebuild');
607 if (!$lock->isAcquired()) {
608 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
609 }
610
611 $limit = CRM_Utils_Array::value( 'limit', $params, 0 );
612
613 CRM_Contact_BAO_GroupContactCache::loadAll(null, $limit);
614 $lock->release();
615
616 return civicrm_api3_create_success();
617 }