Merge pull request #17706 from demeritcowboy/mysql-ssl-alt
[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 throw new CRM_Core_Exception(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 throw new CRM_Core_Exception(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 = $processor1['is_default'] ?? NULL;
266 $p2 = $processor2['is_default'] ?? NULL;
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 * @param bool|NULL $isActive
282 * Do we only want active processors, only inactive (FALSE) or all processors (NULL)
283 *
284 * @throws CiviCRM_API3_Exception
285 * @return array
286 */
287 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE, $isActive = TRUE) {
288
289 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config::domainID();
290 if (!$reset) {
291 $processors = CRM_Utils_Cache::singleton()->get($cacheKey);
292 if (!empty($processors)) {
293 return $processors;
294 }
295 }
296
297 $retrievalParameters = [
298 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
299 'api.payment_processor_type.getsingle' => 1,
300 ];
301 if (isset($isActive)) {
302 // We use isset because we don't want to set the is_active parameter at all is $isActive is NULL
303 $retrievalParameters['is_active'] = $isActive;
304 }
305 if ($isCurrentDomainOnly) {
306 $retrievalParameters['domain_id'] = CRM_Core_Config::domainID();
307 }
308 if ($mode == 'test') {
309 $retrievalParameters['is_test'] = 1;
310 }
311 elseif ($mode == 'live') {
312 $retrievalParameters['is_test'] = 0;
313 }
314
315 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
316 foreach ($processors['values'] as $processor) {
317 $fieldsToProvide = [
318 'id',
319 'name',
320 'payment_processor_type_id',
321 'user_name',
322 'password',
323 'signature',
324 'url_site',
325 'url_api',
326 'url_recur',
327 'url_button',
328 'subject',
329 'class_name',
330 'is_recur',
331 'billing_mode',
332 'is_test',
333 'payment_type',
334 'is_default',
335 ];
336 foreach ($fieldsToProvide as $field) {
337 // Prevent e-notices in processor classes when not configured.
338 if (!isset($processor[$field])) {
339 $processors['values'][$processor['id']][$field] = NULL;
340 }
341 }
342 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
343 $processors['values'][$processor['id']]['object'] = Civi\Payment\System::singleton()->getByProcessor($processors['values'][$processor['id']]);
344 }
345
346 // Add the pay-later pseudo-processor.
347 $processors['values'][0] = [
348 'object' => new CRM_Core_Payment_Manual(),
349 'id' => 0,
350 'payment_processor_type_id' => 0,
351 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
352 'payment_processor_type' => 'Manual',
353 'class_name' => 'Payment_Manual',
354 'name' => 'pay_later',
355 'billing_mode' => '',
356 'is_default' => 0,
357 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')),
358 // Making this optionally recur would give lots of options -but it should
359 // be a row in the payment processor table before we do that.
360 'is_recur' => FALSE,
361 'is_test' => FALSE,
362 ];
363
364 CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']);
365
366 return $processors['values'];
367 }
368
369 /**
370 * Get Payment processors with specified capabilities.
371 * Note that both the singleton & the pseudoconstant function have caching so we don't add
372 * arguably this could go on the pseudoconstant class
373 *
374 * @param array $capabilities
375 * capabilities of processor e.g
376 * - BackOffice
377 * - TestMode
378 * - LiveMode
379 * - FutureStartDate
380 *
381 * @param array|bool $ids
382 *
383 * @return array
384 * available processors
385 *
386 * @throws \CiviCRM_API3_Exception
387 */
388 public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
389 if (is_array($ids)) {
390 if (in_array('TestMode', $capabilities, TRUE)) {
391 $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : [];
392 $allProcessors = self::getAllPaymentProcessors('all', FALSE, FALSE, NULL);
393 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
394 foreach ($possibleLiveIDs as $possibleLiveID) {
395 if (isset($allProcessors[$possibleLiveID]) && ($liveProcessorName = $allProcessors[$possibleLiveID]['name']) != FALSE) {
396 foreach ($testProcessors as $index => $testProcessor) {
397 if ($testProcessor['name'] === $liveProcessorName) {
398 $ids[] = $testProcessor['id'];
399 }
400 }
401 }
402 }
403 $processors = $testProcessors;
404 }
405 else {
406 $processors = self::getAllPaymentProcessors('all', FALSE, FALSE);
407 }
408 }
409 else {
410 $processors = self::getAllPaymentProcessors('all');
411 }
412
413 foreach ($processors as $index => $processor) {
414 if (is_array($ids) && !in_array($processor['id'], $ids)) {
415 unset($processors[$index]);
416 continue;
417 }
418 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
419 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
420 if (!$processor['object'] instanceof \CRM_Core_Payment) {
421 unset($processors[$index]);
422 continue;
423 }
424 foreach ($capabilities as $capability) {
425 if (($processor['object']->supports($capability)) == FALSE) {
426 unset($processors[$index]);
427 continue 1;
428 }
429 }
430 }
431
432 return $processors;
433 }
434
435 /**
436 * Is there a processor on this site with the specified capability.
437 *
438 * The capabilities are defined on CRM_Core_Payment and can be extended by
439 * processors.
440 *
441 * examples are
442 * - supportsBackOffice
443 * - supportsLiveMode
444 * - supportsFutureRecurDate
445 * - supportsRecurring
446 * - supportsCancelRecurring
447 * - supportsRecurContributionsForPledges
448 *
449 * They are passed as array('BackOffice');
450 *
451 * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
452 *
453 * @param array $capabilities
454 *
455 * @return bool
456 */
457 public static function hasPaymentProcessorSupporting($capabilities = []) {
458 $capabilitiesString = implode('', $capabilities);
459 if (!isset(\Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString])) {
460 $result = self::getPaymentProcessors($capabilities);
461 \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]);
462 }
463 return \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString];
464 }
465
466 /**
467 * Retrieve payment processor id / info/ object based on component-id.
468 *
469 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
470 * that are entity specific as there is little shared code specific to obj or info
471 *
472 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
473 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
474 *
475 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
476 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
477 * no way to derive the processor - but hey - what processor? it didn't go through!
478 *
479 * Query for membership might look something like:
480 * SELECT fte.payment_processor_id
481 * FROM civicrm_membership mem
482 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
483 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
484 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
485 * 'civicrm_contribution'
486 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
487 *
488 * @param int $entityID
489 * @param string $component
490 * Component.
491 * @param string $type
492 * Type of payment information to be retrieved.
493 *
494 * @return int|array|object
495 */
496 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
497 $result = NULL;
498 if (!in_array($component, [
499 'membership',
500 'contribute',
501 'recur',
502 ])
503 ) {
504 return $result;
505 }
506
507 if ($component == 'membership') {
508 $sql = "
509 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
510 FROM civicrm_membership mem
511 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
512 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
513 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
514 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
515 WHERE mp.membership_id = %1";
516 }
517 elseif ($component == 'contribute') {
518 $sql = "
519 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
520 FROM civicrm_contribution con
521 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
522 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
523 WHERE con.id = %1";
524 }
525 elseif ($component == 'recur') {
526 // @deprecated - use getPaymentProcessorForRecurringContribution.
527 $sql = "
528 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
529 FROM civicrm_contribution_recur cr
530 WHERE cr.id = %1";
531 }
532
533 // We are interested in a single record.
534 $sql .= ' LIMIT 1';
535
536 $params = [1 => [$entityID, 'Integer']];
537 $dao = CRM_Core_DAO::executeQuery($sql, $params);
538
539 if (!$dao->fetch()) {
540
541 return $result;
542
543 }
544
545 $ppID = (isset($dao->ppID1) && $dao->ppID1) ? $dao->ppID1 : ($dao->ppID2 ?? NULL);
546 $mode = (isset($dao->is_test) && $dao->is_test) ? 'test' : 'live';
547 if (!$ppID || $type == 'id') {
548 $result = $ppID;
549 }
550 elseif ($type == 'info') {
551 $result = self::getPayment($ppID, $mode);
552 }
553 elseif ($type == 'obj' && is_numeric($ppID)) {
554 try {
555 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
556 }
557 catch (API_Exception $e) {
558 // Unable to load the processor because this function uses an unreliable method to derive it.
559 // The function looks to load the payment processor ID from the contribution page, which
560 // can support multiple processors.
561 }
562
563 $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
564 $result = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
565 }
566 return $result;
567 }
568
569 /**
570 * Get the payment processor associated with a recurring contribution series.
571 *
572 * @param int $contributionRecurID
573 *
574 * @return \CRM_Core_Payment
575 */
576 public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
577 $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
578 'id' => $contributionRecurID,
579 'return' => 'payment_processor_id',
580 ]);
581 return Civi\Payment\System::singleton()->getById($paymentProcessorId);
582 }
583
584 /**
585 * Get the name of the payment processor
586 *
587 * @param $paymentProcessorId
588 *
589 * @return null|string
590 */
591 public static function getPaymentProcessorName($paymentProcessorId) {
592 try {
593 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
594 'return' => ['name'],
595 'id' => $paymentProcessorId,
596 ]);
597 return $paymentProcessor['name'];
598 }
599 catch (Exception $e) {
600 return ts('Unknown') . ' (' . $paymentProcessorId . ')';
601 }
602 }
603
604 /**
605 * Generate and assign an arbitrary value to a field of a test object.
606 *
607 * @param string $fieldName
608 * @param array $fieldDef
609 * @param int $counter
610 * The globally-unique ID of the test object.
611 */
612 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
613 if ($fieldName === 'class_name') {
614 $this->class_name = 'Payment_Dummy';
615 }
616 else {
617 parent::assignTestValue($fieldName, $fieldDef, $counter);
618 }
619 }
620
621 /**
622 * Get the default financial account id for payment processor accounts.
623 *
624 * Note that there is only a 'name' field & no label field. If people customise
625 * name then this won't work. This is new best-effort functionality so that's non-regressive.
626 *
627 * The fix for that is to add a label value to the financial account table.
628 */
629 public static function getDefaultFinancialAccountID() {
630 return CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');
631 }
632
633 }