CRM-14494 add system logger files
[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 protected $_paymentForm = NULL;
82
83 /**
84 * singleton function used to manage this object
85 *
86 * @param string $mode the mode of operation: live or test
87 * @param object $paymentProcessor the details of the payment processor being invoked
88 * @param object $paymentForm reference to the form object if available
89 * @param boolean $force should we force a reload of this payment object
90 *
91 * @return object
92 * @static
93 *
94 */
95 static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
96 // make sure paymentProcessor is not empty
97 // CRM-7424
98 if (empty($paymentProcessor)) {
99 return CRM_Core_DAO::$_nullObject;
100 }
101
102 $cacheKey = "{$mode}_{$paymentProcessor['id']}_" . (int)isset($paymentForm);
103 if (!isset(self::$_singleton[$cacheKey]) || $force) {
104 $config = CRM_Core_Config::singleton();
105 $ext = CRM_Extension_System::singleton()->getMapper();
106 if ($ext->isExtensionKey($paymentProcessor['class_name'])) {
107 $paymentClass = $ext->keyToClass($paymentProcessor['class_name'], 'payment');
108 require_once ($ext->classToPath($paymentClass));
109 }
110 else {
111 $paymentClass = 'CRM_Core_' . $paymentProcessor['class_name'];
112 require_once (str_replace('_', DIRECTORY_SEPARATOR, $paymentClass) . '.php');
113 }
114
115 //load the object.
116 self::$_singleton[$cacheKey] = $paymentClass::singleton($mode, $paymentProcessor);
117 }
118
119 //load the payment form for required processor.
120 if ($paymentForm !== NULL) {
121 self::$_singleton[$cacheKey]->setForm($paymentForm);
122 }
123
124 return self::$_singleton[$cacheKey];
125 }
126
127 /**
128 * @param $params
129 *
130 * @return mixed
131 */
132 public static function logPaymentNotification($params) {
133 $message = '';
134 if (!empty($params['processor_name'])) {
135 $message = 'processor_name=' . $params['processor_name'];
136 }
137 if (!empty($params['processor_id'])) {
138 $message .= 'processor_id=' . $params['processor_id'];
139 }
140 $log = CRM_Utils_SystemLogger();
141 $log->log('alert', $message, $_REQUEST);
142 }
143
144 /**
145 * Setter for the payment form that wants to use the processor
146 *
147 * @param obj $paymentForm
148 *
149 */
150 function setForm(&$paymentForm) {
151 $this->_paymentForm = $paymentForm;
152 }
153
154 /**
155 * Getter for payment form that is using the processor
156 *
157 * @return obj A form object
158 */
159 function getForm() {
160 return $this->_paymentForm;
161 }
162
163 /**
164 * Getter for accessing member vars
165 *
166 */
167 function getVar($name) {
168 return isset($this->$name) ? $this->$name : NULL;
169 }
170
171 /**
172 * This function collects all the information from a web/api form and invokes
173 * the relevant payment processor specific functions to perform the transaction
174 *
175 * @param array $params assoc array of input parameters for this transaction
176 *
177 * @return array the result in an nice formatted array (or an error object)
178 * @abstract
179 */
180 abstract function doDirectPayment(&$params);
181
182 /**
183 * This function checks to see if we have the right config values
184 *
185 * @param string $mode the mode we are operating in (live or test)
186 *
187 * @return string the error message if any
188 * @public
189 */
190 abstract function checkConfig();
191
192 static function paypalRedirect(&$paymentProcessor) {
193 if (!$paymentProcessor) {
194 return FALSE;
195 }
196
197 if (isset($_GET['payment_date']) &&
198 isset($_GET['merchant_return_link']) &&
199 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
200 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
201 ) {
202 return TRUE;
203 }
204
205 return FALSE;
206 }
207
208 /**
209 * Page callback for civicrm/payment/ipn
210 * @public
211 */
212 static function handleIPN() {
213 self::handlePaymentMethod(
214 'PaymentNotification',
215 array(
216 'processor_name' => @$_GET['processor_name'],
217 'processor_id' => @$_GET['processor_id'],
218 'mode' => @$_GET['mode'],
219 )
220 );
221 }
222
223 /**
224 * Payment callback handler. The processor_name or processor_id is passed in.
225 * Note that processor_id is more reliable as one site may have more than one instance of a
226 * processor & ideally the processor will be validating the results
227 * Load requested payment processor and call that processor's handle<$method> method
228 *
229 * @public
230 */
231 static function handlePaymentMethod($method, $params = array( )) {
232 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
233 CRM_Core_Error::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
234 }
235 self::logPaymentNotification($params);
236
237 // Query db for processor ..
238 $mode = @$params['mode'];
239
240 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
241 FROM civicrm_payment_processor_type ppt
242 INNER JOIN civicrm_payment_processor pp
243 ON pp.payment_processor_type_id = ppt.id
244 AND pp.is_active
245 AND pp.is_test = %1";
246 $args[1] = array($mode == 'test' ? 1 : 0, 'Integer');
247
248 if (isset($params['processor_id'])) {
249 $sql .= " WHERE pp.id = %2";
250 $args[2] = array($params['processor_id'], 'Integer');
251 $notfound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
252 }
253 else {
254 $sql .= " WHERE ppt.name = %2";
255 $args[2] = array($params['processor_name'], 'String');
256 $notfound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
257 }
258
259 $dao = CRM_Core_DAO::executeQuery($sql, $args);
260
261 // Check whether we found anything at all ..
262 if (!$dao->N) {
263 CRM_Core_Error::fatal($notfound);
264 }
265
266 $method = 'handle' . $method;
267 $extension_instance_found = FALSE;
268
269 // In all likelihood, we'll just end up with the one instance returned here. But it's
270 // possible we may get more. Hence, iterate through all instances ..
271
272 while ($dao->fetch()) {
273 // Check pp is extension
274 $ext = CRM_Extension_System::singleton()->getMapper();
275 if ($ext->isExtensionKey($dao->class_name)) {
276 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
277 require_once $ext->classToPath($paymentClass);
278 }
279 else {
280 // Legacy or extension as module instance
281 if (empty($paymentClass)) {
282 $paymentClass = 'CRM_Core_' . $dao->class_name;
283
284 }
285 }
286
287 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($dao->processor_id, $mode);
288
289 // Should never be empty - we already established this processor_id exists and is active.
290 if (empty($paymentProcessor)) {
291 continue;
292 }
293
294 // Instantiate PP
295 $processorInstance = $paymentClass::singleton($mode, $paymentProcessor);
296
297 // Does PP implement this method, and can we call it?
298 if (!method_exists($processorInstance, $method) ||
299 !is_callable(array($processorInstance, $method))
300 ) {
301 // on the off chance there is a double implementation of this processor we should keep looking for another
302 // note that passing processor_id is more reliable & we should work to deprecate processor_name
303 continue;
304 }
305
306 // Everything, it seems, is ok - execute pp callback handler
307 $processorInstance->$method();
308 $extension_instance_found = TRUE;
309 }
310
311 if (!$extension_instance_found) CRM_Core_Error::fatal(
312 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
313 "$method method is unsupported in legacy payment processors."
314 );
315
316 // Exit here on web requests, allowing just the plain text response to be echoed
317 if ($method == 'handlePaymentNotification') {
318 CRM_Utils_System::civiExit();
319 }
320 }
321
322 /**
323 * Function to check whether a method is present ( & supported ) by the payment processor object.
324 *
325 * @param string $method method to check for.
326 *
327 * @return boolean
328 * @public
329 */
330 function isSupported($method = 'cancelSubscription') {
331 return method_exists(CRM_Utils_System::getClassName($this), $method);
332 }
333
334 function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
335 if ($action == 'cancel') {
336 $url = 'civicrm/contribute/unsubscribe';
337 }
338 elseif ($action == 'billing') {
339 //in notify mode don't return the update billing url
340 if ($this->_paymentProcessor['billing_mode'] == self::BILLING_MODE_NOTIFY) {
341 return NULL;
342 }
343 $url = 'civicrm/contribute/updatebilling';
344 }
345 elseif ($action == 'update') {
346 $url = 'civicrm/contribute/updaterecur';
347 }
348 $session = CRM_Core_Session::singleton();
349 $userId = $session->get('userID');
350 $checksumValue = "";
351
352 if ($entityID && $entity == 'membership') {
353 if (!$userId) {
354 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
355 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
356 $checksumValue = "&cs={$checksumValue}";
357 }
358 return CRM_Utils_System::url($url, "reset=1&mid={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
359 }
360
361 if ($entityID && $entity == 'contribution') {
362 if (!$userId) {
363 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
364 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
365 $checksumValue = "&cs={$checksumValue}";
366 }
367 return CRM_Utils_System::url($url, "reset=1&coid={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
368 }
369
370 if ($entityID && $entity == 'recur') {
371 if (!$userId) {
372 $sql = "
373 SELECT con.contact_id
374 FROM civicrm_contribution_recur rec
375 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
376 WHERE rec.id = %1
377 GROUP BY rec.id";
378 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
379 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
380 $checksumValue = "&cs={$checksumValue}";
381 }
382 return CRM_Utils_System::url($url, "reset=1&crid={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
383 }
384
385 if ($this->isSupported('accountLoginURL')) {
386 return $this->accountLoginURL();
387 }
388 return $this->_paymentProcessor['url_recur'];
389 }
390
391 /**
392 * Check for presence of type 1 or type 3 enabled processors (means we can do back-office submit credit/debit card trxns)
393 * @public
394 */
395 static function allowBackofficeCreditCard($template = NULL, $variableName = 'newCredit') {
396 $newCredit = FALSE;
397 // restrict to type=1 (credit card) payment processor payment_types and only include billing mode types 1 and 3
398 $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE,
399 "billing_mode IN ( 1, 3 ) AND payment_type = 1"
400 );
401 if (count($processors) > 0) {
402 $newCredit = TRUE;
403 }
404 if ($template) {
405 $template->assign($variableName, $newCredit);
406 }
407 return $newCredit;
408 }
409
410 }