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