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