Merge pull request #4893 from colemanw/INFRA-132
[civicrm-core.git] / CRM / Financial / BAO / PaymentProcessor.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class contains payment processor related functions.
38 */
39 class CRM_Financial_BAO_PaymentProcessor extends CRM_Financial_DAO_PaymentProcessor {
40 /**
41 * Static holder for the default payment processor
42 */
43 static $_defaultPaymentProcessor = NULL;
44
45 /**
46 * Create Payment Processor
47 *
48 * @param array $params
49 * Parameters for Processor entity.
50 *
51 * @return CRM_Financial_DAO_PaymentProcessor
52 * @throws Exception
53 */
54 public static function create($params) {
55 // FIXME Reconcile with CRM_Admin_Form_PaymentProcessor::updatePaymentProcessor
56 $processor = new CRM_Financial_DAO_PaymentProcessor();
57 $processor->copyValues($params);
58
59 $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
60 $ppTypeDAO->id = $params['payment_processor_type_id'];
61 if (!$ppTypeDAO->find(TRUE)) {
62 CRM_Core_Error::fatal(ts('Could not find payment processor meta information'));
63 }
64
65 // also copy meta fields from the info DAO
66 $processor->is_recur = $ppTypeDAO->is_recur;
67 $processor->billing_mode = $ppTypeDAO->billing_mode;
68 $processor->class_name = $ppTypeDAO->class_name;
69 $processor->payment_type = $ppTypeDAO->payment_type;
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 = array(
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 return $processor;
85 }
86
87 /**
88 * Class constructor
89 */
90 public function __construct() {
91 parent::__construct();
92 }
93
94 /**
95 * Takes a bunch of params that are needed to match certain criteria and
96 * retrieves the relevant objects. It also stores all the retrieved
97 * values in the default array
98 *
99 * @param array $params
100 * (reference ) an assoc array of name/value pairs.
101 * @param array $defaults
102 * (reference ) an assoc array to hold the flattened values.
103 *
104 * @return CRM_Financial_DAO_PaymentProcessor object on success, null otherwise
105 * @static
106 */
107 public static function retrieve(&$params, &$defaults) {
108 $paymentProcessor = new CRM_Financial_DAO_PaymentProcessor();
109 $paymentProcessor->copyValues($params);
110 if ($paymentProcessor->find(TRUE)) {
111 CRM_Core_DAO::storeValues($paymentProcessor, $defaults);
112 return $paymentProcessor;
113 }
114 return NULL;
115 }
116
117 /**
118 * Update the is_active flag in the db
119 *
120 * @param int $id
121 * Id of the database record.
122 * @param bool $is_active
123 * Value we want to set the is_active field.
124 *
125 * @return Object
126 * DAO object on sucess, null otherwise
127 *
128 * @static
129 */
130 public static function setIsActive($id, $is_active) {
131 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
132 }
133
134 /**
135 * Retrieve the default payment processor
136 *
137 * @param NULL
138 *
139 * @return object
140 * The default payment processor object on success,
141 * null otherwise
142 * @static
143 */
144 public static function &getDefault() {
145 if (self::$_defaultPaymentProcessor == NULL) {
146 $params = array('is_default' => 1);
147 $defaults = array();
148 self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
149 }
150 return self::$_defaultPaymentProcessor;
151 }
152
153 /**
154 * Function to delete payment processor
155 *
156 * @param int $paymentProcessorID
157 *
158 * @return null
159 * @static
160 */
161 public static function del($paymentProcessorID) {
162 if (!$paymentProcessorID) {
163 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
164 }
165
166 $dao = new CRM_Financial_DAO_PaymentProcessor();
167 $dao->id = $paymentProcessorID;
168 if (!$dao->find(TRUE)) {
169 return NULL;
170 }
171
172 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
173 $testDAO->name = $dao->name;
174 $testDAO->is_test = 1;
175 $testDAO->delete();
176
177 $dao->delete();
178 }
179
180 /**
181 * Get the payment processor details
182 *
183 * @param int $paymentProcessorID
184 * Payment processor id.
185 * @param string $mode
186 * Payment mode ie test or live.
187 *
188 * @return array
189 * associated array with payment processor related fields
190 * @static
191 */
192 public static function getPayment($paymentProcessorID, $mode) {
193 if (!$paymentProcessorID) {
194 CRM_Core_Error::fatal(ts('Invalid value passed to getPayment function'));
195 }
196
197 $dao = new CRM_Financial_DAO_PaymentProcessor();
198 $dao->id = $paymentProcessorID;
199 $dao->is_active = 1;
200 if (!$dao->find(TRUE)) {
201 return NULL;
202 }
203
204 if ($mode == 'test') {
205 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
206 $testDAO->name = $dao->name;
207 $testDAO->is_active = 1;
208 $testDAO->is_test = 1;
209 if (!$testDAO->find(TRUE)) {
210 CRM_Core_Error::fatal(ts('Could not retrieve payment processor details'));
211 }
212 return self::buildPayment($testDAO, $mode);
213 }
214 else {
215 return self::buildPayment($dao, $mode);
216 }
217 }
218
219 /**
220 * @param $paymentProcessorIDs
221 * @param $mode
222 *
223 * @return array
224 * @throws Exception
225 */
226 public static function getPayments($paymentProcessorIDs, $mode) {
227 if (!$paymentProcessorIDs) {
228 CRM_Core_Error::fatal(ts('Invalid value passed to getPayment function'));
229 }
230
231 $payments = array();
232 foreach ($paymentProcessorIDs as $paymentProcessorID) {
233 $payment = self::getPayment($paymentProcessorID, $mode);
234 $payments[$payment['id']] = $payment;
235 }
236
237 uasort($payments, 'self::defaultComparison');
238 return $payments;
239 }
240
241 /**
242 * Compare 2 payment processors to see which should go first based on is_default
243 * (sort function for sortDefaultFirst)
244 * @param array $processor1
245 * @param array_type $processor2
246 * @return number
247 */
248 public static function defaultComparison($processor1, $processor2) {
249 $p1 = CRM_Utils_Array::value('is_default', $processor1);
250 $p2 = CRM_Utils_Array::value('is_default', $processor2);
251 if ($p1 == $p2) {
252 return 0;
253 }
254 return ($p1 > $p2) ? -1 : 1;
255 }
256
257 /**
258 * Build payment processor details
259 *
260 * @param object $dao
261 * Payment processor object.
262 * @param string $mode
263 * Payment mode ie test or live.
264 *
265 * @return array
266 * associated array with payment processor related fields
267 * @static
268 */
269 public static function buildPayment($dao, $mode) {
270 $fields = array(
271 'id', 'name', 'payment_processor_type_id', 'user_name', 'password',
272 'signature', 'url_site', 'url_api', 'url_recur', 'url_button',
273 'subject', 'class_name', 'is_recur', 'billing_mode', 'is_test',
274 'payment_type', 'is_default',
275 );
276 $result = array();
277 foreach ($fields as $name) {
278 $result[$name] = $dao->$name;
279 }
280 $result['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, $dao->payment_processor_type_id, 'name');
281
282 $result['instance'] = $result['object'] =& CRM_Core_Payment::singleton($mode, $result);
283
284 return $result;
285 }
286
287 /**
288 * Get all payment processors as an array of objects.
289 *
290 * @param string|NULL $mode
291 * only return this mode - test|live or NULL for all
292 * @param bool $reset
293 *
294 * @throws CiviCRM_API3_Exception
295 * @return array
296 */
297 public static function getAllPaymentProcessors($mode, $reset = FALSE) {
298 /**
299 * $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . ($mode ? 'test' : 'all');
300 if (!$reset) {
301 $processors = CRM_Utils_Cache::singleton()->get($cacheKey);
302 if (!empty($processors)) {
303 return $processors;
304 }
305 }
306 * */
307 $retrievalParameters = array('is_active' => TRUE, 'options' => array('sort' => 'is_default DESC, name'), 'api.payment_processor_type.getsingle' => 1);
308 if ($mode == 'test') {
309 $retrievalParameters['is_test'] = 1;
310 }
311 elseif ($mode == 'live') {
312 $retrievalParameters['is_test'] = 0;
313 }
314 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
315 foreach ($processors['values'] as $processor) {
316 $fieldsToProvide = array('user_name', 'password', 'signature', 'subject');
317 foreach ($fieldsToProvide as $field) {
318 //prevent e-notices in processor classes when not configured
319 if (!isset($processor[$field])) {
320 $processor[$field] = NULL;
321 }
322 }
323 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
324 $mode = empty($processor['is_test']) ? 'live' : 'test';
325 $processors['values'][$processor['id']]['object'] = CRM_Core_Payment::singleton($mode, $processor);
326 }
327 /*
328 CRM_Utils_Cache::singleton()->set($cacheKey, $processors);
329 */
330 return $processors['values'];
331 }
332
333 /**
334 * Get Payment processors with specified capabilities.
335 * Note that both the singleton & the pseudoconstant function have caching so we don't add
336 * arguably this could go on the pseudoconstant class
337 *
338 * @param array $capabilities
339 * capabilities of processor e.g
340 * - BackOffice
341 * - TestMode
342 * - LiveMode
343 * - FutureStartDate
344 * include test processors (we want to phase this out in favour of the testMode Capability)
345 *
346 * @param array $ids
347 *
348 * @return array
349 * available processors
350 */
351 public static function getPaymentProcessors($capabilities = array(), $ids = array()) {
352 $mode = NULL;
353 if (in_array('TestMode', $capabilities)) {
354 $mode = 'test';
355 }
356 elseif (in_array('LiveMode', $capabilities)) {
357 $mode = 'live';
358 }
359 $processors = self::getAllPaymentProcessors($mode);
360 if ($capabilities) {
361 foreach ($processors as $index => $processor) {
362 if (!empty($ids) && !in_array($processor['id'], $ids)) {
363 unset ($processors[$index]);
364 continue;
365 }
366 if (($error = $processor['object']->checkConfig()) != NULL) {
367 unset ($processors[$index]);
368 continue;
369 }
370 foreach ($capabilities as $capability) {
371 if (($processor['object']->supports($capability)) == FALSE) {
372 unset ($processors[$index]);
373 }
374 }
375 }
376 }
377 return $processors;
378 }
379
380 /**
381 * Is there a processor on this site with the specified capability
382 * @param array $capabilities
383 * @param bool $isIncludeTest
384 *
385 * @return bool
386 */
387 public static function hasPaymentProcessorSupporting($capabilities = array(), $isIncludeTest = FALSE) {
388 $mode = $isIncludeTest ? 'Test' : 'Live';
389 $capabilities[] = $mode . 'Mode';
390 $result = self::getPaymentProcessors($capabilities);
391 return (!empty($result)) ? TRUE : FALSE;
392 }
393
394 /**
395 * Retrieve payment processor id / info/ object based on component-id.
396 *
397 * @param int $entityID
398 * @param string $component
399 * Component.
400 * @param string $type
401 * Type of payment information to be retrieved.
402 *
403 * @return int
404 * / array / object based on type
405 * @static
406 */
407 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
408 $result = NULL;
409 if (!in_array($component, array(
410 'membership', 'contribute', 'recur'))) {
411 return $result;
412 }
413 //FIXME:
414 if ($component == 'membership') {
415 $sql = "
416 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
417 FROM civicrm_membership mem
418 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
419 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
420 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
421 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
422 WHERE mp.membership_id = %1";
423 }
424 elseif ($component == 'contribute') {
425 $sql = "
426 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
427 FROM civicrm_contribution con
428 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
429 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
430 WHERE con.id = %1";
431 }
432 elseif ($component == 'recur') {
433 $sql = "
434 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
435 FROM civicrm_contribution_recur cr
436 WHERE cr.id = %1";
437 }
438
439 //we are interesting in single record.
440 $sql .= ' LIMIT 1';
441
442 $params = array(1 => array($entityID, 'Integer'));
443 $dao = CRM_Core_DAO::executeQuery($sql, $params);
444
445 if (!$dao->fetch()) {
446
447 return $result;
448
449 }
450
451 $ppID = (isset($dao->ppID1) && $dao->ppID1) ? $dao->ppID1 : (isset($dao->ppID2) ? $dao->ppID2 : NULL);
452 $mode = (isset($dao->is_test) && $dao->is_test) ? 'test' : 'live';
453 if (!$ppID || $type == 'id') {
454 $result = $ppID;
455 }
456 elseif ($type == 'info') {
457 $result = self::getPayment($ppID, $mode);
458 }
459 elseif ($type == 'obj') {
460 $payment = self::getPayment($ppID, $mode);
461 $result = CRM_Core_Payment::singleton($mode, $payment);
462 }
463
464 return $result;
465 }
466 }