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