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