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