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