Merge remote-tracking branch 'origin/4.6' into 4.6-master-2015-08-03-16-00-35
[civicrm-core.git] / CRM / Financial / BAO / PaymentProcessor.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
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 // FIXME Reconcile with CRM_Admin_Form_PaymentProcessor::updatePaymentProcessor
54 $processor = new CRM_Financial_DAO_PaymentProcessor();
55 $processor->copyValues($params);
56
57 $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
58 $ppTypeDAO->id = $params['payment_processor_type_id'];
59 if (!$ppTypeDAO->find(TRUE)) {
60 CRM_Core_Error::fatal(ts('Could not find payment processor meta information'));
61 }
62
63 // also copy meta fields from the info DAO
64 $processor->is_recur = $ppTypeDAO->is_recur;
65 $processor->billing_mode = $ppTypeDAO->billing_mode;
66 $processor->class_name = $ppTypeDAO->class_name;
67 $processor->payment_type = $ppTypeDAO->payment_type;
68
69 $processor->save();
03e04002 70 // CRM-11826, add entry in civicrm_entity_financial_account
6a488035 71 // if financial_account_id is not NULL
a7488080 72 if (!empty($params['financial_account_id'])) {
f743a6eb 73 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
6a488035
TO
74 $values = array(
75 'entity_table' => 'civicrm_payment_processor',
76 'entity_id' => $processor->id,
77 'account_relationship' => $relationTypeId,
21dfd5f5 78 'financial_account_id' => $params['financial_account_id'],
6a488035 79 );
03e04002 80 CRM_Financial_BAO_FinancialTypeAccount::add($values);
6a488035 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
93 /**
fe482240
EM
94 * Retrieve DB object based on input parameters.
95 *
96 * It also stores all the retrieved values in the default array.
6a488035 97 *
ed5dd492
TO
98 * @param array $params
99 * (reference ) an assoc array of name/value pairs.
100 * @param array $defaults
101 * (reference ) an assoc array to hold the flattened values.
6a488035 102 *
16b10e64
CW
103 * @return CRM_Financial_DAO_PaymentProcessor|null
104 * object on success, null otherwise
6a488035 105 */
00be9182 106 public static function retrieve(&$params, &$defaults) {
6a488035
TO
107 $paymentProcessor = new CRM_Financial_DAO_PaymentProcessor();
108 $paymentProcessor->copyValues($params);
109 if ($paymentProcessor->find(TRUE)) {
110 CRM_Core_DAO::storeValues($paymentProcessor, $defaults);
111 return $paymentProcessor;
112 }
113 return NULL;
114 }
115
116 /**
fe482240 117 * Update the is_active flag in the db.
6a488035 118 *
ed5dd492
TO
119 * @param int $id
120 * Id of the database record.
121 * @param bool $is_active
122 * Value we want to set the is_active field.
6a488035 123 *
16b10e64
CW
124 * @return CRM_Financial_DAO_PaymentProcessor|null
125 * DAO object on success, null otherwise
6a488035 126 *
6a488035 127 */
00be9182 128 public static function setIsActive($id, $is_active) {
6a488035
TO
129 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
130 }
131
132 /**
fe482240 133 * Retrieve the default payment processor.
6a488035 134 *
16b10e64 135 * @return CRM_Financial_DAO_PaymentProcessor|null
a6c01b45 136 * The default payment processor object on success,
16b10e64 137 * null otherwise
6a488035 138 */
00be9182 139 public static function &getDefault() {
6a488035
TO
140 if (self::$_defaultPaymentProcessor == NULL) {
141 $params = array('is_default' => 1);
142 $defaults = array();
143 self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
144 }
145 return self::$_defaultPaymentProcessor;
146 }
147
148 /**
fe482240 149 * Delete payment processor.
6a488035 150 *
c490a46a 151 * @param int $paymentProcessorID
77b97be7
EM
152 *
153 * @return null
6a488035 154 */
00be9182 155 public static function del($paymentProcessorID) {
6a488035 156 if (!$paymentProcessorID) {
1f21f2cf 157 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
6a488035
TO
158 }
159
160 $dao = new CRM_Financial_DAO_PaymentProcessor();
161 $dao->id = $paymentProcessorID;
162 if (!$dao->find(TRUE)) {
163 return NULL;
164 }
165
166 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
167 $testDAO->name = $dao->name;
168 $testDAO->is_test = 1;
169 $testDAO->delete();
170
171 $dao->delete();
d6944518 172 Civi\Payment\System::singleton()->flushProcessors();
6a488035
TO
173 }
174
175 /**
fe482240 176 * Get the payment processor details.
6a488035 177 *
9d8f43b1
EM
178 * This returns an array whereas Civi\Payment\System::singleton->getByID() returns an object.
179 * The object is a key in the array.
2c5311b9 180 *
ed5dd492
TO
181 * @param int $paymentProcessorID
182 * Payment processor id.
183 * @param string $mode
184 * Payment mode ie test or live.
6a488035 185 *
a6c01b45
CW
186 * @return array
187 * associated array with payment processor related fields
6a488035 188 */
aaff4c69 189 public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
9d8f43b1
EM
190 $capabilities = ($mode == 'test') ? array('TestMode') : array();
191 $processors = self::getPaymentProcessors($capabilities, array($paymentProcessorID));
192 $processor = $processors[$paymentProcessorID];
193 $fields = array(
194 'id',
195 'name',
196 'payment_processor_type_id',
197 'user_name',
198 'password',
199 'signature',
200 'url_site',
201 'url_api',
202 'url_recur',
203 'url_button',
204 'subject',
205 'class_name',
206 'is_recur',
207 'billing_mode',
208 'is_test',
209 'payment_type',
210 'is_default',
211 );
212 // Just to prevent e-Notices elsewhere we set all fields.
213 foreach ($fields as $name) {
214 if (!isset($processor)) {
215 $processor[$name] = NULL;
6a488035 216 }
6a488035 217 }
9d8f43b1
EM
218 $processor['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE,
219 $processor['payment_processor_type_id'], 'name');
220 return $processors[$paymentProcessorID];
6a488035
TO
221 }
222
428e38a4
EM
223 /**
224 * Given a live processor ID get the test id.
225 *
226 * @param int $id
227 *
228 * @return int
229 * Test payment processor ID.
230 */
231 public static function getTestProcessorId($id) {
232 $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', array(
233 'id' => $id,
234 'return' => 'name',
235 ));
236 return civicrm_api3('payment_processor', 'getvalue', array(
237 'return' => 'id',
238 'name' => $liveProcessorName,
239 'domain_id' => CRM_Core_Config::domainID(),
240 ));
241 }
242
13ac605f 243 /**
100fef9d 244 * Compare 2 payment processors to see which should go first based on is_default
13ac605f
DG
245 * (sort function for sortDefaultFirst)
246 * @param array $processor1
16b10e64 247 * @param array $processor2
79d7553f 248 *
249 * @return int
13ac605f 250 */
9b873358 251 public static function defaultComparison($processor1, $processor2) {
045f52a3
TO
252 $p1 = CRM_Utils_Array::value('is_default', $processor1);
253 $p2 = CRM_Utils_Array::value('is_default', $processor2);
254 if ($p1 == $p2) {
255 return 0;
13ac605f 256 }
045f52a3
TO
257 return ($p1 > $p2) ? -1 : 1;
258 }
13ac605f 259
fbcb6fba 260 /**
100fef9d 261 * Get all payment processors as an array of objects.
fbcb6fba 262 *
52767de0
EM
263 * @param string|NULL $mode
264 * only return this mode - test|live or NULL for all
fbcb6fba
EM
265 * @param bool $reset
266 *
267 * @throws CiviCRM_API3_Exception
268 * @return array
269 */
52767de0 270 public static function getAllPaymentProcessors($mode, $reset = FALSE) {
7036a6d0 271
9e25c297 272 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . ($mode ? 'test' : 'all') . '_' . CRM_Core_Config::domainID();
7036a6d0
EM
273 if (!$reset) {
274 $processors = CRM_Utils_Cache::singleton()->get($cacheKey);
275 if (!empty($processors)) {
276 return $processors;
277 }
278 }
279
353ffa53
TO
280 $retrievalParameters = array(
281 'is_active' => TRUE,
f81ac4f9 282 'domain_id' => CRM_Core_Config::domainID(),
353ffa53 283 'options' => array('sort' => 'is_default DESC, name'),
79d7553f 284 'api.payment_processor_type.getsingle' => 1,
353ffa53 285 );
52767de0
EM
286 if ($mode == 'test') {
287 $retrievalParameters['is_test'] = 1;
288 }
289 elseif ($mode == 'live') {
fbcb6fba
EM
290 $retrievalParameters['is_test'] = 0;
291 }
7036a6d0 292
fbcb6fba
EM
293 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
294 foreach ($processors['values'] as $processor) {
7036a6d0 295 $fieldsToProvide = array('user_name', 'password', 'signature', 'subject', 'is_recur');
52767de0 296 foreach ($fieldsToProvide as $field) {
7036a6d0 297 // Prevent e-notices in processor classes when not configured.
52767de0 298 if (!isset($processor[$field])) {
be74ba34 299 $processors['values'][$processor['id']][$field] = NULL;
52767de0
EM
300 }
301 }
9d91a9c6 302 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
7036a6d0 303 $processors['values'][$processor['id']]['object'] = Civi\Payment\System::singleton()->getByProcessor($processor);
fbcb6fba 304 }
7036a6d0
EM
305
306 CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']);
307
fbcb6fba
EM
308 return $processors['values'];
309 }
310
311 /**
100fef9d 312 * Get Payment processors with specified capabilities.
fbcb6fba
EM
313 * Note that both the singleton & the pseudoconstant function have caching so we don't add
314 * arguably this could go on the pseudoconstant class
315 *
316 * @param array $capabilities
16b10e64
CW
317 * capabilities of processor e.g
318 * - BackOffice
319 * - TestMode
320 * - LiveMode
321 * - FutureStartDate
fbcb6fba 322 *
93e11927 323 * @param array|bool $ids
dc913073 324 *
a6c01b45
CW
325 * @return array
326 * available processors
fbcb6fba 327 */
93e11927 328 public static function getPaymentProcessors($capabilities = array(), $ids = FALSE) {
52767de0 329 $mode = NULL;
e082c947 330 $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : array();
331 $processors = $liveProcessors = self::getAllPaymentProcessors('live');
332
52767de0 333 if (in_array('TestMode', $capabilities)) {
93e11927 334 if ($ids) {
335 foreach ($testProcessors as $testProcessor) {
336 if (!in_array($testProcessor['id'], $ids)) {
337 foreach ($liveProcessors as $liveProcessor) {
338 if ($liveProcessor['name'] == $testProcessor['name']) {
339 $ids[] = $testProcessor['id'];
340 }
e082c947 341 }
342 }
343 }
344 }
345 $processors = $testProcessors;
52767de0 346 }
7036a6d0 347
1b9f9ca3 348 foreach ($processors as $index => $processor) {
93e11927 349 if ($ids && !in_array($processor['id'], $ids)) {
1b9f9ca3
EM
350 unset ($processors[$index]);
351 continue;
352 }
353 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
354 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
355 if (!is_a($processor['object'], 'CRM_Core_Payment')) {
356 unset ($processors[$index]);
357 continue;
358 }
359 foreach ($capabilities as $capability) {
360 if (($processor['object']->supports($capability)) == FALSE) {
fbcb6fba 361 unset ($processors[$index]);
1b9f9ca3 362 continue 1;
fbcb6fba
EM
363 }
364 }
365 }
1b9f9ca3 366
fbcb6fba
EM
367 return $processors;
368 }
369
370 /**
fe482240 371 * Is there a processor on this site with the specified capability.
fbcb6fba 372 * @param array $capabilities
fbcb6fba
EM
373 *
374 * @return bool
375 */
fb674ca9 376 public static function hasPaymentProcessorSupporting($capabilities = array()) {
52767de0 377 $result = self::getPaymentProcessors($capabilities);
fbcb6fba
EM
378 return (!empty($result)) ? TRUE : FALSE;
379 }
380
6a488035 381 /**
100fef9d 382 * Retrieve payment processor id / info/ object based on component-id.
6a488035 383 *
100fef9d 384 * @param int $entityID
ed5dd492
TO
385 * @param string $component
386 * Component.
387 * @param string $type
388 * Type of payment information to be retrieved.
6a488035 389 *
16b10e64 390 * @return int|array|object
6a488035 391 */
00be9182 392 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
6a488035
TO
393 $result = NULL;
394 if (!in_array($component, array(
353ffa53
TO
395 'membership',
396 'contribute',
79d7553f 397 'recur',
353ffa53
TO
398 ))
399 ) {
6a488035
TO
400 return $result;
401 }
402 //FIXME:
403 if ($component == 'membership') {
404 $sql = "
405 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
406 FROM civicrm_membership mem
407INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
408INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
409 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
410 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
411 WHERE mp.membership_id = %1";
412 }
413 elseif ($component == 'contribute') {
414 $sql = "
415 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
416 FROM civicrm_contribution con
417 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
418 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
419 WHERE con.id = %1";
420 }
421 elseif ($component == 'recur') {
422 $sql = "
423 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
424 FROM civicrm_contribution_recur cr
425 WHERE cr.id = %1";
426 }
427
428 //we are interesting in single record.
429 $sql .= ' LIMIT 1';
430
431 $params = array(1 => array($entityID, 'Integer'));
432 $dao = CRM_Core_DAO::executeQuery($sql, $params);
433
434 if (!$dao->fetch()) {
435
436 return $result;
437
438 }
439
440 $ppID = (isset($dao->ppID1) && $dao->ppID1) ? $dao->ppID1 : (isset($dao->ppID2) ? $dao->ppID2 : NULL);
441 $mode = (isset($dao->is_test) && $dao->is_test) ? 'test' : 'live';
442 if (!$ppID || $type == 'id') {
443 $result = $ppID;
444 }
445 elseif ($type == 'info') {
446 $result = self::getPayment($ppID, $mode);
447 }
448 elseif ($type == 'obj') {
449 $payment = self::getPayment($ppID, $mode);
9d8f43b1 450 $result = Civi\Payment\System::singleton()->getByProcessor($payment);
6a488035
TO
451 }
452
453 return $result;
454 }
96025800 455
6a488035 456}