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