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