Merge pull request #7260 from futurefirst/master-rest-cid
[civicrm-core.git] / CRM / Financial / BAO / PaymentProcessor.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 */
41 static $_defaultPaymentProcessor = NULL;
42
43 /**
44 * Create Payment Processor.
45 *
46 * @param array $params
47 * Parameters for Processor entity.
48 *
49 * @return CRM_Financial_DAO_PaymentProcessor
50 * @throws Exception
51 */
52 public static function create($params) {
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();
70 // CRM-11826, add entry in civicrm_entity_financial_account
71 // if financial_account_id is not NULL
72 if (!empty($params['financial_account_id'])) {
73 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
74 $values = array(
75 'entity_table' => 'civicrm_payment_processor',
76 'entity_id' => $processor->id,
77 'account_relationship' => $relationTypeId,
78 'financial_account_id' => $params['financial_account_id'],
79 );
80 CRM_Financial_BAO_FinancialTypeAccount::add($values);
81 }
82 Civi\Payment\System::singleton()->flushProcessors();
83 return $processor;
84 }
85
86 /**
87 * Class constructor.
88 */
89 public function __construct() {
90 parent::__construct();
91 }
92
93 /**
94 * Retrieve DB object based on input parameters.
95 *
96 * It also stores all the retrieved values in the default array.
97 *
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.
102 *
103 * @return CRM_Financial_DAO_PaymentProcessor|null
104 * object on success, null otherwise
105 */
106 public static function retrieve(&$params, &$defaults) {
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 /**
117 * Update the is_active flag in the db.
118 *
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.
123 *
124 * @return CRM_Financial_DAO_PaymentProcessor|null
125 * DAO object on success, null otherwise
126 *
127 */
128 public static function setIsActive($id, $is_active) {
129 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
130 }
131
132 /**
133 * Retrieve the default payment processor.
134 *
135 * @return CRM_Financial_DAO_PaymentProcessor|null
136 * The default payment processor object on success,
137 * null otherwise
138 */
139 public static function &getDefault() {
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 /**
149 * Delete payment processor.
150 *
151 * @param int $paymentProcessorID
152 *
153 * @return null
154 */
155 public static function del($paymentProcessorID) {
156 if (!$paymentProcessorID) {
157 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
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();
172 Civi\Payment\System::singleton()->flushProcessors();
173 }
174
175 /**
176 * Get the payment processor details.
177 *
178 * This returns an array whereas Civi\Payment\System::singleton->getByID() returns an object.
179 * The object is a key in the array.
180 *
181 * @param int $paymentProcessorID
182 * Payment processor id.
183 * @param string $mode
184 * Payment mode ie test or live.
185 *
186 * @return array
187 * associated array with payment processor related fields
188 */
189 public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
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;
216 }
217 }
218 $processor['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE,
219 $processor['payment_processor_type_id'], 'name');
220 return $processors[$paymentProcessorID];
221 }
222
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
243 /**
244 * Compare 2 payment processors to see which should go first based on is_default
245 * (sort function for sortDefaultFirst)
246 * @param array $processor1
247 * @param array $processor2
248 *
249 * @return int
250 */
251 public static function defaultComparison($processor1, $processor2) {
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;
256 }
257 return ($p1 > $p2) ? -1 : 1;
258 }
259
260 /**
261 * Get all payment processors as an array of objects.
262 *
263 * @param string|NULL $mode
264 * only return this mode - test|live or NULL for all
265 * @param bool $reset
266 *
267 * @throws CiviCRM_API3_Exception
268 * @return array
269 */
270 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
271
272 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . CRM_Core_Config::domainID();
273 if (!$reset) {
274 $processors = CRM_Utils_Cache::singleton()->get($cacheKey);
275 if (!empty($processors)) {
276 return $processors;
277 }
278 }
279
280 $retrievalParameters = array(
281 'is_active' => TRUE,
282 'domain_id' => CRM_Core_Config::domainID(),
283 'options' => array('sort' => 'is_default DESC, name'),
284 'api.payment_processor_type.getsingle' => 1,
285 );
286 if ($mode == 'test') {
287 $retrievalParameters['is_test'] = 1;
288 }
289 elseif ($mode == 'live') {
290 $retrievalParameters['is_test'] = 0;
291 }
292
293 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
294 foreach ($processors['values'] as $processor) {
295 $fieldsToProvide = array('user_name', 'password', 'signature', 'subject', 'is_recur');
296 foreach ($fieldsToProvide as $field) {
297 // Prevent e-notices in processor classes when not configured.
298 if (!isset($processor[$field])) {
299 $processors['values'][$processor['id']][$field] = NULL;
300 }
301 }
302 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
303 $processors['values'][$processor['id']]['object'] = Civi\Payment\System::singleton()->getByProcessor($processor);
304 }
305
306 // Add the pay-later pseudo-processor.
307 $processors['values'][0] = array(
308 'object' => new CRM_Core_Payment_Manual(),
309 'id' => 0,
310 'payment_processor_type_id' => 0,
311 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
312 'payment_processor_type' => 'Manual',
313 'class_name' => 'Payment_Manual',
314 'name' => 'pay_later',
315 'billing_mode' => '',
316 'is_default' => 0,
317 // This should ideally be retrieved from the DB but existing default is check so we'll code that for now.
318 'payment_instrument_id' => CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name'),
319 // Making this optionally recur would give lots of options -but it should
320 // be a row in the payment processor table before we do that.
321 'is_recur' => FALSE,
322 );
323
324 CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']);
325
326 return $processors['values'];
327 }
328
329 /**
330 * Get Payment processors with specified capabilities.
331 * Note that both the singleton & the pseudoconstant function have caching so we don't add
332 * arguably this could go on the pseudoconstant class
333 *
334 * @param array $capabilities
335 * capabilities of processor e.g
336 * - BackOffice
337 * - TestMode
338 * - LiveMode
339 * - FutureStartDate
340 *
341 * @param array|bool $ids
342 *
343 * @return array
344 * available processors
345 */
346 public static function getPaymentProcessors($capabilities = array(), $ids = FALSE) {
347 $mode = NULL;
348 $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : array();
349 $processors = self::getAllPaymentProcessors('all');
350
351 if (in_array('TestMode', $capabilities)) {
352 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
353 foreach ($possibleLiveIDs as $possibleLiveID) {
354 if (isset($processors[$possibleLiveID]) && ($liveProcessorName = $processors[$possibleLiveID]['name']) != FALSE) {
355 foreach ($testProcessors as $index => $testProcessor) {
356 if ($testProcessor['name'] == $liveProcessorName) {
357 $ids[] = $testProcessor['id'];
358 }
359 }
360 }
361 }
362 $processors = $testProcessors;
363 }
364
365 foreach ($processors as $index => $processor) {
366 if (is_array($ids) && !in_array($processor['id'], $ids)) {
367 unset ($processors[$index]);
368 continue;
369 }
370 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
371 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
372 if (!is_a($processor['object'], 'CRM_Core_Payment')) {
373 unset ($processors[$index]);
374 continue;
375 }
376 foreach ($capabilities as $capability) {
377 if (($processor['object']->supports($capability)) == FALSE) {
378 unset ($processors[$index]);
379 continue 1;
380 }
381 }
382 }
383
384 return $processors;
385 }
386
387 /**
388 * Is there a processor on this site with the specified capability.
389 * @param array $capabilities
390 *
391 * @return bool
392 */
393 public static function hasPaymentProcessorSupporting($capabilities = array()) {
394 $result = self::getPaymentProcessors($capabilities);
395 return (!empty($result)) ? TRUE : FALSE;
396 }
397
398 /**
399 * Retrieve payment processor id / info/ object based on component-id.
400 *
401 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
402 * that are entity specific as there is little shared code specific to obj or info
403 *
404 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
405 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
406 *
407 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
408 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
409 * no way to derive the processor - but hey - what processor? it didn't go through!
410 *
411 * Query for membership might look something like:
412 * SELECT fte.payment_processor_id
413 * FROM civicrm_membership mem
414 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
415 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
416 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
417 * 'civicrm_contribution'
418 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
419 *
420 * @param int $entityID
421 * @param string $component
422 * Component.
423 * @param string $type
424 * Type of payment information to be retrieved.
425 *
426 * @return int|array|object
427 */
428 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
429 $result = NULL;
430 if (!in_array($component, array(
431 'membership',
432 'contribute',
433 'recur',
434 ))
435 ) {
436 return $result;
437 }
438
439 if ($component == 'membership') {
440 $sql = "
441 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
442 FROM civicrm_membership mem
443 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
444 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
445 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
446 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
447 WHERE mp.membership_id = %1";
448 }
449 elseif ($component == 'contribute') {
450 $sql = "
451 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
452 FROM civicrm_contribution con
453 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
454 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
455 WHERE con.id = %1";
456 }
457 elseif ($component == 'recur') {
458 $sql = "
459 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
460 FROM civicrm_contribution_recur cr
461 WHERE cr.id = %1";
462 }
463
464 // We are interested in a single record.
465 $sql .= ' LIMIT 1';
466
467 $params = array(1 => array($entityID, 'Integer'));
468 $dao = CRM_Core_DAO::executeQuery($sql, $params);
469
470 if (!$dao->fetch()) {
471
472 return $result;
473
474 }
475
476 $ppID = (isset($dao->ppID1) && $dao->ppID1) ? $dao->ppID1 : (isset($dao->ppID2) ? $dao->ppID2 : NULL);
477 $mode = (isset($dao->is_test) && $dao->is_test) ? 'test' : 'live';
478 if (!$ppID || $type == 'id') {
479 $result = $ppID;
480 }
481 elseif ($type == 'info') {
482 $result = self::getPayment($ppID, $mode);
483 }
484 elseif ($type == 'obj' && is_numeric($ppID)) {
485 try {
486 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', array('id' => $ppID));
487 }
488 catch (API_Exception $e) {
489 // Unable to load the processor because this function uses an unreliable method to derive it.
490 // The function looks to load the payment processor ID from the contribution page, which
491 // can support multiple processors.
492 }
493 $result = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
494 }
495 return $result;
496 }
497
498 }