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