Merge pull request #16691 from mattwire/eventcart_cleanup
[civicrm-core.git] / CRM / Financial / BAO / PaymentProcessor.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class contains payment processor related functions.
20 */
21 class CRM_Financial_BAO_PaymentProcessor extends CRM_Financial_DAO_PaymentProcessor {
22 /**
23 * Static holder for the default payment processor
24 * @var object
25 */
26 public static $_defaultPaymentProcessor = NULL;
27
28 /**
29 * Create Payment Processor.
30 *
31 * @param array $params
32 * Parameters for Processor entity.
33 *
34 * @return CRM_Financial_DAO_PaymentProcessor
35 * @throws Exception
36 */
37 public static function create($params) {
38 // If we are creating a new PaymentProcessor and have not specified the payment instrument to use, get the default from the Payment Processor Type.
39 if (empty($params['id']) && empty($params['payment_instrument_id'])) {
40 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessorType', 'getvalue', [
41 'id' => $params['payment_processor_type_id'],
42 'return' => 'payment_instrument_id',
43 ]);
44 }
45 $processor = new CRM_Financial_DAO_PaymentProcessor();
46 $processor->copyValues($params);
47
48 if (empty($params['id'])) {
49 $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
50 $ppTypeDAO->id = $params['payment_processor_type_id'];
51 if (!$ppTypeDAO->find(TRUE)) {
52 CRM_Core_Error::fatal(ts('Could not find payment processor meta information'));
53 }
54
55 // also copy meta fields from the info DAO
56 $processor->is_recur = $ppTypeDAO->is_recur;
57 $processor->billing_mode = $ppTypeDAO->billing_mode;
58 $processor->class_name = $ppTypeDAO->class_name;
59 $processor->payment_type = $ppTypeDAO->payment_type;
60 }
61
62 $processor->save();
63 // CRM-11826, add entry in civicrm_entity_financial_account
64 // if financial_account_id is not NULL
65 if (!empty($params['financial_account_id'])) {
66 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
67 $values = [
68 'entity_table' => 'civicrm_payment_processor',
69 'entity_id' => $processor->id,
70 'account_relationship' => $relationTypeId,
71 'financial_account_id' => $params['financial_account_id'],
72 ];
73 CRM_Financial_BAO_FinancialTypeAccount::add($values);
74 }
75
76 if (isset($params['id']) && isset($params['is_active']) && !isset($params['is_test'])) {
77 // check if is_active has changed & if so update test instance is_active too.
78 $test_id = self::getTestProcessorId($params['id']);
79 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
80 $testDAO->id = $test_id;
81 if ($testDAO->find(TRUE)) {
82 $testDAO->is_active = $params['is_active'];
83 $testDAO->save();
84 }
85 }
86
87 Civi\Payment\System::singleton()->flushProcessors();
88 return $processor;
89 }
90
91 /**
92 * Class constructor.
93 */
94 public function __construct() {
95 parent::__construct();
96 }
97
98 /**
99 * Retrieve array of allowed credit cards for this payment processor.
100 * @param interger|null $paymentProcessorID id of processor.
101 * @return array
102 */
103 public static function getCreditCards($paymentProcessorID = NULL) {
104 if (!empty($paymentProcessorID)) {
105 $processor = new CRM_Financial_DAO_PaymentProcessor();
106 $processor->id = $paymentProcessorID;
107 $processor->find(TRUE);
108 $cards = json_decode($processor->accepted_credit_cards, TRUE);
109 return $cards;
110 }
111 return [];
112 }
113
114 /**
115 * Get options for a given contribution field.
116 *
117 * @param string $fieldName
118 * @param string $context see CRM_Core_DAO::buildOptionsContext.
119 * @param array $props whatever is known about this dao object.
120 *
121 * @return array|bool
122 * @see CRM_Core_DAO::buildOptions
123 *
124 */
125 public static function buildOptions($fieldName, $context = NULL, $props = []) {
126 $params = [];
127 if ($fieldName === 'financial_account_id') {
128 // Pseudo-field - let's help out.
129 return CRM_Core_BAO_FinancialTrxn::buildOptions('to_financial_account_id', $context, $props);
130 }
131 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
132 }
133
134 /**
135 * Retrieve DB object based on input parameters.
136 *
137 * It also stores all the retrieved values in the default array.
138 *
139 * @param array $params
140 * (reference ) an assoc array of name/value pairs.
141 * @param array $defaults
142 * (reference ) an assoc array to hold the flattened values.
143 *
144 * @return CRM_Financial_DAO_PaymentProcessor|null
145 * object on success, null otherwise
146 */
147 public static function retrieve(&$params, &$defaults) {
148 $paymentProcessor = new CRM_Financial_DAO_PaymentProcessor();
149 $paymentProcessor->copyValues($params);
150 if ($paymentProcessor->find(TRUE)) {
151 CRM_Core_DAO::storeValues($paymentProcessor, $defaults);
152 return $paymentProcessor;
153 }
154 return NULL;
155 }
156
157 /**
158 * Update the is_active flag in the db.
159 *
160 * @param int $id
161 * Id of the database record.
162 * @param bool $is_active
163 * Value we want to set the is_active field.
164 *
165 * @return bool
166 * true if we found and updated the object, else false
167 */
168 public static function setIsActive($id, $is_active) {
169 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
170 }
171
172 /**
173 * Retrieve the default payment processor.
174 *
175 * @return CRM_Financial_DAO_PaymentProcessor|null
176 * The default payment processor object on success,
177 * null otherwise
178 */
179 public static function &getDefault() {
180 if (self::$_defaultPaymentProcessor == NULL) {
181 $params = ['is_default' => 1];
182 $defaults = [];
183 self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
184 }
185 return self::$_defaultPaymentProcessor;
186 }
187
188 /**
189 * Delete payment processor.
190 *
191 * @param int $paymentProcessorID
192 *
193 * @return null
194 */
195 public static function del($paymentProcessorID) {
196 if (!$paymentProcessorID) {
197 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
198 }
199
200 $dao = new CRM_Financial_DAO_PaymentProcessor();
201 $dao->id = $paymentProcessorID;
202 if (!$dao->find(TRUE)) {
203 return NULL;
204 }
205
206 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
207 $testDAO->name = $dao->name;
208 $testDAO->is_test = 1;
209 $testDAO->delete();
210
211 $dao->delete();
212 Civi\Payment\System::singleton()->flushProcessors();
213 }
214
215 /**
216 * Get the payment processor details.
217 *
218 * This returns an array whereas Civi\Payment\System::singleton->getByID() returns an object.
219 * The object is a key in the array.
220 *
221 * @param int $paymentProcessorID
222 * Payment processor id.
223 * @param string $mode
224 * Payment mode ie test or live.
225 *
226 * @return array
227 * associated array with payment processor related fields
228 */
229 public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
230 $capabilities = ($mode == 'test') ? ['TestMode'] : [];
231 $processors = self::getPaymentProcessors($capabilities, [$paymentProcessorID]);
232 return $processors[$paymentProcessorID];
233 }
234
235 /**
236 * Given a live processor ID get the test id.
237 *
238 * @param int $id
239 *
240 * @return int
241 * Test payment processor ID.
242 */
243 public static function getTestProcessorId($id) {
244 $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', [
245 'id' => $id,
246 'return' => 'name',
247 ]);
248 return civicrm_api3('payment_processor', 'getvalue', [
249 'return' => 'id',
250 'name' => $liveProcessorName,
251 'is_test' => 1,
252 'domain_id' => CRM_Core_Config::domainID(),
253 ]);
254 }
255
256 /**
257 * Compare 2 payment processors to see which should go first based on is_default
258 * (sort function for sortDefaultFirst)
259 * @param array $processor1
260 * @param array $processor2
261 *
262 * @return int
263 */
264 public static function defaultComparison($processor1, $processor2) {
265 $p1 = CRM_Utils_Array::value('is_default', $processor1);
266 $p2 = CRM_Utils_Array::value('is_default', $processor2);
267 if ($p1 == $p2) {
268 return 0;
269 }
270 return ($p1 > $p2) ? -1 : 1;
271 }
272
273 /**
274 * Get all payment processors as an array of objects.
275 *
276 * @param string|NULL $mode
277 * only return this mode - test|live or NULL for all
278 * @param bool $reset
279 * @param bool $isCurrentDomainOnly
280 * Do we only want to load payment processors associated with the current domain.
281 *
282 * @throws CiviCRM_API3_Exception
283 * @return array
284 */
285 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE) {
286
287 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config::domainID();
288 if (!$reset) {
289 $processors = CRM_Utils_Cache::singleton()->get($cacheKey);
290 if (!empty($processors)) {
291 return $processors;
292 }
293 }
294
295 $retrievalParameters = [
296 'is_active' => TRUE,
297 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
298 'api.payment_processor_type.getsingle' => 1,
299 ];
300 if ($isCurrentDomainOnly) {
301 $retrievalParameters['domain_id'] = CRM_Core_Config::domainID();
302 }
303 if ($mode == 'test') {
304 $retrievalParameters['is_test'] = 1;
305 }
306 elseif ($mode == 'live') {
307 $retrievalParameters['is_test'] = 0;
308 }
309
310 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
311 foreach ($processors['values'] as $processor) {
312 $fieldsToProvide = [
313 'id',
314 'name',
315 'payment_processor_type_id',
316 'user_name',
317 'password',
318 'signature',
319 'url_site',
320 'url_api',
321 'url_recur',
322 'url_button',
323 'subject',
324 'class_name',
325 'is_recur',
326 'billing_mode',
327 'is_test',
328 'payment_type',
329 'is_default',
330 ];
331 foreach ($fieldsToProvide as $field) {
332 // Prevent e-notices in processor classes when not configured.
333 if (!isset($processor[$field])) {
334 $processors['values'][$processor['id']][$field] = NULL;
335 }
336 }
337 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
338 $processors['values'][$processor['id']]['object'] = Civi\Payment\System::singleton()->getByProcessor($processors['values'][$processor['id']]);
339 }
340
341 // Add the pay-later pseudo-processor.
342 $processors['values'][0] = [
343 'object' => new CRM_Core_Payment_Manual(),
344 'id' => 0,
345 'payment_processor_type_id' => 0,
346 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
347 'payment_processor_type' => 'Manual',
348 'class_name' => 'Payment_Manual',
349 'name' => 'pay_later',
350 'billing_mode' => '',
351 'is_default' => 0,
352 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')),
353 // Making this optionally recur would give lots of options -but it should
354 // be a row in the payment processor table before we do that.
355 'is_recur' => FALSE,
356 'is_test' => FALSE,
357 ];
358
359 CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']);
360
361 return $processors['values'];
362 }
363
364 /**
365 * Get Payment processors with specified capabilities.
366 * Note that both the singleton & the pseudoconstant function have caching so we don't add
367 * arguably this could go on the pseudoconstant class
368 *
369 * @param array $capabilities
370 * capabilities of processor e.g
371 * - BackOffice
372 * - TestMode
373 * - LiveMode
374 * - FutureStartDate
375 *
376 * @param array|bool $ids
377 *
378 * @return array
379 * available processors
380 */
381 public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
382 if (is_array($ids)) {
383 $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : [];
384 $processors = self::getAllPaymentProcessors('all', FALSE, FALSE);
385 if (in_array('TestMode', $capabilities)) {
386 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
387 foreach ($possibleLiveIDs as $possibleLiveID) {
388 if (isset($processors[$possibleLiveID]) && ($liveProcessorName = $processors[$possibleLiveID]['name']) != FALSE) {
389 foreach ($testProcessors as $index => $testProcessor) {
390 if ($testProcessor['name'] == $liveProcessorName) {
391 $ids[] = $testProcessor['id'];
392 }
393 }
394 }
395 }
396 $processors = $testProcessors;
397 }
398 }
399 else {
400 $processors = self::getAllPaymentProcessors('all');
401 }
402
403 foreach ($processors as $index => $processor) {
404 if (is_array($ids) && !in_array($processor['id'], $ids)) {
405 unset($processors[$index]);
406 continue;
407 }
408 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
409 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
410 if (!is_a($processor['object'], 'CRM_Core_Payment')) {
411 unset($processors[$index]);
412 continue;
413 }
414 foreach ($capabilities as $capability) {
415 if (($processor['object']->supports($capability)) == FALSE) {
416 unset($processors[$index]);
417 continue 1;
418 }
419 }
420 }
421
422 return $processors;
423 }
424
425 /**
426 * Is there a processor on this site with the specified capability.
427 *
428 * The capabilities are defined on CRM_Core_Payment and can be extended by
429 * processors.
430 *
431 * examples are
432 * - supportsBackOffice
433 * - supportsLiveMode
434 * - supportsFutureRecurDate
435 * - supportsRecurring
436 * - supportsCancelRecurring
437 * - supportsRecurContributionsForPledges
438 *
439 * They are passed as array('BackOffice');
440 *
441 * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
442 *
443 * @param array $capabilities
444 *
445 * @return bool
446 */
447 public static function hasPaymentProcessorSupporting($capabilities = []) {
448 $capabilitiesString = implode('', $capabilities);
449 if (!isset(\Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString])) {
450 $result = self::getPaymentProcessors($capabilities);
451 \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]) ? TRUE : FALSE;
452 }
453 return \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString];
454 }
455
456 /**
457 * Retrieve payment processor id / info/ object based on component-id.
458 *
459 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
460 * that are entity specific as there is little shared code specific to obj or info
461 *
462 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
463 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
464 *
465 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
466 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
467 * no way to derive the processor - but hey - what processor? it didn't go through!
468 *
469 * Query for membership might look something like:
470 * SELECT fte.payment_processor_id
471 * FROM civicrm_membership mem
472 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
473 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
474 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
475 * 'civicrm_contribution'
476 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
477 *
478 * @param int $entityID
479 * @param string $component
480 * Component.
481 * @param string $type
482 * Type of payment information to be retrieved.
483 *
484 * @return int|array|object
485 */
486 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
487 $result = NULL;
488 if (!in_array($component, [
489 'membership',
490 'contribute',
491 'recur',
492 ])
493 ) {
494 return $result;
495 }
496
497 if ($component == 'membership') {
498 $sql = "
499 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
500 FROM civicrm_membership mem
501 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
502 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
503 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
504 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
505 WHERE mp.membership_id = %1";
506 }
507 elseif ($component == 'contribute') {
508 $sql = "
509 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
510 FROM civicrm_contribution con
511 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
512 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
513 WHERE con.id = %1";
514 }
515 elseif ($component == 'recur') {
516 // @deprecated - use getPaymentProcessorForRecurringContribution.
517 $sql = "
518 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
519 FROM civicrm_contribution_recur cr
520 WHERE cr.id = %1";
521 }
522
523 // We are interested in a single record.
524 $sql .= ' LIMIT 1';
525
526 $params = [1 => [$entityID, 'Integer']];
527 $dao = CRM_Core_DAO::executeQuery($sql, $params);
528
529 if (!$dao->fetch()) {
530
531 return $result;
532
533 }
534
535 $ppID = (isset($dao->ppID1) && $dao->ppID1) ? $dao->ppID1 : (isset($dao->ppID2) ? $dao->ppID2 : NULL);
536 $mode = (isset($dao->is_test) && $dao->is_test) ? 'test' : 'live';
537 if (!$ppID || $type == 'id') {
538 $result = $ppID;
539 }
540 elseif ($type == 'info') {
541 $result = self::getPayment($ppID, $mode);
542 }
543 elseif ($type == 'obj' && is_numeric($ppID)) {
544 try {
545 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
546 }
547 catch (API_Exception $e) {
548 // Unable to load the processor because this function uses an unreliable method to derive it.
549 // The function looks to load the payment processor ID from the contribution page, which
550 // can support multiple processors.
551 }
552
553 $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
554 $result = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
555 }
556 return $result;
557 }
558
559 /**
560 * Get the payment processor associated with a recurring contribution series.
561 *
562 * @param int $contributionRecurID
563 *
564 * @return \CRM_Core_Payment
565 */
566 public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
567 $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
568 'id' => $contributionRecurID,
569 'return' => 'payment_processor_id',
570 ]);
571 return Civi\Payment\System::singleton()->getById($paymentProcessorId);
572 }
573
574 /**
575 * Get the name of the payment processor
576 *
577 * @param $paymentProcessorId
578 *
579 * @return null|string
580 */
581 public static function getPaymentProcessorName($paymentProcessorId) {
582 try {
583 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
584 'return' => ['name'],
585 'id' => $paymentProcessorId,
586 ]);
587 return $paymentProcessor['name'];
588 }
589 catch (Exception $e) {
590 return ts('Unknown') . ' (' . $paymentProcessorId . ')';
591 }
592 }
593
594 /**
595 * Generate and assign an arbitrary value to a field of a test object.
596 *
597 * @param string $fieldName
598 * @param array $fieldDef
599 * @param int $counter
600 * The globally-unique ID of the test object.
601 */
602 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
603 if ($fieldName === 'class_name') {
604 $this->class_name = 'Payment_Dummy';
605 }
606 else {
607 parent::assignTestValue($fieldName, $fieldDef, $counter);
608 }
609 }
610
611 /**
612 * Get the default financial account id for payment processor accounts.
613 *
614 * Note that there is only a 'name' field & no label field. If people customise
615 * name then this won't work. This is new best-effort functionality so that's non-regressive.
616 *
617 * The fix for that is to add a label value to the financial account table.
618 */
619 public static function getDefaultFinancialAccountID() {
620 return CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');
621 }
622
623 }