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