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