Merge pull request #5424 from agh1/reminder-created_date
[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('title' => 'Start Date');
143 $params['end'] = array('title' => 'End Date');
144 $params['geocoding'] = array('title' => 'Geocode address?');
145 $params['parse'] = array('title' => 'Parse street address?');
146 $params['throttle'] = array(
147 'title' => 'Throttle?',
148 'description' => 'if enabled, geo-codes at a slow rate',
149 );
150 }
151
152 /**
153 * Send the scheduled reminders for all contacts (either for activities or events).
154 *
155 * @param array $params
156 * (reference ) input parameters.
157 * now - the time to use, in YmdHis format
158 * - makes testing a bit simpler since we can simulate past/future time
159 *
160 * @return array
161 */
162 function civicrm_api3_job_send_reminder($params) {
163 //note that $params['rowCount' can be overridden by one of the preferred syntaxes ($options['limit'] = x
164 //It's not clear whether than syntax can be passed in via the UI config - but this keeps the pre 4.4.4 behaviour
165 // in that case (ie. makes it non-configurable via the UI). Another approach would be to set a default of 0
166 // in the _spec function - but since that is a deprecated value it seems more contentious than this approach
167 $params['rowCount'] = 0;
168 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
169 if (!$lock->isAcquired()) {
170 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
171 }
172
173 $result = CRM_Core_BAO_ActionSchedule::processQueue(CRM_Utils_Array::value('now', $params), $params);
174 $lock->release();
175
176 if ($result['is_error'] == 0) {
177 return civicrm_api3_create_success();
178 }
179 else {
180 return civicrm_api3_create_error($result['messages']);
181 }
182 }
183 /**
184 * Adjust metadata for "send_reminder" action.
185 *
186 * The metadata is used for setting defaults, documentation & validation.
187 *
188 * @param array $params
189 * Array of parameters determined by getfields.
190 */
191 function _civicrm_api3_job_send_reminder(&$params) {
192 //@todo this function will now take all fields in action_schedule as params
193 // as it is calling the api fn to set the filters - update getfields to reflect
194 $params['id'] = array(
195 'type' => CRM_Utils_Type::T_INT,
196 'title' => 'Action Schedule ID',
197 );
198 }
199 /**
200 * Execute a specific report instance and send the output via email.
201 *
202 * @param array $params
203 * (reference ) input parameters.
204 * sendmail - Boolean - should email be sent?, required
205 * instanceId - Integer - the report instance ID
206 * resetVal - Integer - should we reset form state (always true)?
207 *
208 * @return array
209 */
210 function civicrm_api3_job_mail_report($params) {
211 $result = CRM_Report_Utils_Report::processReport($params);
212
213 if ($result['is_error'] == 0) {
214 // this should be handling by throwing exceptions but can't remove until we can test that.
215 return civicrm_api3_create_success();
216 }
217 else {
218 return civicrm_api3_create_error($result['messages']);
219 }
220 }
221
222 /**
223 * This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
224 *
225 * IMPORTANT: You must first create valid option value before using via admin interface.
226 * Check option lists for Email Greetings, Postal Greetings and Addressee
227 *
228 * @todo - is this here by mistake or should it be added to _spec function :id - Integer - greetings option group.
229 *
230 * @param array $params
231 *
232 * @return array
233 */
234 function civicrm_api3_job_update_greeting($params) {
235 if (isset($params['ct']) && isset($params['gt'])) {
236 $ct = explode(',', $params['ct']);
237 $gt = explode(',', $params['gt']);
238 foreach ($ct as $ctKey => $ctValue) {
239 foreach ($gt as $gtKey => $gtValue) {
240 $params['ct'] = trim($ctValue);
241 $params['gt'] = trim($gtValue);
242 CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
243 }
244 }
245 }
246 else {
247 CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
248 }
249 return civicrm_api3_create_success();
250 }
251
252 /**
253 * Adjust Metadata for Get action.
254 *
255 * The metadata is used for setting defaults, documentation & validation.
256 *
257 * @param array $params
258 * Array of parameters determined by getfields.
259 */
260 function _civicrm_api3_job_update_greeting_spec(&$params) {
261 $params['ct'] = array(
262 'api.required' => 1,
263 'title' => 'Contact Type',
264 'type' => CRM_Utils_Type::T_STRING,
265 );
266 $params['gt'] = array(
267 'api.required' => 1,
268 'title' => 'Greeting Type',
269 'type' => CRM_Utils_Type::T_STRING,
270 );
271 }
272
273 /**
274 * Mass update pledge statuses.
275 *
276 * @param array $params
277 *
278 * @return array
279 */
280 function civicrm_api3_job_process_pledge($params) {
281 // *** Uncomment the next line if you want automated reminders to be sent
282 // $params['send_reminders'] = true;
283 $result = CRM_Pledge_BAO_Pledge::updatePledgeStatus($params);
284
285 if ($result['is_error'] == 0) {
286 // experiment: detailed execution log is a result here
287 return civicrm_api3_create_success($result['messages']);
288 }
289 else {
290 return civicrm_api3_create_error($result['error_message']);
291 }
292 }
293
294 /**
295 * Process mail queue.
296 *
297 * @param array $params
298 *
299 * @return array
300 */
301 function civicrm_api3_job_process_mailing($params) {
302
303 if (!CRM_Mailing_BAO_Mailing::processQueue()) {
304 return civicrm_api3_create_error('Process Queue failed');
305 }
306 else {
307 $values = array();
308 return civicrm_api3_create_success($values, $params, 'Job', 'process_mailing');
309 }
310 }
311
312 /**
313 * Process sms queue.
314 *
315 * @param array $params
316 *
317 * @return array
318 */
319 function civicrm_api3_job_process_sms($params) {
320 if (!CRM_Mailing_BAO_Mailing::processQueue('sms')) {
321 return civicrm_api3_create_error('Process Queue failed');
322 }
323 else {
324 $values = array();
325 return civicrm_api3_create_success($values, $params, 'Job', 'process_sms');
326 }
327 }
328
329 /**
330 * Job to get mail responses from civiMailing.
331 *
332 * @param array $params
333 *
334 * @return array
335 */
336 function civicrm_api3_job_fetch_bounces($params) {
337 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
338 if (!$lock->isAcquired()) {
339 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
340 }
341 if (!CRM_Utils_Mail_EmailProcessor::processBounces()) {
342 $lock->release();
343 return civicrm_api3_create_error('Process Bounces failed');
344 }
345 $lock->release();
346
347 // FIXME: processBounces doesn't return true/false on success/failure
348 $values = array();
349 return civicrm_api3_create_success($values, $params, 'Job', 'fetch_bounces');
350 }
351
352 /**
353 * Job to get mail and create activities.
354 *
355 * @param array $params
356 *
357 * @return array
358 */
359 function civicrm_api3_job_fetch_activities($params) {
360 $lock = new CRM_Core_Lock('civimail.job.EmailProcessor');
361 if (!$lock->isAcquired()) {
362 return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
363 }
364
365 try {
366 CRM_Utils_Mail_EmailProcessor::processActivities();
367 $values = array();
368 $lock->release();
369 return civicrm_api3_create_success($values, $params, 'Job', 'fetch_activities');
370 }
371 catch (Exception $e) {
372 $lock->release();
373 return civicrm_api3_create_error('Process Activities failed');
374 }
375 }
376
377 /**
378 * Process participant statuses.
379 *
380 * @param array $params
381 * Input parameters.
382 *
383 * @return array
384 * array of properties, if error an array with an error id and error message
385 */
386 function civicrm_api3_job_process_participant($params) {
387 $result = CRM_Event_BAO_ParticipantStatusType::process($params);
388
389 if (!$result['is_error']) {
390 return civicrm_api3_create_success(implode("\r\r", $result['messages']));
391 }
392 else {
393 return civicrm_api3_create_error('Error while processing participant statuses');
394 }
395 }
396
397
398 /**
399 * This api checks and updates the status of all membership records for a given domain.
400 *
401 * The function uses the calc_membership_status and update_contact_membership APIs.
402 *
403 * IMPORTANT:
404 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
405 *
406 * @param array $params
407 * Input parameters NOT USED.
408 *
409 * @return bool
410 * true if success, else false
411 */
412 function civicrm_api3_job_process_membership($params) {
413 $lock = new CRM_Core_Lock('civimail.job.updateMembership');
414 if (!$lock->isAcquired()) {
415 return civicrm_api3_create_error('Could not acquire lock, another Membership Processing process is running');
416 }
417
418 $result = CRM_Member_BAO_Membership::updateAllMembershipStatus();
419 $lock->release();
420
421 if ($result['is_error'] == 0) {
422 return civicrm_api3_create_success($result['messages'], $params, 'Job', 'process_membership');
423 }
424 else {
425 return civicrm_api3_create_error($result['messages']);
426 }
427 }
428
429 /**
430 * This api checks and updates the status of all survey respondents.
431 *
432 * @param array $params
433 * (reference ) input parameters.
434 *
435 * @return bool
436 * true if success, else false
437 */
438 function civicrm_api3_job_process_respondent($params) {
439 $result = CRM_Campaign_BAO_Survey::releaseRespondent($params);
440
441 if ($result['is_error'] == 0) {
442 return civicrm_api3_create_success();
443 }
444 else {
445 return civicrm_api3_create_error($result['messages']);
446 }
447 }
448
449 /**
450 * Merges given pair of duplicate contacts.
451 *
452 * @param array $params
453 * Input parameters.
454 *
455 * @return array
456 * API Result Array
457 */
458 function civicrm_api3_job_process_batch_merge($params) {
459 $rgid = CRM_Utils_Array::value('rgid', $params);
460 $gid = CRM_Utils_Array::value('gid', $params);
461
462 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
463 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
464
465 $result = CRM_Dedupe_Merger::batchMerge($rgid, $gid, $mode, $autoFlip);
466
467 if ($result['is_error'] == 0) {
468 return civicrm_api3_create_success();
469 }
470 else {
471 return civicrm_api3_create_error($result['messages']);
472 }
473 }
474
475 /**
476 * Metadata for batch merge function.
477 *
478 * @param $params
479 */
480 function _civicrm_api3_job_process_batch_merge_spec(&$params) {
481 $params['rgid'] = array(
482 'title' => 'rule group id',
483 'type' => CRM_Utils_Type::T_INT,
484 );
485 $params['gid'] = array(
486 'title' => 'group id',
487 'type' => CRM_Utils_Type::T_INT,
488 );
489 $params['mode'] = array(
490 'title' => 'Mode',
491 '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.',
492 'type' => CRM_Utils_Type::T_STRING,
493 );
494 $params['auto_flip'] = array(
495 'title' => 'Auto Flip',
496 'description' => 'let the api decide which contact to retain and which to delete?',
497 'type' => CRM_Utils_Type::T_BOOLEAN,
498 );
499 }
500
501 /**
502 * Runs handlePaymentCron method in the specified payment processor.
503 *
504 * @param array $params
505 * Input parameters.
506 *
507 * Expected @params array keys are: INCORRECTLY DOCUMENTED AND SHOULD BE IN THE _spec function
508 * for retrieval via getfields.
509 * {string 'processor_name' - the name of the payment processor, eg: Sagepay}
510 */
511 function civicrm_api3_job_run_payment_cron($params) {
512
513 // live mode
514 CRM_Core_Payment::handlePaymentMethod(
515 'PaymentCron',
516 array_merge(
517 $params,
518 array(
519 'caller' => 'api',
520 )
521 )
522 );
523
524 // test mode
525 CRM_Core_Payment::handlePaymentMethod(
526 'PaymentCron',
527 array_merge(
528 $params,
529 array(
530 'mode' => 'test',
531 )
532 )
533 );
534 }
535
536 /**
537 * This api cleans up all the old session entries and temp tables.
538 *
539 * 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 *
572 * @param array $params
573 *
574 * @return array
575 * @throws \API_Exception
576 */
577 function civicrm_api3_job_disable_expired_relationships($params) {
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(1, $params, 'Job', 'disable_expired_relationships');
583 }
584
585 /**
586 * This api reloads all the smart groups.
587 *
588 * If the org has a large number of smart groups it is recommended that they use the limit clause
589 * to limit the number of smart groups evaluated on a per job basis.
590 *
591 * Might also help to increase the smartGroupCacheTimeout and use the cache.
592 *
593 * @param array $params
594 *
595 * @return array
596 * @throws \API_Exception
597 */
598 function civicrm_api3_job_group_rebuild($params) {
599 $lock = new CRM_Core_Lock('civimail.job.groupRebuild');
600 if (!$lock->isAcquired()) {
601 throw new API_Exception('Could not acquire lock, another EmailProcessor process is running');
602 }
603
604 $limit = CRM_Utils_Array::value('limit', $params, 0);
605
606 CRM_Contact_BAO_GroupContactCache::loadAll(NULL, $limit);
607 $lock->release();
608
609 return civicrm_api3_create_success();
610 }