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