3f922aacda08cdb00b7e72340205dfe950a2f059
[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 // @noinspection PhpUnusedParameterInspection
104
105 $facility = new CRM_Core_JobManager();
106 $facility->execute(FALSE);
107
108 // always creates success - results are handled elsewhere
109 return civicrm_api3_create_success();
110 }
111
112 /**
113 * Adjust Metadata for Execute action.
114 *
115 * @param array $params
116 * Array or parameters determined by getfields.
117 */
118 function _civicrm_api3_job_execute_spec(&$params) {
119 }
120
121 /**
122 * Geocode group of contacts based on given params.
123 *
124 * @param array $params
125 * input parameters.
126 *
127 * @return array
128 * API Result Array
129 */
130 function civicrm_api3_job_geocode($params) {
131 $gc = new CRM_Utils_Address_BatchUpdate($params);
132
133 $result = $gc->run();
134
135 if ($result['is_error'] == 0) {
136 return civicrm_api3_create_success($result['messages']);
137 }
138 else {
139 return civicrm_api3_create_error($result['messages']);
140 }
141 }
142
143 /**
144 * First check on Code documentation.
145 *
146 * @param array $params
147 */
148 function _civicrm_api3_job_geocode_spec(&$params) {
149 $params['start'] = array('title' => 'Start Date');
150 $params['end'] = array('title' => 'End Date');
151 $params['geocoding'] = array('title' => 'Geocode address?');
152 $params['parse'] = array('title' => 'Parse street address?');
153 $params['throttle'] = array('title' => 'Throttle? if enabled, geo-codes at a slow rate');
154 }
155
156 /**
157 * Send the scheduled reminders for all contacts (either for activities or events).
158 *
159 * @param array $params
160 * (reference ) input parameters.
161 * now - the time to use, in YmdHis format
162 * - makes testing a bit simpler since we can simulate past/future time
163 *
164 * @return array
165 */
166 function civicrm_api3_job_send_reminder($params) {
167 //note that $params['rowCount' can be overridden by one of the preferred syntaxes ($options['limit'] = x
168 //It's not clear whether than syntax can be passed in via the UI config - but this keeps the pre 4.4.4 behaviour
169 // in that case (ie. makes it non-configurable via the UI). Another approach would be to set a default of 0
170 // in the _spec function - but since that is a deprecated value it seems more contentious than this approach
171 $params['rowCount'] = 0;
172 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
173 if (!$lock->isAcquired()) {
174 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
175 }
176
177 $result = CRM_Core_BAO_ActionSchedule::processQueue(CRM_Utils_Array::value('now', $params), $params);
178 $lock->release();
179
180 if ($result['is_error'] == 0) {
181 return civicrm_api3_create_success();
182 }
183 else {
184 return civicrm_api3_create_error($result['messages']);
185 }
186 }
187 /**
188 * Adjust metadata for "send_reminder" action.
189 *
190 * The metadata is used for setting defaults, documentation & validation.
191 *
192 * @param array $params
193 * Array or parameters determined by getfields.
194 */
195 function _civicrm_api3_job_send_reminder(&$params) {
196 //@todo this function will now take all fields in action_schedule as params
197 // as it is calling the api fn to set the filters - update getfields to reflect
198 $params['id'] = array(
199 'type' => CRM_Utils_Type::T_INT,
200 'title' => 'Action Schedule ID',
201 );
202 }
203 /**
204 * Execute a specific report instance and send the output via email.
205 *
206 * @param array $params
207 * (reference ) input parameters.
208 * sendmail - Boolean - should email be sent?, required
209 * instanceId - Integer - the report instance ID
210 * resetVal - Integer - should we reset form state (always true)?
211 *
212 * @return array
213 */
214 function civicrm_api3_job_mail_report($params) {
215 $result = CRM_Report_Utils_Report::processReport($params);
216
217 if ($result['is_error'] == 0) {
218 // this should be handling by throwing exceptions but can't remove until we can test that.
219 return civicrm_api3_create_success();
220 }
221 else {
222 return civicrm_api3_create_error($result['messages']);
223 }
224 }
225
226 /**
227 * This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
228 *
229 * IMPORTANT: You must first create valid option value before using via admin interface.
230 * Check option lists for Email Greetings, Postal Greetings and Addressee
231 *
232 * @todo - is this here by mistake or should it be added to _spec function :id - Integer - greetings option group.
233 *
234 * @param array $params
235 *
236 * @return array
237 */
238 function civicrm_api3_job_update_greeting($params) {
239 if (isset($params['ct']) && isset($params['gt'])) {
240 $ct = explode(',', $params['ct']);
241 $gt = explode(',', $params['gt']);
242 foreach ($ct as $ctKey => $ctValue) {
243 foreach ($gt as $gtKey => $gtValue) {
244 $params['ct'] = trim($ctValue);
245 $params['gt'] = trim($gtValue);
246 CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
247 }
248 }
249 }
250 else {
251 CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
252 }
253 return civicrm_api3_create_success();
254 }
255
256 /**
257 * Adjust Metadata for Get action.
258 *
259 * The metadata is used for setting defaults, documentation & validation.
260 *
261 * @param array $params
262 * Array or parameters determined by getfields.
263 */
264 function _civicrm_api3_job_update_greeting_spec(&$params) {
265 $params['ct'] = array(
266 'api.required' => 1,
267 'title' => 'Contact Type',
268 'type' => CRM_Utils_Type::T_STRING,
269 );
270 $params['gt'] = array(
271 'api.required' => 1,
272 'title' => 'Greeting Type',
273 'type' => CRM_Utils_Type::T_STRING,
274 );
275 }
276
277 /**
278 * Mass update pledge statuses.
279 *
280 * @param array $params
281 *
282 * @return array
283 */
284 function civicrm_api3_job_process_pledge($params) {
285 // *** Uncomment the next line if you want automated reminders to be sent
286 // $params['send_reminders'] = true;
287 $result = CRM_Pledge_BAO_Pledge::updatePledgeStatus($params);
288
289 if ($result['is_error'] == 0) {
290 // experiment: detailed execution log is a result here
291 return civicrm_api3_create_success($result['messages']);
292 }
293 else {
294 return civicrm_api3_create_error($result['error_message']);
295 }
296 }
297
298 /**
299 * Process mail queue.
300 *
301 * @param array $params
302 *
303 * @return array
304 */
305 function civicrm_api3_job_process_mailing($params) {
306
307 if (!CRM_Mailing_BAO_Mailing::processQueue()) {
308 return civicrm_api3_create_error('Process Queue failed');
309 }
310 else {
311 $values = array();
312 return civicrm_api3_create_success($values, $params, 'mailing', 'process');
313 }
314 }
315
316 /**
317 * Process sms queue.
318 *
319 * @param array $params
320 *
321 * @return array
322 */
323 function civicrm_api3_job_process_sms($params) {
324 if (!CRM_Mailing_BAO_Mailing::processQueue('sms')) {
325 return civicrm_api3_create_error('Process Queue failed');
326 }
327 else {
328 $values = array();
329 return civicrm_api3_create_success($values, $params, 'mailing', 'process');
330 }
331 }
332
333 /**
334 * Job to get mail responses from civiMailing.
335 *
336 * @param array $params
337 *
338 * @return array
339 */
340 function civicrm_api3_job_fetch_bounces($params) {
341 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
342 if (!$lock->isAcquired()) {
343 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
344 }
345 if (!CRM_Utils_Mail_EmailProcessor::processBounces()) {
346 $lock->release();
347 return civicrm_api3_create_error('Process Bounces failed');
348 }
349 $lock->release();
350
351 // FIXME: processBounces doesn't return true/false on success/failure
352 $values = array();
353 return civicrm_api3_create_success($values, $params, 'mailing', 'bounces');
354 }
355
356 /**
357 * Job to get mail and create activities
358 *
359 * @param array $params
360 *
361 * @return array
362 */
363 function civicrm_api3_job_fetch_activities($params) {
364 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
365 if (!$lock->isAcquired()) {
366 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
367 }
368
369 try {
370 CRM_Utils_Mail_EmailProcessor::processActivities();
371 $values = array();
372 $lock->release();
373 return civicrm_api3_create_success($values, $params, 'mailing', 'activities');
374 }
375 catch (Exception $e) {
376 $lock->release();
377 return civicrm_api3_create_error('Process Activities failed');
378 }
379 }
380
381 /**
382 * Process participant statuses
383 *
384 * @param array $params
385 * (reference ) input parameters.
386 *
387 * @return array
388 * array of properties, if error an array with an error id and error message
389 */
390 function civicrm_api3_job_process_participant($params) {
391 $result = CRM_Event_BAO_ParticipantStatusType::process($params);
392
393 if (!$result['is_error']) {
394 return civicrm_api3_create_success(implode("\r\r", $result['messages']));
395 }
396 else {
397 return civicrm_api3_create_error('Error while processing participant statuses');
398 }
399 }
400
401
402 /**
403 * This api checks and updates the status of all membership records for a given domain using the calc_membership_status and
404 * 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']);
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 */
462 function civicrm_api3_job_process_batch_merge($params) {
463 $rgid = CRM_Utils_Array::value('rgid', $params);
464 $gid = CRM_Utils_Array::value('gid', $params);
465
466 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
467 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
468
469 $result = CRM_Dedupe_Merger::batchMerge($rgid, $gid, $mode, $autoFlip);
470
471 if ($result['is_error'] == 0) {
472 return civicrm_api3_create_success();
473 }
474 else {
475 return civicrm_api3_create_error($result['messages']);
476 }
477 }
478
479 /**
480 * @param $params
481 */
482 function _civicrm_api3_job_process_batch_merge_spec(&$params) {
483 $params['rgid'] = array(
484 'title' => 'rule group id',
485 'type' => CRM_Utils_Type::T_INT,
486 );
487 $params['gid'] = array(
488 'title' => 'group id',
489 'type' => CRM_Utils_Type::T_INT,
490 );
491 $params['mode'] = array(
492 'title' => 'Mode',
493 '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.',
494 'type' => CRM_Utils_Type::T_STRING,
495 );
496 $params['auto_flip'] = array(
497 'title' => 'Auto Flip',
498 'description' => 'let the api decide which contact to retain and which to delete?',
499 'type' => CRM_Utils_Type::T_BOOLEAN,
500 );
501 }
502
503 /**
504 * Runs handlePaymentCron method in the specified payment processor
505 *
506 * @param array $params
507 * Input parameters.
508 *
509 * Expected @params array keys are:
510 * {string 'processor_name' - the name of the payment processor, eg: Sagepay}
511 *
512 */
513 function civicrm_api3_job_run_payment_cron($params) {
514
515 // live mode
516 CRM_Core_Payment::handlePaymentMethod(
517 'PaymentCron',
518 array_merge(
519 $params,
520 array(
521 'caller' => 'api',
522 )
523 )
524 );
525
526 // test mode
527 CRM_Core_Payment::handlePaymentMethod(
528 'PaymentCron',
529 array_merge(
530 $params,
531 array(
532 'mode' => 'test',
533 )
534 )
535 );
536 }
537
538 /**
539 * This api cleans up all the old session entries and temp tables. We recommend that sites run this on an hourly basis
540 *
541 * @param array $params
542 * Sends in various config parameters to decide what needs to be cleaned.
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 * @param $params
572 * @return array
573 * @throws \API_Exception
574 */
575 function civicrm_api3_job_disable_expired_relationships($params) {
576 /** @noinspection PhpUnusedParameterInspection */
577 $result = CRM_Contact_BAO_Relationship::disableExpiredRelationships();
578 if (!$result) {
579 throw new API_Exception('Failed to disable all expired relationships.');
580 }
581 return civicrm_api3_create_success();
582 }
583
584 /**
585 * This api reloads all the smart groups. If the org has a large number of smart groups
586 * it is recommended that they use the limit clause to limit the number of smart groups
587 * evaluated on a per job basis. Might also help to increase the smartGroupCacheTimeout
588 * and use the cache
589 *
590 * @param array $params
591 * @return array
592 * @throws \API_Exception
593 */
594 function civicrm_api3_job_group_rebuild($params) {
595 $lock = new CRM_Core_Lock('civimail.job.groupRebuild');
596 if (!$lock->isAcquired()) {
597 throw new API_Exception('Could not acquire lock, another EmailProcessor process is running');
598 }
599
600 $limit = CRM_Utils_Array::value('limit', $params, 0);
601
602 CRM_Contact_BAO_GroupContactCache::loadAll(NULL, $limit);
603 $lock->release();
604
605 return civicrm_api3_create_success();
606 }