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