use processor class to determine if backoffice processing is supported
[civicrm-core.git] / CRM / Core / Payment.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 abstract class CRM_Core_Payment {
37
38 /**
39 * how are we getting billing information?
40 *
41 * FORM - we collect it on the same page
42 * BUTTON - the processor collects it and sends it back to us via some protocol
43 */
44 CONST
45 BILLING_MODE_FORM = 1,
46 BILLING_MODE_BUTTON = 2,
47 BILLING_MODE_NOTIFY = 4;
48
49 /**
50 * which payment type(s) are we using?
51 *
52 * credit card
53 * direct debit
54 * or both
55 *
56 */
57 CONST
58 PAYMENT_TYPE_CREDIT_CARD = 1,
59 PAYMENT_TYPE_DIRECT_DEBIT = 2;
60
61 /**
62 * Subscription / Recurring payment Status
63 * START, END
64 *
65 */
66 CONST
67 RECURRING_PAYMENT_START = 'START',
68 RECURRING_PAYMENT_END = 'END';
69
70 /**
71 * We only need one instance of this object. So we use the singleton
72 * pattern and cache the instance in this variable
73 *
74 * @var object
75 * @static
76 */
77 static private $_singleton = NULL;
78
79 protected $_paymentProcessor;
80
81 /**
82 * @var CRM_Core_Form
83 */
84 protected $_paymentForm = NULL;
85
86 /**
87 * singleton function used to manage this object
88 *
89 * @param string $mode the mode of operation: live or test
90 * @param array $paymentProcessor the details of the payment processor being invoked
91 * @param object $paymentForm reference to the form object if available
92 * @param boolean $force should we force a reload of this payment object
93 *
94 * @return CRM_Core_Payment
95 * @static
96 *
97 */
98 static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
99 // make sure paymentProcessor is not empty
100 // CRM-7424
101 if (empty($paymentProcessor)) {
102 return CRM_Core_DAO::$_nullObject;
103 }
104
105 $cacheKey = "{$mode}_{$paymentProcessor['id']}_" . (int)isset($paymentForm);
106 if (!isset(self::$_singleton[$cacheKey]) || $force) {
107 $config = CRM_Core_Config::singleton();
108 $ext = CRM_Extension_System::singleton()->getMapper();
109 if ($ext->isExtensionKey($paymentProcessor['class_name'])) {
110 $paymentClass = $ext->keyToClass($paymentProcessor['class_name'], 'payment');
111 require_once ($ext->classToPath($paymentClass));
112 }
113 else {
114 $paymentClass = 'CRM_Core_' . $paymentProcessor['class_name'];
115 require_once (str_replace('_', DIRECTORY_SEPARATOR, $paymentClass) . '.php');
116 }
117
118 //load the object.
119 self::$_singleton[$cacheKey] = $paymentClass::singleton($mode, $paymentProcessor);
120 }
121
122 //load the payment form for required processor.
123 if ($paymentForm !== NULL) {
124 self::$_singleton[$cacheKey]->setForm($paymentForm);
125 }
126
127 return self::$_singleton[$cacheKey];
128 }
129
130 /**
131 * @param $params
132 *
133 * @return mixed
134 */
135 public static function logPaymentNotification($params) {
136 $message = 'payment_notification ';
137 if (!empty($params['processor_name'])) {
138 $message .= 'processor_name=' . $params['processor_name'];
139 }
140 if (!empty($params['processor_id'])) {
141 $message .= 'processor_id=' . $params['processor_id'];
142 }
143
144 $log = new CRM_Utils_SystemLogger();
145 $log->alert($message, $_REQUEST);
146 }
147
148 /**
149 * check if capability is supported
150 * @param string $capability e.g BackOffice, LiveMode, FutureRecurStartDate
151 *
152 * @return bool
153 */
154 public function supports($capability) {
155 $function = 'supports' . ucfirst($capability);
156 if (method_exists($this, $function)) {
157 return $this->$function();
158 }
159 return FALSE;
160 }
161
162 /**
163 * are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
164 * @return bool
165 */
166 private function supportsBackOffice() {
167 return TRUE;
168 }
169
170 /**
171 * are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
172 * @return bool
173 */
174 private function supportsLiveMode() {
175 return TRUE;
176 }
177
178 /**
179 * should the first payment date be configurable when setting up back office recurring payments
180 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
181 * @return bool
182 */
183 private function supportsFutureRecurStartDate() {
184 return FALSE;
185 }
186
187 /**
188 * Setter for the payment form that wants to use the processor
189 *
190 * @param CRM_Core_Form $paymentForm
191 *
192 */
193 function setForm(&$paymentForm) {
194 $this->_paymentForm = $paymentForm;
195 }
196
197 /**
198 * Getter for payment form that is using the processor
199 *
200 * @return CRM_Core_Form A form object
201 */
202 function getForm() {
203 return $this->_paymentForm;
204 }
205
206 /**
207 * Getter for accessing member vars
208 *
209 */
210 function getVar($name) {
211 return isset($this->$name) ? $this->$name : NULL;
212 }
213
214 /**
215 * This function collects all the information from a web/api form and invokes
216 * the relevant payment processor specific functions to perform the transaction
217 *
218 * @param array $params assoc array of input parameters for this transaction
219 *
220 * @return array the result in an nice formatted array (or an error object)
221 * @abstract
222 */
223 abstract function doDirectPayment(&$params);
224
225 /**
226 * This function checks to see if we have the right config values
227 *
228 * @internal param string $mode the mode we are operating in (live or test)
229 *
230 * @return string the error message if any
231 * @public
232 */
233 abstract function checkConfig();
234
235 /**
236 * @param $paymentProcessor
237 *
238 * @return bool
239 */
240 static function paypalRedirect(&$paymentProcessor) {
241 if (!$paymentProcessor) {
242 return FALSE;
243 }
244
245 if (isset($_GET['payment_date']) &&
246 isset($_GET['merchant_return_link']) &&
247 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
248 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
249 ) {
250 return TRUE;
251 }
252
253 return FALSE;
254 }
255
256 /**
257 * Page callback for civicrm/payment/ipn
258 * @public
259 */
260 static function handleIPN() {
261 self::handlePaymentMethod(
262 'PaymentNotification',
263 array(
264 'processor_name' => @$_GET['processor_name'],
265 'processor_id' => @$_GET['processor_id'],
266 'mode' => @$_GET['mode'],
267 )
268 );
269 }
270
271 /**
272 * Payment callback handler. The processor_name or processor_id is passed in.
273 * Note that processor_id is more reliable as one site may have more than one instance of a
274 * processor & ideally the processor will be validating the results
275 * Load requested payment processor and call that processor's handle<$method> method
276 *
277 * @public
278 * @param $method
279 * @param array $params
280 */
281 static function handlePaymentMethod($method, $params = array()) {
282 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
283 CRM_Core_Error::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
284 }
285 self::logPaymentNotification($params);
286
287 // Query db for processor ..
288 $mode = @$params['mode'];
289
290 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
291 FROM civicrm_payment_processor_type ppt
292 INNER JOIN civicrm_payment_processor pp
293 ON pp.payment_processor_type_id = ppt.id
294 AND pp.is_active
295 AND pp.is_test = %1";
296 $args[1] = array($mode == 'test' ? 1 : 0, 'Integer');
297
298 if (isset($params['processor_id'])) {
299 $sql .= " WHERE pp.id = %2";
300 $args[2] = array($params['processor_id'], 'Integer');
301 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
302 }
303 else {
304 $sql .= " WHERE ppt.name = %2";
305 $args[2] = array($params['processor_name'], 'String');
306 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
307 }
308
309 $dao = CRM_Core_DAO::executeQuery($sql, $args);
310
311 // Check whether we found anything at all ..
312 if (!$dao->N) {
313 CRM_Core_Error::fatal($notfound);
314 }
315
316 $method = 'handle' . $method;
317 $extension_instance_found = FALSE;
318
319 // In all likelihood, we'll just end up with the one instance returned here. But it's
320 // possible we may get more. Hence, iterate through all instances ..
321
322 while ($dao->fetch()) {
323 // Check pp is extension
324 $ext = CRM_Extension_System::singleton()->getMapper();
325 if ($ext->isExtensionKey($dao->class_name)) {
326 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
327 require_once $ext->classToPath($paymentClass);
328 }
329 else {
330 // Legacy or extension as module instance
331 if (empty($paymentClass)) {
332 $paymentClass = 'CRM_Core_' . $dao->class_name;
333
334 }
335 }
336
337 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($dao->processor_id, $mode);
338
339 // Should never be empty - we already established this processor_id exists and is active.
340 if (empty($paymentProcessor)) {
341 continue;
342 }
343
344 // Instantiate PP
345 $processorInstance = $paymentClass::singleton($mode, $paymentProcessor);
346
347 // Does PP implement this method, and can we call it?
348 if (!method_exists($processorInstance, $method) ||
349 !is_callable(array($processorInstance, $method))
350 ) {
351 // on the off chance there is a double implementation of this processor we should keep looking for another
352 // note that passing processor_id is more reliable & we should work to deprecate processor_name
353 continue;
354 }
355
356 // Everything, it seems, is ok - execute pp callback handler
357 $processorInstance->$method();
358 $extension_instance_found = TRUE;
359 }
360
361 if (!$extension_instance_found) CRM_Core_Error::fatal(
362 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
363 "$method method is unsupported in legacy payment processors."
364 );
365
366 // Exit here on web requests, allowing just the plain text response to be echoed
367 if ($method == 'handlePaymentNotification') {
368 CRM_Utils_System::civiExit();
369 }
370 }
371
372 /**
373 * Function to check whether a method is present ( & supported ) by the payment processor object.
374 *
375 * @param string $method method to check for.
376 *
377 * @return boolean
378 * @public
379 */
380 function isSupported($method = 'cancelSubscription') {
381 return method_exists(CRM_Utils_System::getClassName($this), $method);
382 }
383
384 /**
385 * @param null $entityID
386 * @param null $entity
387 * @param string $action
388 *
389 * @return string
390 */
391 function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
392 // Set URL
393 switch ($action) {
394 case 'cancel' :
395 $url = 'civicrm/contribute/unsubscribe';
396 break;
397 case 'billing' :
398 //in notify mode don't return the update billing url
399 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
400 return NULL;
401 }
402 $url = 'civicrm/contribute/updatebilling';
403 break;
404 case 'update' :
405 $url = 'civicrm/contribute/updaterecur';
406 break;
407 }
408
409 $session = CRM_Core_Session::singleton();
410 $userId = $session->get('userID');
411 $contactID = 0;
412 $checksumValue = '';
413 $entityArg = '';
414
415 // Find related Contact
416 if ($entityID) {
417 switch ($entity) {
418 case 'membership' :
419 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
420 $entityArg = 'mid';
421 break;
422
423 case 'contribution' :
424 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
425 $entityArg = 'coid';
426 break;
427
428 case 'recur' :
429 $sql = "
430 SELECT con.contact_id
431 FROM civicrm_contribution_recur rec
432 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
433 WHERE rec.id = %1
434 GROUP BY rec.id";
435 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
436 $entityArg = 'crid';
437 break;
438 }
439 }
440
441 // Add entity arguments
442 if ($entityArg != '') {
443 // Add checksum argument
444 if ($contactID != 0 && $userId != $contactID) {
445 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
446 }
447 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
448 }
449
450 // Else login URL
451 if ($this->isSupported('accountLoginURL')) {
452 return $this->accountLoginURL();
453 }
454
455 // Else default
456 return $this->_paymentProcessor['url_recur'];
457 }
458 }