CRM-14684 add comments
[civicrm-core.git] / CRM / Core / Payment.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36abstract 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
ac32ed13
EM
81 /**
82 * @var CRM_Core_Form
83 */
6a488035
TO
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 object $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 object
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.
0e6e8724 119 self::$_singleton[$cacheKey] = $paymentClass::singleton($mode, $paymentProcessor);
6a488035
TO
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
e2bef985 130 /**
131 * @param $params
132 *
133 * @return mixed
134 */
135 public static function logPaymentNotification($params) {
414e3596 136 $message = 'payment_notification ';
e2bef985 137 if (!empty($params['processor_name'])) {
414e3596 138 $message .= 'processor_name=' . $params['processor_name'];
e2bef985 139 }
140 if (!empty($params['processor_id'])) {
141 $message .= 'processor_id=' . $params['processor_id'];
142 }
414e3596 143
144 $log = new CRM_Utils_SystemLogger();
145 $log->alert($message, $_REQUEST);
e2bef985 146 }
147
6a488035
TO
148 /**
149 * Setter for the payment form that wants to use the processor
150 *
ac32ed13 151 * @param CRM_Core_Form $paymentForm
6a488035
TO
152 *
153 */
154 function setForm(&$paymentForm) {
155 $this->_paymentForm = $paymentForm;
156 }
157
158 /**
159 * Getter for payment form that is using the processor
160 *
ac32ed13 161 * @return CRM_Core_Form A form object
6a488035
TO
162 */
163 function getForm() {
164 return $this->_paymentForm;
165 }
166
167 /**
168 * Getter for accessing member vars
169 *
170 */
171 function getVar($name) {
172 return isset($this->$name) ? $this->$name : NULL;
173 }
174
175 /**
176 * This function collects all the information from a web/api form and invokes
177 * the relevant payment processor specific functions to perform the transaction
178 *
179 * @param array $params assoc array of input parameters for this transaction
180 *
181 * @return array the result in an nice formatted array (or an error object)
182 * @abstract
183 */
184 abstract function doDirectPayment(&$params);
185
186 /**
187 * This function checks to see if we have the right config values
188 *
414e3596 189 * @internal param string $mode the mode we are operating in (live or test)
6a488035
TO
190 *
191 * @return string the error message if any
192 * @public
193 */
194 abstract function checkConfig();
195
196 static function paypalRedirect(&$paymentProcessor) {
197 if (!$paymentProcessor) {
198 return FALSE;
199 }
200
201 if (isset($_GET['payment_date']) &&
202 isset($_GET['merchant_return_link']) &&
203 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
204 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
205 ) {
206 return TRUE;
207 }
208
209 return FALSE;
210 }
211
212 /**
213 * Page callback for civicrm/payment/ipn
214 * @public
215 */
216 static function handleIPN() {
217 self::handlePaymentMethod(
218 'PaymentNotification',
219 array(
220 'processor_name' => @$_GET['processor_name'],
42b90e8f 221 'processor_id' => @$_GET['processor_id'],
6a488035
TO
222 'mode' => @$_GET['mode'],
223 )
224 );
225 }
226
227 /**
43d1ae00
EM
228 * Payment callback handler. The processor_name or processor_id is passed in.
229 * Note that processor_id is more reliable as one site may have more than one instance of a
230 * processor & ideally the processor will be validating the results
6a488035
TO
231 * Load requested payment processor and call that processor's handle<$method> method
232 *
233 * @public
234 */
235 static function handlePaymentMethod($method, $params = array( )) {
42b90e8f
CB
236 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
237 CRM_Core_Error::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
6a488035 238 }
e2bef985 239 self::logPaymentNotification($params);
6a488035
TO
240
241 // Query db for processor ..
242 $mode = @$params['mode'];
243
42b90e8f
CB
244 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
245 FROM civicrm_payment_processor_type ppt
246 INNER JOIN civicrm_payment_processor pp
247 ON pp.payment_processor_type_id = ppt.id
248 AND pp.is_active
249 AND pp.is_test = %1";
250 $args[1] = array($mode == 'test' ? 1 : 0, 'Integer');
251
252 if (isset($params['processor_id'])) {
253 $sql .= " WHERE pp.id = %2";
254 $args[2] = array($params['processor_id'], 'Integer');
255 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
256 }
257 else {
258 $sql .= " WHERE ppt.name = %2";
259 $args[2] = array($params['processor_name'], 'String');
260 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
261 }
262
263 $dao = CRM_Core_DAO::executeQuery($sql, $args);
6a488035
TO
264
265 // Check whether we found anything at all ..
266 if (!$dao->N) {
42b90e8f 267 CRM_Core_Error::fatal($notfound);
6a488035
TO
268 }
269
270 $method = 'handle' . $method;
271 $extension_instance_found = FALSE;
272
273 // In all likelihood, we'll just end up with the one instance returned here. But it's
274 // possible we may get more. Hence, iterate through all instances ..
275
276 while ($dao->fetch()) {
277 // Check pp is extension
278 $ext = CRM_Extension_System::singleton()->getMapper();
279 if ($ext->isExtensionKey($dao->class_name)) {
6a488035
TO
280 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
281 require_once $ext->classToPath($paymentClass);
282 }
283 else {
43d1ae00 284 // Legacy or extension as module instance
d031c654 285 if (empty($paymentClass)) {
43d1ae00
EM
286 $paymentClass = 'CRM_Core_' . $dao->class_name;
287
288 }
6a488035
TO
289 }
290
291 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($dao->processor_id, $mode);
292
293 // Should never be empty - we already established this processor_id exists and is active.
294 if (empty($paymentProcessor)) {
295 continue;
296 }
297
298 // Instantiate PP
0e6e8724 299 $processorInstance = $paymentClass::singleton($mode, $paymentProcessor);
6a488035
TO
300
301 // Does PP implement this method, and can we call it?
302 if (!method_exists($processorInstance, $method) ||
303 !is_callable(array($processorInstance, $method))
304 ) {
43d1ae00
EM
305 // on the off chance there is a double implementation of this processor we should keep looking for another
306 // note that passing processor_id is more reliable & we should work to deprecate processor_name
307 continue;
6a488035
TO
308 }
309
310 // Everything, it seems, is ok - execute pp callback handler
311 $processorInstance->$method();
a5ef96f6 312 $extension_instance_found = TRUE;
6a488035
TO
313 }
314
315 if (!$extension_instance_found) CRM_Core_Error::fatal(
316 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
317 "$method method is unsupported in legacy payment processors."
318 );
319
320 // Exit here on web requests, allowing just the plain text response to be echoed
321 if ($method == 'handlePaymentNotification') {
322 CRM_Utils_System::civiExit();
323 }
324 }
325
326 /**
327 * Function to check whether a method is present ( & supported ) by the payment processor object.
328 *
329 * @param string $method method to check for.
330 *
331 * @return boolean
332 * @public
333 */
334 function isSupported($method = 'cancelSubscription') {
335 return method_exists(CRM_Utils_System::getClassName($this), $method);
336 }
337
338 function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
339 if ($action == 'cancel') {
340 $url = 'civicrm/contribute/unsubscribe';
341 }
342 elseif ($action == 'billing') {
1a9f6d0d
PJ
343 //in notify mode don't return the update billing url
344 if ($this->_paymentProcessor['billing_mode'] == self::BILLING_MODE_NOTIFY) {
345 return NULL;
346 }
6a488035
TO
347 $url = 'civicrm/contribute/updatebilling';
348 }
349 elseif ($action == 'update') {
350 $url = 'civicrm/contribute/updaterecur';
351 }
352 $session = CRM_Core_Session::singleton();
353 $userId = $session->get('userID');
354 $checksumValue = "";
355
356 if ($entityID && $entity == 'membership') {
357 if (!$userId) {
358 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
359 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
360 $checksumValue = "&cs={$checksumValue}";
361 }
6a30bb95 362 return CRM_Utils_System::url($url, "reset=1&mid={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
6a488035
TO
363 }
364
365 if ($entityID && $entity == 'contribution') {
366 if (!$userId) {
367 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
368 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
369 $checksumValue = "&cs={$checksumValue}";
370 }
6a30bb95 371 return CRM_Utils_System::url($url, "reset=1&coid={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
6a488035
TO
372 }
373
374 if ($entityID && $entity == 'recur') {
375 if (!$userId) {
376 $sql = "
377 SELECT con.contact_id
378 FROM civicrm_contribution_recur rec
379INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
380 WHERE rec.id = %1
381 GROUP BY rec.id";
382 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
383 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
384 $checksumValue = "&cs={$checksumValue}";
385 }
6a30bb95 386 return CRM_Utils_System::url($url, "reset=1&crid={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
6a488035
TO
387 }
388
389 if ($this->isSupported('accountLoginURL')) {
390 return $this->accountLoginURL();
391 }
392 return $this->_paymentProcessor['url_recur'];
393 }
6a488035 394}