Merge pull request #9769 from scardinius/crm-19958
[civicrm-core.git] / CRM / Financial / BAO / PaymentProcessor.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33
34/**
35 * This class contains payment processor related functions.
36 */
d3e86119 37class CRM_Financial_BAO_PaymentProcessor extends CRM_Financial_DAO_PaymentProcessor {
6a488035 38 /**
100fef9d 39 * Static holder for the default payment processor
6a488035
TO
40 */
41 static $_defaultPaymentProcessor = NULL;
42
c490a46a 43 /**
fe482240 44 * Create Payment Processor.
6a488035 45 *
ed5dd492
TO
46 * @param array $params
47 * Parameters for Processor entity.
e0ef6999
EM
48 *
49 * @return CRM_Financial_DAO_PaymentProcessor
50 * @throws Exception
51 */
00be9182 52 public static function create($params) {
6a488035
TO
53 $processor = new CRM_Financial_DAO_PaymentProcessor();
54 $processor->copyValues($params);
55
56 $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
57 $ppTypeDAO->id = $params['payment_processor_type_id'];
58 if (!$ppTypeDAO->find(TRUE)) {
59 CRM_Core_Error::fatal(ts('Could not find payment processor meta information'));
60 }
61
62 // also copy meta fields from the info DAO
63 $processor->is_recur = $ppTypeDAO->is_recur;
64 $processor->billing_mode = $ppTypeDAO->billing_mode;
65 $processor->class_name = $ppTypeDAO->class_name;
66 $processor->payment_type = $ppTypeDAO->payment_type;
67
68 $processor->save();
03e04002 69 // CRM-11826, add entry in civicrm_entity_financial_account
6a488035 70 // if financial_account_id is not NULL
a7488080 71 if (!empty($params['financial_account_id'])) {
f743a6eb 72 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
6a488035
TO
73 $values = array(
74 'entity_table' => 'civicrm_payment_processor',
75 'entity_id' => $processor->id,
76 'account_relationship' => $relationTypeId,
21dfd5f5 77 'financial_account_id' => $params['financial_account_id'],
6a488035 78 );
03e04002 79 CRM_Financial_BAO_FinancialTypeAccount::add($values);
6a488035 80 }
b7e7f943 81
d6944518 82 Civi\Payment\System::singleton()->flushProcessors();
6a488035
TO
83 return $processor;
84 }
85
86 /**
fe482240 87 * Class constructor.
6a488035 88 */
00be9182 89 public function __construct() {
6a488035
TO
90 parent::__construct();
91 }
92
cb5962bd 93 /**
c294dbbc 94 * Retrieve array of allowed credit cards for this payment processor.
cb5962bd
SL
95 * @param interger|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 array();
107 }
108
6a488035 109 /**
fe482240
EM
110 * Retrieve DB object based on input parameters.
111 *
112 * It also stores all the retrieved values in the default array.
6a488035 113 *
ed5dd492
TO
114 * @param array $params
115 * (reference ) an assoc array of name/value pairs.
116 * @param array $defaults
117 * (reference ) an assoc array to hold the flattened values.
6a488035 118 *
16b10e64
CW
119 * @return CRM_Financial_DAO_PaymentProcessor|null
120 * object on success, null otherwise
6a488035 121 */
00be9182 122 public static function retrieve(&$params, &$defaults) {
6a488035
TO
123 $paymentProcessor = new CRM_Financial_DAO_PaymentProcessor();
124 $paymentProcessor->copyValues($params);
125 if ($paymentProcessor->find(TRUE)) {
126 CRM_Core_DAO::storeValues($paymentProcessor, $defaults);
127 return $paymentProcessor;
128 }
129 return NULL;
130 }
131
132 /**
fe482240 133 * Update the is_active flag in the db.
6a488035 134 *
ed5dd492
TO
135 * @param int $id
136 * Id of the database record.
137 * @param bool $is_active
138 * Value we want to set the is_active field.
6a488035 139 *
16b10e64
CW
140 * @return CRM_Financial_DAO_PaymentProcessor|null
141 * DAO object on success, null otherwise
6a488035 142 *
6a488035 143 */
00be9182 144 public static function setIsActive($id, $is_active) {
6a488035
TO
145 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
146 }
147
148 /**
fe482240 149 * Retrieve the default payment processor.
6a488035 150 *
16b10e64 151 * @return CRM_Financial_DAO_PaymentProcessor|null
a6c01b45 152 * The default payment processor object on success,
16b10e64 153 * null otherwise
6a488035 154 */
00be9182 155 public static function &getDefault() {
6a488035
TO
156 if (self::$_defaultPaymentProcessor == NULL) {
157 $params = array('is_default' => 1);
158 $defaults = array();
159 self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
160 }
161 return self::$_defaultPaymentProcessor;
162 }
163
164 /**
fe482240 165 * Delete payment processor.
6a488035 166 *
c490a46a 167 * @param int $paymentProcessorID
77b97be7
EM
168 *
169 * @return null
6a488035 170 */
00be9182 171 public static function del($paymentProcessorID) {
6a488035 172 if (!$paymentProcessorID) {
1f21f2cf 173 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
6a488035
TO
174 }
175
176 $dao = new CRM_Financial_DAO_PaymentProcessor();
177 $dao->id = $paymentProcessorID;
178 if (!$dao->find(TRUE)) {
179 return NULL;
180 }
181
182 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
183 $testDAO->name = $dao->name;
184 $testDAO->is_test = 1;
185 $testDAO->delete();
186
187 $dao->delete();
d6944518 188 Civi\Payment\System::singleton()->flushProcessors();
6a488035
TO
189 }
190
191 /**
fe482240 192 * Get the payment processor details.
6a488035 193 *
9d8f43b1
EM
194 * This returns an array whereas Civi\Payment\System::singleton->getByID() returns an object.
195 * The object is a key in the array.
2c5311b9 196 *
ed5dd492
TO
197 * @param int $paymentProcessorID
198 * Payment processor id.
199 * @param string $mode
200 * Payment mode ie test or live.
6a488035 201 *
a6c01b45
CW
202 * @return array
203 * associated array with payment processor related fields
6a488035 204 */
aaff4c69 205 public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
9d8f43b1
EM
206 $capabilities = ($mode == 'test') ? array('TestMode') : array();
207 $processors = self::getPaymentProcessors($capabilities, array($paymentProcessorID));
208 $processor = $processors[$paymentProcessorID];
209 $fields = array(
210 'id',
211 'name',
212 'payment_processor_type_id',
213 'user_name',
214 'password',
215 'signature',
216 'url_site',
217 'url_api',
218 'url_recur',
219 'url_button',
220 'subject',
221 'class_name',
222 'is_recur',
223 'billing_mode',
224 'is_test',
225 'payment_type',
226 'is_default',
227 );
228 // Just to prevent e-Notices elsewhere we set all fields.
229 foreach ($fields as $name) {
230 if (!isset($processor)) {
231 $processor[$name] = NULL;
6a488035 232 }
6a488035 233 }
9d8f43b1
EM
234 $processor['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE,
235 $processor['payment_processor_type_id'], 'name');
236 return $processors[$paymentProcessorID];
6a488035
TO
237 }
238
428e38a4
EM
239 /**
240 * Given a live processor ID get the test id.
241 *
242 * @param int $id
243 *
244 * @return int
245 * Test payment processor ID.
246 */
247 public static function getTestProcessorId($id) {
248 $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', array(
249 'id' => $id,
250 'return' => 'name',
251 ));
252 return civicrm_api3('payment_processor', 'getvalue', array(
253 'return' => 'id',
254 'name' => $liveProcessorName,
255 'domain_id' => CRM_Core_Config::domainID(),
256 ));
257 }
258
13ac605f 259 /**
100fef9d 260 * Compare 2 payment processors to see which should go first based on is_default
13ac605f
DG
261 * (sort function for sortDefaultFirst)
262 * @param array $processor1
16b10e64 263 * @param array $processor2
79d7553f 264 *
265 * @return int
13ac605f 266 */
9b873358 267 public static function defaultComparison($processor1, $processor2) {
045f52a3
TO
268 $p1 = CRM_Utils_Array::value('is_default', $processor1);
269 $p2 = CRM_Utils_Array::value('is_default', $processor2);
270 if ($p1 == $p2) {
271 return 0;
13ac605f 272 }
045f52a3
TO
273 return ($p1 > $p2) ? -1 : 1;
274 }
13ac605f 275
fbcb6fba 276 /**
100fef9d 277 * Get all payment processors as an array of objects.
fbcb6fba 278 *
52767de0
EM
279 * @param string|NULL $mode
280 * only return this mode - test|live or NULL for all
fbcb6fba
EM
281 * @param bool $reset
282 *
283 * @throws CiviCRM_API3_Exception
284 * @return array
285 */
a160bb08 286 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
7036a6d0 287
a160bb08 288 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . CRM_Core_Config::domainID();
7036a6d0
EM
289 if (!$reset) {
290 $processors = CRM_Utils_Cache::singleton()->get($cacheKey);
291 if (!empty($processors)) {
292 return $processors;
293 }
294 }
295
353ffa53
TO
296 $retrievalParameters = array(
297 'is_active' => TRUE,
f81ac4f9 298 'domain_id' => CRM_Core_Config::domainID(),
353ffa53 299 'options' => array('sort' => 'is_default DESC, name'),
79d7553f 300 'api.payment_processor_type.getsingle' => 1,
353ffa53 301 );
52767de0
EM
302 if ($mode == 'test') {
303 $retrievalParameters['is_test'] = 1;
304 }
305 elseif ($mode == 'live') {
fbcb6fba
EM
306 $retrievalParameters['is_test'] = 0;
307 }
7036a6d0 308
fbcb6fba
EM
309 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
310 foreach ($processors['values'] as $processor) {
7036a6d0 311 $fieldsToProvide = array('user_name', 'password', 'signature', 'subject', 'is_recur');
52767de0 312 foreach ($fieldsToProvide as $field) {
7036a6d0 313 // Prevent e-notices in processor classes when not configured.
52767de0 314 if (!isset($processor[$field])) {
be74ba34 315 $processors['values'][$processor['id']][$field] = NULL;
52767de0
EM
316 }
317 }
9d91a9c6 318 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
7036a6d0 319 $processors['values'][$processor['id']]['object'] = Civi\Payment\System::singleton()->getByProcessor($processor);
fbcb6fba 320 }
7036a6d0 321
1d1fee72 322 // Add the pay-later pseudo-processor.
323 $processors['values'][0] = array(
f48e6cf7 324 'object' => new CRM_Core_Payment_Manual(),
1d1fee72 325 'id' => 0,
326 'payment_processor_type_id' => 0,
f48e6cf7 327 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
328 'payment_processor_type' => 'Manual',
1d1fee72 329 'class_name' => 'Payment_Manual',
330 'name' => 'pay_later',
331 'billing_mode' => '',
fdf4616e 332 'is_default' => 0,
ecb7ec32 333 // This should ideally be retrieved from the DB but existing default is check so we'll code that for now.
334 'payment_instrument_id' => CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name'),
1d1fee72 335 // Making this optionally recur would give lots of options -but it should
336 // be a row in the payment processor table before we do that.
337 'is_recur' => FALSE,
338 );
339
7036a6d0
EM
340 CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']);
341
fbcb6fba
EM
342 return $processors['values'];
343 }
344
345 /**
100fef9d 346 * Get Payment processors with specified capabilities.
fbcb6fba
EM
347 * Note that both the singleton & the pseudoconstant function have caching so we don't add
348 * arguably this could go on the pseudoconstant class
349 *
350 * @param array $capabilities
16b10e64
CW
351 * capabilities of processor e.g
352 * - BackOffice
353 * - TestMode
354 * - LiveMode
355 * - FutureStartDate
fbcb6fba 356 *
93e11927 357 * @param array|bool $ids
dc913073 358 *
a6c01b45
CW
359 * @return array
360 * available processors
fbcb6fba 361 */
93e11927 362 public static function getPaymentProcessors($capabilities = array(), $ids = FALSE) {
52767de0 363 $mode = NULL;
e082c947 364 $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : array();
74b91f33 365 $processors = self::getAllPaymentProcessors('all');
e082c947 366
99459756 367 if (in_array('TestMode', $capabilities) && is_array($ids)) {
74b91f33 368 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
369 foreach ($possibleLiveIDs as $possibleLiveID) {
370 if (isset($processors[$possibleLiveID]) && ($liveProcessorName = $processors[$possibleLiveID]['name']) != FALSE) {
371 foreach ($testProcessors as $index => $testProcessor) {
372 if ($testProcessor['name'] == $liveProcessorName) {
373 $ids[] = $testProcessor['id'];
e082c947 374 }
375 }
376 }
377 }
378 $processors = $testProcessors;
52767de0 379 }
7036a6d0 380
1b9f9ca3 381 foreach ($processors as $index => $processor) {
74b91f33 382 if (is_array($ids) && !in_array($processor['id'], $ids)) {
1b9f9ca3
EM
383 unset ($processors[$index]);
384 continue;
385 }
386 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
387 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
388 if (!is_a($processor['object'], 'CRM_Core_Payment')) {
389 unset ($processors[$index]);
390 continue;
391 }
392 foreach ($capabilities as $capability) {
393 if (($processor['object']->supports($capability)) == FALSE) {
fbcb6fba 394 unset ($processors[$index]);
1b9f9ca3 395 continue 1;
fbcb6fba
EM
396 }
397 }
398 }
1b9f9ca3 399
fbcb6fba
EM
400 return $processors;
401 }
402
403 /**
fe482240 404 * Is there a processor on this site with the specified capability.
c1f95567 405 *
406 * The capabilities are defined on CRM_Core_Payment and can be extended by
407 * processors.
408 *
409 * examples are
410 * - supportsBackOffice
411 * - supportsLiveMode
412 * - supportsFutureRecurDate
413 * - supportsCancelRecurring
414 * - supportsRecurContributionsForPledges
415 *
416 * They are passed as array('BackOffice');
417 *
418 * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
419 *
fbcb6fba 420 * @param array $capabilities
fbcb6fba
EM
421 *
422 * @return bool
423 */
fb674ca9 424 public static function hasPaymentProcessorSupporting($capabilities = array()) {
52767de0 425 $result = self::getPaymentProcessors($capabilities);
fbcb6fba
EM
426 return (!empty($result)) ? TRUE : FALSE;
427 }
428
6a488035 429 /**
100fef9d 430 * Retrieve payment processor id / info/ object based on component-id.
6a488035 431 *
0bd096e8 432 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
433 * that are entity specific as there is little shared code specific to obj or info
434 *
435 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
436 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
437 *
438 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
439 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
440 * no way to derive the processor - but hey - what processor? it didn't go through!
441 *
442 * Query for membership might look something like:
443 * SELECT fte.payment_processor_id
444 * FROM civicrm_membership mem
445 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
446 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
447 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
448 * 'civicrm_contribution'
449 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
450 *
100fef9d 451 * @param int $entityID
ed5dd492
TO
452 * @param string $component
453 * Component.
454 * @param string $type
455 * Type of payment information to be retrieved.
6a488035 456 *
16b10e64 457 * @return int|array|object
6a488035 458 */
00be9182 459 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
6a488035
TO
460 $result = NULL;
461 if (!in_array($component, array(
353ffa53
TO
462 'membership',
463 'contribute',
79d7553f 464 'recur',
353ffa53
TO
465 ))
466 ) {
6a488035
TO
467 return $result;
468 }
cded2ebf 469
6a488035
TO
470 if ($component == 'membership') {
471 $sql = "
472 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
473 FROM civicrm_membership mem
474INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
475INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
476 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
477 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
478 WHERE mp.membership_id = %1";
479 }
480 elseif ($component == 'contribute') {
481 $sql = "
482 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
483 FROM civicrm_contribution con
484 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
485 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
486 WHERE con.id = %1";
487 }
488 elseif ($component == 'recur') {
489 $sql = "
490 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
491 FROM civicrm_contribution_recur cr
492 WHERE cr.id = %1";
493 }
494
cded2ebf 495 // We are interested in a single record.
6a488035
TO
496 $sql .= ' LIMIT 1';
497
498 $params = array(1 => array($entityID, 'Integer'));
499 $dao = CRM_Core_DAO::executeQuery($sql, $params);
500
501 if (!$dao->fetch()) {
502
503 return $result;
504
505 }
506
507 $ppID = (isset($dao->ppID1) && $dao->ppID1) ? $dao->ppID1 : (isset($dao->ppID2) ? $dao->ppID2 : NULL);
508 $mode = (isset($dao->is_test) && $dao->is_test) ? 'test' : 'live';
509 if (!$ppID || $type == 'id') {
510 $result = $ppID;
511 }
512 elseif ($type == 'info') {
513 $result = self::getPayment($ppID, $mode);
514 }
0bd096e8 515 elseif ($type == 'obj' && is_numeric($ppID)) {
516 try {
517 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', array('id' => $ppID));
518 }
519 catch (API_Exception $e) {
520 // Unable to load the processor because this function uses an unreliable method to derive it.
521 // The function looks to load the payment processor ID from the contribution page, which
522 // can support multiple processors.
523 }
524 $result = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
6a488035 525 }
6a488035
TO
526 return $result;
527 }
96025800 528
6a488035 529}