Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2014-12-09-14-48-51
[civicrm-core.git] / CRM / Financial / BAO / PaymentProcessor.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 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 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 * @access public
104 * @static
105 */
106 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 id of the database record
120 * @param boolean $is_active value we want to set the is_active field
121 *
122 * @return Object DAO object on sucess, null otherwise
123 *
124 * @access public
125 * @static
126 */
127 static function setIsActive($id, $is_active) {
128 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
129 }
130
131 /**
132 * Retrieve the default payment processor
133 *
134 * @param NULL
135 *
136 * @return object The default payment processor object on success,
137 * null otherwise
138 * @static
139 * @access public
140 */
141 static function &getDefault() {
142 if (self::$_defaultPaymentProcessor == NULL) {
143 $params = array('is_default' => 1);
144 $defaults = array();
145 self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
146 }
147 return self::$_defaultPaymentProcessor;
148 }
149
150 /**
151 * Function to delete payment processor
152 *
153 * @param int $paymentProcessorID
154 *
155 * @return null
156 * @access public
157 * @static
158 */
159 static function del($paymentProcessorID) {
160 if (!$paymentProcessorID) {
161 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
162 }
163
164 $dao = new CRM_Financial_DAO_PaymentProcessor();
165 $dao->id = $paymentProcessorID;
166 if (!$dao->find(TRUE)) {
167 return NULL;
168 }
169
170 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
171 $testDAO->name = $dao->name;
172 $testDAO->is_test = 1;
173 $testDAO->delete();
174
175 $dao->delete();
176 }
177
178 /**
179 * Get the payment processor details
180 *
181 * @param int $paymentProcessorID payment processor id
182 * @param string $mode payment mode ie test or live
183 *
184 * @return array associated array with payment processor related fields
185 * @static
186 * @access public
187 */
188 static function getPayment($paymentProcessorID, $mode) {
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 * @param $paymentProcessorIDs
217 * @param $mode
218 *
219 * @return array
220 * @throws Exception
221 */
222 static function getPayments($paymentProcessorIDs, $mode) {
223 if (!$paymentProcessorIDs) {
224 CRM_Core_Error::fatal(ts('Invalid value passed to getPayment function'));
225 }
226
227 $payments = array( );
228 foreach ($paymentProcessorIDs as $paymentProcessorID) {
229 $payment = self::getPayment($paymentProcessorID, $mode);
230 $payments[$payment['id']] = $payment;
231 }
232
233 uasort($payments, 'self::defaultComparison');
234 return $payments;
235 }
236
237 /**
238 * Compare 2 payment processors to see which should go first based on is_default
239 * (sort function for sortDefaultFirst)
240 * @param array $processor1
241 * @param array_type $processor2
242 * @return number
243 */
244 static function defaultComparison($processor1, $processor2){
245 $p1 = CRM_Utils_Array::value('is_default', $processor1);
246 $p2 = CRM_Utils_Array::value('is_default', $processor2);
247 if ($p1 == $p2) {
248 return 0;
249 }
250 return ($p1 > $p2) ? -1 : 1;
251 }
252
253 /**
254 * Build payment processor details
255 *
256 * @param object $dao payment processor object
257 * @param string $mode payment mode ie test or live
258 *
259 * @return array associated array with payment processor related fields
260 * @static
261 * @access public
262 */
263 static function buildPayment($dao, $mode) {
264 $fields = array(
265 'id', 'name', 'payment_processor_type_id', 'user_name', 'password',
266 'signature', 'url_site', 'url_api', 'url_recur', 'url_button',
267 'subject', 'class_name', 'is_recur', 'billing_mode', 'is_test',
268 'payment_type', 'is_default',
269 );
270 $result = array();
271 foreach ($fields as $name) {
272 $result[$name] = $dao->$name;
273 }
274 $result['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, $dao->payment_processor_type_id, 'name');
275
276 $result['instance'] = $result['object'] =& CRM_Core_Payment::singleton($mode, $result);
277
278 return $result;
279 }
280
281 /**
282 * Get all payment processors as an array of objects.
283 *
284 * @param $isExcludeTest
285 * @param bool $reset
286 *
287 * @throws CiviCRM_API3_Exception
288 * @return array
289 */
290 static function getAllPaymentProcessors($isExcludeTest, $reset = FALSE) {
291 /**
292 * $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . ($isExcludeTest ? 'test' : 'all');
293 if (!$reset) {
294 $processors = CRM_Utils_Cache::singleton()->get($cacheKey);
295 if (!empty($processors)) {
296 return $processors;
297 }
298 }
299 * */
300 $retrievalParameters = array('is_active' => TRUE, 'options' => array('sort' => 'is_default DESC, name'), 'api.payment_processor_type.getsingle' => 1);
301 if ($isExcludeTest) {
302 $retrievalParameters['is_test'] = 0;
303 }
304 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
305 foreach ($processors['values'] as $processor) {
306 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
307 $processors['values'][$processor['id']]['object'] = CRM_Core_Payment::singleton(empty($processor['is_test']) ? 'live' : 'test', $processor);
308 }
309 /*
310 CRM_Utils_Cache::singleton()->set($cacheKey, $processors);
311 */
312 return $processors['values'];
313 }
314
315 /**
316 * Get Payment processors with specified capabilities.
317 * Note that both the singleton & the pseudoconstant function have caching so we don't add
318 * arguably this could go on the pseudoconstant class
319 *
320 * @param array $capabilities
321 * @param bool $isIncludeTest
322 *
323 * @param array $ids
324 *
325 * @return array available processors
326 */
327 static function getPaymentProcessors($capabilities = array(), $isIncludeTest = FALSE, $ids = array()) {
328 $processors = self::getAllPaymentProcessors(!$isIncludeTest);
329 if ($capabilities) {
330 foreach ($processors as $index => $processor) {
331 if (!empty($ids) && !in_array($processor['id'], $ids)) {
332 unset ($processors[$index]);
333 continue;
334 }
335 if (($error = $processor['object']->checkConfig()) != NULL) {
336 unset ($processors[$index]);
337 continue;
338 }
339 foreach ($capabilities as $capability) {
340 if (($processor['object']->supports($capability)) == FALSE) {
341 unset ($processors[$index]);
342 }
343 }
344 }
345 }
346 return $processors;
347 }
348
349 /**
350 * Is there a processor on this site with the specified capability
351 * @param array $capabilities
352 * @param bool $isIncludeTest
353 *
354 * @return bool
355 */
356 static function hasPaymentProcessorSupporting($capabilities = array(), $isIncludeTest = FALSE) {
357 $result = self::getPaymentProcessors($capabilities, $isIncludeTest);
358 return (!empty($result)) ? TRUE : FALSE;
359 }
360
361 /**
362 * Retrieve payment processor id / info/ object based on component-id.
363 *
364 * @param int $entityID
365 * @param string $component component
366 * @param string $type type of payment information to be retrieved
367 *
368 * @return int / array / object based on type
369 * @static
370 * @access public
371 */
372 static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
373 $result = NULL;
374 if (!in_array($component, array(
375 'membership', 'contribute', 'recur'))) {
376 return $result;
377 }
378 //FIXME:
379 if ($component == 'membership') {
380 $sql = "
381 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
382 FROM civicrm_membership mem
383 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
384 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
385 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
386 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
387 WHERE mp.membership_id = %1";
388 }
389 elseif ($component == 'contribute') {
390 $sql = "
391 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
392 FROM civicrm_contribution con
393 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
394 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
395 WHERE con.id = %1";
396 }
397 elseif ($component == 'recur') {
398 $sql = "
399 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
400 FROM civicrm_contribution_recur cr
401 WHERE cr.id = %1";
402 }
403
404 //we are interesting in single record.
405 $sql .= ' LIMIT 1';
406
407 $params = array(1 => array($entityID, 'Integer'));
408 $dao = CRM_Core_DAO::executeQuery($sql, $params);
409
410 if (!$dao->fetch()) {
411
412 return $result;
413
414 }
415
416 $ppID = (isset($dao->ppID1) && $dao->ppID1) ? $dao->ppID1 : (isset($dao->ppID2) ? $dao->ppID2 : NULL);
417 $mode = (isset($dao->is_test) && $dao->is_test) ? 'test' : 'live';
418 if (!$ppID || $type == 'id') {
419 $result = $ppID;
420 }
421 elseif ($type == 'info') {
422 $result = self::getPayment($ppID, $mode);
423 }
424 elseif ($type == 'obj') {
425 $payment = self::getPayment($ppID, $mode);
426 $result = CRM_Core_Payment::singleton($mode, $payment);
427 }
428
429 return $result;
430 }
431 }
432