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