dolibarr 23.0.3
paymentok.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2001-2002 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2006-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2021-2023 Waël Almoman <info@almoman.com>
6 * Copyright (C) 2021 Maxime Demarest <maxime@indelog.fr>
7 * Copyright (C) 2021 Dorian Vabre <dorian.vabre@gmail.com>
8 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
34if (!defined('NOLOGIN')) {
35 define("NOLOGIN", 1); // This means this output page does not require to be logged.
36}
37if (!defined('NOCSRFCHECK')) {
38 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
39}
40if (!defined('NOIPCHECK')) {
41 define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
42}
43if (!defined('NOBROWSERNOTIF')) {
44 define('NOBROWSERNOTIF', '1');
45}
46
47if (!defined('XFRAMEOPTIONS_ALLOWALL')) {
48 define('XFRAMEOPTIONS_ALLOWALL', '1');
49}
50
51// For MultiCompany module.
52// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
53// Because 2 entities can have the same ref.
54$entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1));
55if (is_numeric($entity)) {
56 define("DOLENTITY", $entity);
57}
58
59// Load Dolibarr environment
60require '../../main.inc.php';
71require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
72require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
73require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
74if (isModEnabled('paypal')) {
75 require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
76 require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php';
77}
78
79// Hook to be used by external payment modules (ie Payzen, ...)
80$hookmanager = new HookManager($db);
81
82$hookmanager->initHooks(array('newpayment'));
83
84$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paypal", "stripe"));
85
86// Clean parameters
87$PAYPAL_API_USER = "";
88$PAYPAL_API_PASSWORD = "";
89$PAYPAL_API_SIGNATURE = "";
90$PAYPAL_API_SANDBOX = "";
91$PAYPALTOKEN = "";
92$PAYPALPAYERID = "";
93if (isModEnabled('paypal')) {
94 $PAYPAL_API_USER = getDolGlobalString('PAYPAL_API_USER');
95 $PAYPAL_API_PASSWORD = getDolGlobalString('PAYPAL_API_PASSWORD');
96 $PAYPAL_API_SIGNATURE = getDolGlobalString('PAYPAL_API_SIGNATURE');
97 $PAYPAL_API_SANDBOX = getDolGlobalString('PAYPAL_API_SANDBOX');
98
99 $PAYPALTOKEN = GETPOST('TOKEN');
100 if (empty($PAYPALTOKEN)) {
101 $PAYPALTOKEN = GETPOST('token');
102 }
103 $PAYPALPAYERID = GETPOST('PAYERID');
104 if (empty($PAYPALPAYERID)) {
105 $PAYPALPAYERID = GETPOST('PayerID');
106 }
107}
108
109$FULLTAG = GETPOST('FULLTAG');
110if (empty($FULLTAG)) {
111 $FULLTAG = GETPOST('fulltag');
112}
113$source = GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha');
114$ref = GETPOST('ref');
115
116$suffix = GETPOST("suffix", 'aZ09');
117$membertypeid = GETPOSTINT("membertypeid");
118
119
120// Detect $paymentmethod
121$paymentmethod = '';
122$reg = array();
123if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) {
124 $paymentmethod = $reg[1];
125}
126if (empty($paymentmethod)) {
127 dol_syslog("***** paymentok.php was called with a non valid parameter FULLTAG=".$FULLTAG, LOG_DEBUG, 0, '_payment');
128 dol_print_error(null, 'The callback url does not contain a parameter fulltag that should help us to find the payment method used');
129 exit;
130}
131
132dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLTAG=".$FULLTAG." REQUEST_URI=".$_SERVER["REQUEST_URI"], LOG_DEBUG, 0, '_payment');
133
134// Detect $ws
135$reg_ws = array();
136$ws = preg_match('/WS=([^\.]+)/', $FULLTAG, $reg_ws) ? $reg_ws[1] : 0;
137if ($ws) {
138 dol_syslog("paymentok.php page is invoked from a website with ref ".$ws.". It performs actions and then redirects back to this website. A page with ref paymentok must be created for this website.", LOG_DEBUG, 0, '_payment');
139}
140
141$validpaymentmethod = getValidOnlinePaymentMethods($paymentmethod);
142
143// Security check
144if (empty($validpaymentmethod)) {
145 httponly_accessforbidden('No valid payment mode');
146}
147
148// Common variables
149$creditor = $mysoc->name;
150$paramcreditor = 'ONLINE_PAYMENT_CREDITOR';
151$paramcreditorlong = 'ONLINE_PAYMENT_CREDITOR_'.$suffix;
152if (getDolGlobalString($paramcreditorlong)) {
153 $creditor = getDolGlobalString($paramcreditorlong); // use label long of the seller to show
154} elseif (getDolGlobalString($paramcreditor)) {
155 $creditor = getDolGlobalString($paramcreditor); // use label short of the seller to show
156}
157
158
159$ispaymentok = false;
160// If payment is ok
161$PAYMENTSTATUS = $TRANSACTIONID = $LONGTRANSACTIONID = $TAXAMT = $NOTE = '';
162// If payment is ko
163$ErrorCode = $ErrorShortMsg = $ErrorLongMsg = $ErrorSeverityCode = '';
164
165
166$object = new stdClass(); // For triggers
167
168$error = 0;
169
170// Check if we have redirtodomain to do.
171$ws_virtuelhost = null;
172$ws_id = 0;
173$doactionsthenredirect = 0;
174if ($ws) {
175 $doactionsthenredirect = 1;
176 include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';
177 $website = new Website($db);
178 $result = $website->fetch(0, $ws);
179 if ($result > 0) {
180 $ws_virtuelhost = $website->virtualhost;
181 $ws_id = $website->id;
182 }
183}
184
185/*
186 * Actions
187 */
188
189// None
190
191
192/*
193 * View
194 */
195
196$now = dol_now();
197
198dol_syslog("Callback url when a payment was done. doactionsthenredirect=".$doactionsthenredirect." query_string=".(empty($_SERVER["QUERY_STRING"]) ? '' : dol_escape_htmltag($_SERVER["QUERY_STRING"]))." script_uri=".(empty($_SERVER["SCRIPT_URI"]) ? '' : dol_escape_htmltag($_SERVER["SCRIPT_URI"])), LOG_DEBUG, 0, '_payment');
199dol_syslog("_SERVER[SERVER_NAME] = ".(empty($_SERVER["SERVER_NAME"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_NAME"])), LOG_DEBUG, 0, '_payment');
200dol_syslog("_SERVER[SERVER_ADDR] = ".(empty($_SERVER["SERVER_ADDR"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_ADDR"])), LOG_DEBUG, 0, '_payment');
201
202$tracepost = "";
203foreach ($_POST as $k => $v) {
204 if (is_scalar($k) && is_scalar($v)) {
205 $tracepost .= "$k=$v\n";
206 }
207}
208dol_syslog("POST: ".$tracepost, LOG_DEBUG, 0, '_payment');
209
210$tracesession = "";
211foreach ($_SESSION as $k => $v) {
212 if (is_scalar($k) && is_scalar($v) && in_array($k, array('currencyCodeType', 'errormessage', 'FinalPaymentAmt', 'ipaddress', 'onlinetoken', 'payerID', 'paymentType', 'TRANSACTIONID', 'paymentoksessionkey', 'paymentkosessionkey'))) {
213 $tracesession .= "$k=$v\n";
214 }
215}
216dol_syslog("session_id=".session_id()." SESSION: ".$tracesession, LOG_DEBUG, 0, '_payment');
217
218dol_syslog("paymentoksessioncode=".GETPOST('paymentoksessioncode')." SESSION['paymentoksessioncode']=".$_SESSION['paymentoksessioncode'], LOG_DEBUG, 0, '_payment');
219
220$head = '';
221if (getDolGlobalString('ONLINE_PAYMENT_CSS_URL')) {
222 $head = '<link rel="stylesheet" type="text/css" href="' . getDolGlobalString('ONLINE_PAYMENT_CSS_URL').'?lang='.$langs->defaultlang.'">'."\n";
223}
224
225$conf->dol_hide_topmenu = 1;
226$conf->dol_hide_leftmenu = 1;
227
228
229// Show header
230if (empty($doactionsthenredirect)) {
231 $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
232 llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);
233
234
235 // Show page content id="dolpaymentdiv"
236 print '<span id="dolpaymentspan"></span>'."\n";
237 print '<div id="dolpaymentdiv" class="center">'."\n";
238
239
240 // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo)
241 // Define logo and logosmall
242 $logosmall = $mysoc->logo_small;
243 $logo = $mysoc->logo;
244 $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix;
245 if (getDolGlobalString($paramlogo)) {
246 $logosmall = getDolGlobalString($paramlogo);
247 } elseif (getDolGlobalString('ONLINE_PAYMENT_LOGO')) {
248 $logosmall = getDolGlobalString('ONLINE_PAYMENT_LOGO');
249 }
250 //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
251 // Define urllogo
252 $urllogo = '';
253 $urllogofull = '';
254 if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
255 $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
256 $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
257 } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
258 $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
259 $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
260 }
261
262 // Output html code for logo
263 if ($urllogo) {
264 print '<div class="backgreypublicpayment">';
265 print '<div class="logopublicpayment">';
266 print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
267 print '>';
268 print '</div>';
269 if (!getDolGlobalString('MAIN_HIDE_POWERED_BY')) {
270 print '<div class="poweredbypublicpayment opacitymedium right"><a class="poweredbyhref" href="https://www.dolibarr.org?utm_medium=website&utm_source=poweredby" target="dolibarr" rel="noopener">'.$langs->trans("PoweredBy").'<br><img class="poweredbyimg" src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>';
271 }
272 print '</div>';
273 } elseif ($creditor) {
274 print '<div class="backgreypublicpayment">';
275 print '<div class="logopublicpayment">';
276 print $creditor;
277 print '</div>';
278 print '</div>';
279 }
280 if (getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT')) {
281 print '<div class="backimagepublicpayment">';
282 print '<img id="idMAIN_IMAGE_PUBLIC_PAYMENT" src="' . getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT').'">';
283 print '</div>';
284 }
285
286
287 print '<br><br><br>';
288}
289
290
291// Add steps to validate payment is complete when we enter this page
292$service = $paymentmethod; // to have a default value. We may change it later for 'StripeLive' or 'StripeTest'...
293
294// For Paypal: validate the payment (Paypal need another step after the callback return to validate the payment).
295if (isModEnabled('paypal') && $paymentmethod === 'paypal') { // We call this page only if payment is ok on payment system
296 if (!empty($PAYPALTOKEN)) {
297 // TODO: Move this block to the top to ensure all session variables (e.g., TRANSACTIONID, FinalPaymentAmt, currencyCodeType, etc.) are loaded before executing checks for any payment module.
298 // Get on url call
299 $onlinetoken = $PAYPALTOKEN;
300 $fulltag = $FULLTAG;
301 $payerID = !empty($PAYPALPAYERID) ? $PAYPALPAYERID : '';
302 // Set by newpayment.php
303 $ipaddress = $_SESSION['ipaddress'];
304 $currencyCodeType = $_SESSION['currencyCodeType'];
305 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
306 $paymentType = $_SESSION['PaymentType']; // Value can be 'Mark', 'Sole', 'Sale' for example
307
308 dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
309
310 // Validate record
311 if (!empty($paymentType)) {
312 dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment');
313 $resArray = getDetails($onlinetoken);
314 //var_dump($resarray);
315
316 $ack = strtoupper($resArray["ACK"]);
317 if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
318 // Nothing to do
319 dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
320 } else {
321 dol_syslog("Call to GetExpressCheckoutDetails return error: ".json_encode($resArray), LOG_WARNING, 0, '_payment');
322 }
323
324 dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
325 $resArray2 = confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag);
326 //var_dump($resarray);
327
328 $ack = strtoupper($resArray2["ACK"]);
329 if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
330 dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
331
332 $object->source = $source;
333 $object->ref = $ref;
334 $object->payerID = $payerID;
335 $object->fulltag = $fulltag;
336 $object->resArray = $resArray2;
337
338 // resArray was built from a string like that
339 // TOKEN=EC%2d1NJ057703V9359028&TIMESTAMP=2010%2d11%2d01T11%3a40%3a13Z&CORRELATIONID=1efa8c6a36bd8&ACK=Success&VERSION=56&BUILD=1553277&TRANSACTIONID=9B994597K9921420R&TRANSACTIONTYPE=expresscheckout&PAYMENTTYPE=instant&ORDERTIME=2010%2d11%2d01T11%3a40%3a12Z&AMT=155%2e57&FEEAMT=5%2e54&TAXAMT=0%2e00&CURRENCYCODE=EUR&PAYMENTSTATUS=Completed&PENDINGREASON=None&REASONCODE=None
340 $PAYMENTSTATUS = urldecode($resArray2["PAYMENTSTATUS"]); // Should contains 'Completed'
341 $TRANSACTIONID = urldecode($resArray2["TRANSACTIONID"]);
342 $TAXAMT = urldecode($resArray2["TAXAMT"]);
343 $NOTE = urldecode($resArray2["NOTE"]);
344
345 $ispaymentok = true;
346 } else {
347 dol_syslog("Call to DoExpressCheckoutPayment return error: ".json_encode($resArray2), LOG_WARNING, 0, '_payment');
348
349 //Display a user friendly Error on the page using any of the following error information returned by PayPal
350 $ErrorCode = urldecode($resArray2["L_ERRORCODE0"]);
351 $ErrorShortMsg = urldecode($resArray2["L_SHORTMESSAGE0"]);
352 $ErrorLongMsg = urldecode($resArray2["L_LONGMESSAGE0"]);
353 $ErrorSeverityCode = urldecode($resArray2["L_SEVERITYCODE0"]);
354 }
355 } else {
356 $ErrorCode = "SESSIONEXPIRED";
357 $ErrorLongMsg = "Session expired. Can't retrieve PaymentType. Payment has not been validated.";
358 $ErrorShortMsg = "Session expired";
359
360 dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
361 dol_print_error(null, 'Session expired');
362 }
363 } else {
364 $ErrorCode = "PAYPALTOKENNOTDEFINED";
365 $ErrorLongMsg = "The parameter PAYPALTOKEN was not defined. Payment has not been validated.";
366 $ErrorShortMsg = "Parameter PAYPALTOKEN not defined";
367
368 dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
369 dol_print_error(null, 'PAYPALTOKEN not defined');
370 }
371}
372
373// For Paybox
374if (isModEnabled('paybox') && $paymentmethod === 'paybox') {
375 // TODO Add a check to validate that payment is ok.
376 $ispaymentok = true; // We will do the rest of code
377}
378
379// For Stripe
380if (isModEnabled('stripe') && $paymentmethod === 'stripe') {
381 // TODO: Move this block to the top to ensure all session variables (e.g., TRANSACTIONID, FinalPaymentAmt, currencyCodeType, etc.) are loaded before executing checks for any payment module.
382 if (empty($TRANSACTIONID)) {
383 $TRANSACTIONID = empty($_SESSION['TRANSACTIONID']) ? '' : $_SESSION['TRANSACTIONID']; // pi_... or ch_...
384 if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
385 // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
386 $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
387 }
388 }
389 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
390 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
391
392 $service = 'StripeTest';
393 $servicestatus = 0;
394 if (getDolGlobalString('STRIPE_LIVE')/* && !GETPOSTINT('forcesandbox') */) {
395 $service = 'StripeLive';
396 $servicestatus = 1;
397 }
398
399 // Check we are coming from the newpaymentpage
400 if (GETPOST('paymentoksessioncode') !== $_SESSION['paymentoksessioncode']) {
401 $error++;
402 $errmsg = 'Attempted direct access to the paymentok page without a valid session.';
403 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
404 }
405
406 // Check on payment platform that the payment has been really validated
407 if (!$error && $TRANSACTIONID) {
408 // Stripe payment verification via Stripe API
409 try {
410 include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
411 $stripe = new Stripe($db);
412 $stripeacc = $stripe->getStripeAccount($service);
413
414 // Use the correct Stripe API key
415 global $stripearrayofkeysbyenv;
416 \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
417
418 try {
419 if (empty($stripeacc)) {
420 $paymentIntent = \Stripe\PaymentIntent::retrieve($TRANSACTIONID);
421 } else {
422 $paymentIntent = \Stripe\PaymentIntent::retrieve($TRANSACTIONID, array("stripe_account" => $stripeacc));
423 }
424
425 // Check amount and currency
426 $expectedAmount = (int) round($FinalPaymentAmt * 100); // Stripe uses cents
427 $expectedCurrency = strtolower($currencyCodeType);
428
429 if ((int) $paymentIntent->amount !== $expectedAmount || strtolower($paymentIntent->currency) !== $expectedCurrency) {
430 $error++;
431 $errmsg = 'Stripe payment information mismatch: expected amount ' . $expectedAmount . ' and currency ' . $expectedCurrency . ', got amount ' . $paymentIntent->amount . ' and currency ' . $paymentIntent->currency;
432 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
433 }
434 if ($paymentIntent->status !== 'succeeded') {
435 $error++;
436 $errmsg = 'Stripe payment not succeeded. Status: ' . $paymentIntent->status;
437 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
438 }
439
440 // Get $customerid and $pkey to forge $LONGTRANSACTIONID
441 $customerid = '';
442 $pkey = '';
443 if ($paymentIntent instanceof \Stripe\PaymentIntent) {
444 $customerid = $paymentIntent->customer;
445 }
446 if (isset($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])) {
447 $pkey = $stripearrayofkeysbyenv[$servicestatus]['publishable_key'];
448 }
449
450 if ($customerid && $pkey) {
451 $LONGTRANSACTIONID = $TRANSACTIONID.':'.$customerid.'@'.$pkey;
452 }
453 } catch (\Stripe\Exception\ApiErrorException $e) {
454 $error++;
455 $errormessage = "Stripe API error: ".$e->getMessage();
456 dol_syslog($errormessage, LOG_ERR, 0, '_payment');
457 setEventMessages($e->getMessage(), null, 'errors');
458 } catch (Exception $e) {
459 $error++;
460 $errormessage = "CantRetrievePaymentIntent: ".$e->getMessage();
461 dol_syslog($errormessage, LOG_ERR, 0, '_payment');
462 setEventMessages($e->getMessage(), null, 'errors');
463 }
464 } catch (Exception $e) {
465 $error++;
466 $errmsg = 'Stripe API error: ' . $e->getMessage();
467 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
468 }
469 } else {
470 $error++;
471 $errmsg = 'Stripe payment verification failed: TRANSACTIONID is not set or session key does not match.';
472 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
473 setEventMessages($errmsg, null, 'errors');
474 }
475
476 if (!$error) {
477 $ispaymentok = true; // We will do the rest of code
478 } else {
479 $ispaymentok = false; // We won't do the rest of code
480 }
481}
482
483// For other payment modules
484if (!in_array($paymentmethod, array('paypal', 'paybox', 'stripe'))) {
485 // Check status of the object to verify if it is paid by external payment modules
486 $action = '';
487 $parameters = [
488 'paymentmethod' => $paymentmethod,
489 ];
490 $reshook = $hookmanager->executeHooks('isPaymentOK', $parameters, $object, $action);
491 if ($reshook >= 0) {
492 if (isset($hookmanager->resArray['ispaymentok'])) {
493 dol_syslog('ispaymentok overwrite by hook return with value='.$hookmanager->resArray['ispaymentok'], LOG_DEBUG, 0, '_payment');
494 $ispaymentok = $hookmanager->resArray['ispaymentok'];
495 }
496 } else {
497 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
498 }
499}
500
501// TODO: Move this block to the top to ensure all session variables (e.g., TRANSACTIONID, FinalPaymentAmt, currencyCodeType, etc.) are loaded before executing checks for any payment module.
502// Get variable into the session env
503if (empty($ipaddress)) {
504 $ipaddress = $_SESSION['ipaddress'];
505}
506if (empty($FinalPaymentAmt)) {
507 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
508}
509if (empty($currencyCodeType)) {
510 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
511}
512if (empty($paymentType)) { // Seems used only by Paypal
513 $paymentType = empty($_SESSION["paymentType"]) ? '' : $_SESSION["paymentType"];
514}
515
516if (empty($TRANSACTIONID)) {
517 $TRANSACTIONID = empty($_SESSION['TRANSACTIONID']) ? '' : $_SESSION['TRANSACTIONID']; // pi_... or ch_...
518 if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
519 // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
520 $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
521 }
522}
523
524$fulltag = $FULLTAG;
525$tmptag = dolExplodeIntoArray($fulltag, '.', '=');
526
527
528dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG_DEBUG, 0, '_payment');
529
530
531// Set $appli for emails title
532$appli = $mysoc->name;
533
534
535// Make complementary actions (post payment actions if payment is ok)
536$ispostactionok = 0;
537$paymentTypeId = 0;
538$postactionmessages = array();
539if ($ispaymentok) {
540 // Set permission for the anonymous user
541 if (empty($user->rights->societe)) {
542 $user->rights->societe = new stdClass();
543 }
544 if (empty($user->rights->facture)) {
545 $user->rights->facture = new stdClass();
546 $user->rights->facture->invoice_advance = new stdClass();
547 }
548 if (empty($user->rights->adherent)) {
549 $user->rights->adherent = new stdClass();
550 $user->rights->adherent->cotisation = new stdClass();
551 }
552 $user->rights->societe->creer = 1;
553 $user->rights->facture->creer = 1;
554 $user->rights->facture->invoice_advance->validate = 1;
555 $user->rights->adherent->cotisation->creer = 1;
556
557 if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) {
558 // Validate member
559 // Create subscription
560 // Create complementary actions (this include creation of thirdparty)
561 // Send confirmation email
562
563 // Record subscription
564 include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
565 include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
566 include_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
567 $adht = new AdherentType($db);
568 $object = new Adherent($db);
569
570 $result1 = $object->fetch((int) $tmptag['MEM']);
571 $result2 = $adht->fetch($object->typeid);
572
573 $defaultdelay = !empty($adht->duration_value) ? $adht->duration_value : 1;
574 $defaultdelayunit = !empty($adht->duration_unit) ? $adht->duration_unit : 'y';
575
576 dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment');
577
578 if ($result1 > 0 && $result2 > 0) {
579 if ($paymentmethod == 'paybox') {
580 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
581 }
582 if ($paymentmethod == 'paypal') {
583 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
584 }
585 if ($paymentmethod == 'stripe') {
586 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
587 }
588 if (empty($paymentTypeId)) {
589 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
590
591 if (empty($paymentType)) {
592 $paymentType = 'CB';
593 }
594 // May return nothing when paymentType means nothing
595 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
596 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
597
598 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
599 if (empty($paymentTypeId) || $paymentTypeId < 0) {
600 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
601 }
602 }
603
604 dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId." currencyCodeType=".$currencyCodeType, LOG_DEBUG, 0, '_payment');
605
606 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
607 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
608 // Security protection:
609 if (empty($adht->caneditamount)) { // If we didn't allow members to choose their membership amount (if the amount is allowed in edit mode, no need to check)
610 if ($object->status == $object::STATUS_DRAFT) { // If the member is not yet validated, we check that the amount is the same as expected.
611 $typeid = $object->typeid;
612 $amountbytype = $adht->amountByType(1); // Load the array of amount per type
613
614 // Set amount for the subscription:
615 // - First check the amount of the member type.
616 $amountexpected = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
617 // - If not found, take the default amount
618 if (empty($amountexpected) && getDolGlobalString('MEMBER_NEWFORM_AMOUNT')) {
619 $amountexpected = getDolGlobalString('MEMBER_NEWFORM_AMOUNT');
620 }
621 // - If not set, we accept to have amount defined as parameter (for backward compatibility).
622 //if (empty($amount)) {
623 // $amount = (GETPOST('amount') ? price2num(GETPOST('amount', 'alpha'), 'MT', 2) : '');
624 //}
625 // - If a min is set, we take it into account
626 $amountexpected = max(0, (float) $amountexpected, (float) getDolGlobalInt("MEMBER_MIN_AMOUNT"));
627
628 if ($amountexpected && $amountexpected != $FinalPaymentAmt) {
629 $error++;
630 $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') propagated by payment page differs from the expected value for membership ('.$amountexpected.'). May be a hack to try to pay a different amount ?';
631 $postactionmessages[] = $errmsg;
632 $ispostactionok = -1;
633 dol_syslog("Failed to validate member (bad amount check): ".$errmsg, LOG_ERR, 0, '_payment');
634 }
635 }
636 }
637
638 // Security protection:
639 if (getDolGlobalInt('MEMBER_MIN_AMOUNT')) {
640 if ($FinalPaymentAmt < getDolGlobalInt('MEMBER_MIN_AMOUNT')) {
641 $error++;
642 $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') is lower than the minimum allowed (' . getDolGlobalString('MEMBER_MIN_AMOUNT').'). May be a hack to try to pay a different amount ?';
643 $postactionmessages[] = $errmsg;
644 $ispostactionok = -1;
645 dol_syslog("Failed to validate member (amount propagated from payment page is lower than allowed minimum): ".$errmsg, LOG_ERR, 0, '_payment');
646 }
647 }
648
649 // Security protection:
650 if ($currencyCodeType && $currencyCodeType != $conf->currency) { // Check that currency is the good one
651 $error++;
652 $errmsg = 'Value of currencyCodeType ('.$currencyCodeType.') differs from value expected for membership ('.$conf->currency.'). May be a hack to try to pay a different amount ?';
653 $postactionmessages[] = $errmsg;
654 $ispostactionok = -1;
655 dol_syslog("Failed to validate member (bad currency check): ".$errmsg, LOG_ERR, 0, '_payment');
656 }
657
658 if (! $error) {
659 // We validate the member (no effect if it is already validated)
660 $result = ($object->status == $object::STATUS_EXCLUDED) ? -1 : $object->validate($user); // if membre is excluded (status == -2) the new validation is not possible
661 if ($result < 0 || empty($object->datevalid)) {
662 $error++;
663 $errmsg = $object->error;
664 $postactionmessages[] = $errmsg;
665 $postactionmessages = array_merge($postactionmessages, $object->errors);
666 $ispostactionok = -1;
667 dol_syslog("Failed to validate member: ".$errmsg, LOG_ERR, 0, '_payment');
668 }
669 }
670
671 // Guess the subscription start date
672 $datesubscription = $object->datevalid; // By default, the subscription start date is the payment date
673 if ($object->datefin > 0) {
674 $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
675 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER')) {
676 $datesubscription = dol_time_plus_duree($now, (int) substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), 0, -1), substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), -1));
677 }
678 // Now do a correction of the suggested date
679 if (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "m") {
680 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"), (int) dol_print_date($datesubscription, "%m"));
681 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "3m") {
682 $datesubscription = dol_time_plus_duree($object->datefin, -3, 'm');
683 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"), (int) dol_print_date($datesubscription, "%m"));
684 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "Y") {
685 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"));
686 }
687
688 $datesubend = 0;
689 if ($datesubscription && $defaultdelay && $defaultdelayunit) {
690 $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
691 // the new end date of subscription must be in futur
692 while ($datesubend < $now) {
693 $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
694 $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
695 }
696 $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
697 }
698
699 // Set output language
700 $outputlangs = new Translate('', $conf);
701 $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? (string) $mysoc->default_lang : (string) $object->thirdparty->default_lang);
702 $paymentdate = $now;
703 $amount = $FinalPaymentAmt;
704 $formatteddate = dol_print_date($paymentdate, 'dayhour', 'auto', $outputlangs);
705 $label = $langs->trans("OnlineSubscriptionPaymentLine", $formatteddate, $paymentmethod, $ipaddress, $TRANSACTIONID);
706
707 // Payment information
708 $accountid = 0;
709 if ($paymentmethod == 'paybox') {
710 $accountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
711 }
712 if ($paymentmethod == 'paypal') {
713 $accountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
714 }
715 if ($paymentmethod == 'stripe') {
716 $accountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
717 }
718
719 //Get bank account for a specific paymentmedthod
720 $parameters = [
721 'paymentmethod' => $paymentmethod,
722 ];
723 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
724 if ($reshook >= 0) {
725 if (isset($hookmanager->resArray['bankaccountid'])) {
726 dol_syslog('accountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
727 $accountid = $hookmanager->resArray['bankaccountid'];
728 }
729 }
730 if ($accountid < 0) {
731 $error++;
732 $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
733 $postactionmessages[] = $errmsg;
734 $ispostactionok = -1;
735 dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
736 }
737
738 $operation = dol_getIdFromCode($db, $paymentTypeId, 'c_paiement', 'id', 'code', 1); // Payment mode code returned from payment mode id
739 $num_chq = '';
740 $emetteur_nom = '';
741 $emetteur_banque = '';
742 // Define default choice for complementary actions
743 $option = '';
744 if (getDolGlobalString('ADHERENT_BANK_USE') == 'bankviainvoice' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
745 $option = 'bankviainvoice';
746 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'bankdirect' && isModEnabled("bank")) {
747 $option = 'bankdirect';
748 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'invoiceonly' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
749 $option = 'invoiceonly';
750 }
751 if (empty($option)) {
752 $option = 'none';
753 }
754 $sendalsoemail = 1;
755 $crowid = 0;
756
757 // Record the subscription then complementary actions
758 $db->begin();
759
760 // Create subscription
761 if (!$error) {
762 dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
763
764 $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
765 if ($crowid <= 0) {
766 $error++;
767 $errmsg = $object->error;
768 $postactionmessages[] = $errmsg;
769 $ispostactionok = -1;
770 } else {
771 $postactionmessages[] = 'Subscription created (id='.$crowid.')';
772 $ispostactionok = 1;
773 }
774 }
775
776 $autocreatethirdparty = 0;
777
778 if (!$error) {
779 dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
780
781 $autocreatethirdparty = 1; // will create third party if member not yet linked to a thirdparty
782
783 $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
784 if ($result < 0) {
785 dol_syslog("Error ".$object->error." ".implode(',', $object->errors), LOG_DEBUG, 0, '_payment');
786
787 $error++;
788 $postactionmessages[] = $object->error;
789 $postactionmessages = array_merge($postactionmessages, $object->errors);
790 $ispostactionok = -1;
791 } else {
792 if ($option == 'bankviainvoice') {
793 $postactionmessages[] = 'Invoice, payment and bank record created';
794 dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
795 }
796 if ($option == 'bankdirect') {
797 $postactionmessages[] = 'Bank record created';
798 dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
799 }
800 if ($option == 'invoiceonly') {
801 $postactionmessages[] = 'Invoice recorded';
802 dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
803 }
804 $ispostactionok = 1;
805
806 // If an invoice was created, it is into $object->invoice
807 }
808 }
809
810 if (!$error) {
811 // If payment using Stripe, save the Stripe payment info into societe_account
812 if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
813 $thirdparty_id = ($object->socid ? $object->socid : $object->fk_soc);
814
815 dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
816
817 $service = 'StripeTest';
818 $servicestatus = 0;
819 if (getDolGlobalString('STRIPE_LIVE')/* && !GETPOST('forcesandbox', 'alpha') */) {
820 $service = 'StripeLive';
821 $servicestatus = 1;
822 }
823 $stripeacc = ''; // No Oauth/connect use for public pages
824
825 $thirdparty = new Societe($db);
826 $thirdparty->fetch($thirdparty_id);
827
828 include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
829 $stripe = new Stripe($db);
830 //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
831
832 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
833
834 if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
835 dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
836
837 try {
838 global $stripearrayofkeysbyenv;
839 \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
840
841 if (preg_match('/^pi_/', $TRANSACTIONID)) {
842 // This may throw an error if not found.
843 $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
844 } else {
845 // This throw an error if not found
846 $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
847 }
848
849 if ($chpi) {
850 $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
851
852 if (empty($stripecu)) {
853 // This include the INSERT
854 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
855
856 // Link this customer to the payment intent
857 if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
858 \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
859 }
860 } else {
861 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
862 $sql .= " VALUES (".((int) $thirdparty_id).", '', '".$db->escape($stripecu)."', 'stripe', '".$db->escape($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])."', ".((int) $servicestatus).", ".((int) $conf->entity).", '".$db->idate(dol_now())."', 0)";
863 $resql = $db->query($sql);
864 if (!$resql) { // should not happen
865 $error++;
866 $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
867 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
868 $postactionmessages[] = $errmsg;
869 $ispostactionok = -1;
870 }
871 }
872 } else { // should not happen
873 $error++;
874 $errmsg = 'Failed to retrieve paymentintent or charge from id';
875 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
876 $postactionmessages[] = $errmsg;
877 $ispostactionok = -1;
878 }
879 } catch (Exception $e) { // should not happen
880 $error++;
881 $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
882 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
883 $postactionmessages[] = $errmsg;
884 $ispostactionok = -1;
885 }
886 }
887 }
888 }
889
890 if (!$error) {
891 $db->commit();
892 } else {
893 $db->rollback();
894 }
895
896 // Set string to use to send email info
897 $infouserlogin = '';
898
899 // Create external user
900 if (getDolGlobalString('ADHERENT_CREATE_EXTERNAL_USER_LOGIN')) {
901 $nuser = new User($db);
902 $tmpuser = dol_clone($object, 0); // $object is type Adherent
903
904 // Check if a user login already exists for this member or not
905 $found = 0;
906 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."user WHERE fk_member = ".((int) $object->id);
907 $resqlcount = $db->query($sql);
908 if ($resqlcount) {
909 $objcount = $db->fetch_object($resqlcount);
910 if ($objcount) {
911 $found = $objcount->nb;
912 }
913 }
914
915 if (!$found) {
916 $result = $nuser->create_from_member($tmpuser, $object->login);
917 $newpassword = $nuser->setPassword($user, '');
918
919 if ($result < 0) {
920 $outputlangs->load("errors");
921 $postactionmessages[] = 'Error in create external user : '.$nuser->error;
922 } else {
923 $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
924 $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
925 }
926 } else {
927 $outputlangs->load("errors");
928 $postactionmessages[] = 'No user created because a user linked to member already exists';
929 }
930 }
931
932 // Send email to member
933 if (!$error) {
934 dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
935
936 // Send confirmation Email
937 if ($object->email && $sendalsoemail) {
938 $subject = '';
939 $msg = '';
940
941 // Send subscription email
942 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
943 $formmail = new FormMail($db);
944 // Load traductions files required by page
945 $outputlangs->loadLangs(array("main", "members"));
946 // Get email content from template
947 $arraydefaultmessage = null;
948 $labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION');
949
950 if (!empty($labeltouse)) {
951 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
952 }
953
954 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
955 $subject = $arraydefaultmessage->topic;
956 $msg = $arraydefaultmessage->content;
957 }
958
959 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
960
961 if ($infouserlogin) {
962 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
963 }
964
965 complete_substitutions_array($substitutionarray, $outputlangs, $object);
966 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
967 $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
968
969 // Attach a file ?
970 $file = '';
971 $listofpaths = array();
972 $listofnames = array();
973 $listofmimes = array();
974 if (is_object($object->invoice)) {
975 $invoicediroutput = $conf->facture->dir_output;
976 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
977 $file = $fileparams['fullname'];
978
979 $listofpaths = array($file);
980 $listofnames = array(basename($file));
981 $listofmimes = array(dol_mimetype($file));
982 }
983
984 $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
985
986 $result = $object->sendEmail($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
987
988 if ($result < 0) {
989 $errmsg = $object->error;
990 $postactionmessages[] = $errmsg;
991 $ispostactionok = -1;
992 } else {
993 if ($file) {
994 $postactionmessages[] = 'Email sent to member (with invoice document attached)';
995 } else {
996 $postactionmessages[] = 'Email sent to member (without any attached document)';
997 }
998
999 // TODO Add actioncomm event
1000 }
1001 }
1002 }
1003 } else {
1004 $postactionmessages[] = 'Failed to get a valid value for "amount paid" or "payment type" to record the payment of subscription for member '.$tmptag['MEM'].'. May be payment was already recorded.';
1005 $ispostactionok = -1;
1006 }
1007 } else {
1008 $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
1009 $ispostactionok = -1;
1010 }
1011 } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
1012 // Record payment
1013 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1014 $object = new Facture($db);
1015 $result = $object->fetch((int) $tmptag['INV']);
1016 if ($result) {
1017 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1018
1019 $paymentTypeId = 0;
1020 if ($paymentmethod === 'paybox') {
1021 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1022 }
1023 if ($paymentmethod === 'paypal') {
1024 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1025 }
1026 if ($paymentmethod === 'stripe') {
1027 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1028 }
1029 if (empty($paymentTypeId)) {
1030 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1031
1032 if (empty($paymentType)) {
1033 $paymentType = 'CB';
1034 }
1035 // May return nothing when paymentType means nothing
1036 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1037 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1038
1039 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1040 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1041 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1042 }
1043 }
1044
1045 dol_syslog("FinalPaymentAmt = ".$FinalPaymentAmt." paymentTypeId = ".$paymentTypeId, LOG_DEBUG, 0, '_payment');
1046
1047 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1048 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1049 $db->begin();
1050
1051 // Creation of payment line
1052 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1053 $paiement = new Paiement($db);
1054 $paiement->datepaye = $now;
1055 if ($currencyCodeType == $conf->currency) {
1056 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1057 } else {
1058 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1059
1060 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1061 $ispostactionok = -1;
1062 $error++; // Not yet supported
1063 }
1064 $paiement->paiementid = $paymentTypeId;
1065 $paiement->num_payment = '';
1066 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1067
1068 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1069 if ($LONGTRANSACTIONID) {
1070 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1071 } else {
1072 $paiement->ext_payment_id = $TRANSACTIONID;
1073 }
1074 $paiement->ext_payment_site = $service;
1075
1076 // Validate invoice if not already validated (this can happen for automatically generated invoices with a free amount)
1077 if (!$error && $object->status == Facture::STATUS_DRAFT) {
1078 $result = $object->validate($user);
1079 if ($result < 0) {
1080 $postactionmessages[] = $object->error;
1081 $ispostactionok = -1;
1082 $error++;
1083 } else {
1084 $postactionmessages[] = 'Invoice validated';
1085 $ispostactionok = 1;
1086 }
1087 }
1088
1089 if (!$error) {
1090 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1091 if ($paiement_id < 0) {
1092 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1093 $ispostactionok = -1;
1094 $error++;
1095 } else {
1096 $postactionmessages[] = 'Payment created';
1097 $ispostactionok = 1;
1098 }
1099 }
1100
1101 if (!$error && isModEnabled("bank")) {
1102 $bankaccountid = 0;
1103 if ($paymentmethod == 'paybox') {
1104 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1105 } elseif ($paymentmethod == 'paypal') {
1106 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1107 } elseif ($paymentmethod == 'stripe') {
1108 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1109 }
1110
1111 //Get bank account for a specific paymentmedthod
1112 $parameters = [
1113 'paymentmethod' => $paymentmethod,
1114 ];
1115 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1116 if ($reshook >= 0) {
1117 if (isset($hookmanager->resArray['bankaccountid'])) {
1118 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1119 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1120 }
1121 }
1122 if ($bankaccountid > 0) {
1123 $label = '(CustomerInvoicePayment)';
1124 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1125 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1126 }
1127 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1128 if ($result < 0) {
1129 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1130 $ispostactionok = -1;
1131 $error++;
1132 } else {
1133 $postactionmessages[] = 'Bank transaction of payment created';
1134 $ispostactionok = 1;
1135 }
1136 } else {
1137 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1138 $ispostactionok = -1;
1139 $error++;
1140 }
1141 }
1142
1143 if (!$error) {
1144 $db->commit();
1145 } else {
1146 $db->rollback();
1147 }
1148 } else {
1149 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['INV'].'. May be payment was already recorded.';
1150 $ispostactionok = -1;
1151 }
1152 } else {
1153 $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
1154 $ispostactionok = -1;
1155 }
1156 } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
1157 include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
1158 $object = new Commande($db);
1159 $result = $object->fetch((int) $tmptag['ORD']);
1160 if ($result) {
1161 dol_syslog("We have loaded the order id=".$object->id." to use to create the invoice", LOG_DEBUG, 0, '_payment');
1162
1163 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1164
1165 $paymentTypeId = 0;
1166 if ($paymentmethod == 'paybox') {
1167 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1168 }
1169 if ($paymentmethod == 'paypal') {
1170 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1171 }
1172 if ($paymentmethod == 'stripe') {
1173 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1174 }
1175 if (empty($paymentTypeId)) {
1176 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1177
1178 if (empty($paymentType)) {
1179 $paymentType = 'CB';
1180 }
1181 // May return nothing when paymentType means nothing
1182 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1183 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1184
1185 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1186 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1187 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1188 }
1189 }
1190
1191 dol_syslog("The payment type id to use is paymentTypeId=".$paymentTypeId." and FinalPaymentAmt=".$FinalPaymentAmt, LOG_DEBUG, 0, '_payment');
1192
1193 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1194 if (isModEnabled('invoice')) {
1195 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1196 $db->begin();
1197
1198 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1199 $invoice = new Facture($db);
1200 $result = $invoice->createFromOrder($object, $user);
1201 if ($result > 0) {
1202 if ($FinalPaymentAmt != $object->total_ttc) {
1203 // The amount paid can be lower than the order only if the user tried to modified the amount from the payment page. A payment has been received but it is a hack attempt
1204 // We can add a line to reduce the amount of the invoice but with which vat ?
1205 // TODO Test if vat on line is the same everywhere, if yes we can add
1206 // $invoice->addline('Fix amount of invoice', $FinalPaymentAmt - $object->total_ttc, 1, $txtva);
1207 // TODO Send a warning email.
1208 }
1209
1210 $object->classifyBilled($user); // The invoice has been create from the order so total is the same, so we can classify order to billed (even if payment may be partial).
1211
1212 $invoice->validate($user); // This may re-classify all linked orders to billed (done previously) if amount of invoice is ok by triggers, depending on the workflow module setup.
1213
1214 // Creation of payment line (warning: if amount has been modified on page, the payment may be partial)
1215 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1216 $paiement = new Paiement($db);
1217 $paiement->datepaye = $now;
1218 if ($currencyCodeType == $conf->currency) {
1219 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1220 } else {
1221 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1222
1223 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1224 $ispostactionok = -1;
1225 $error++;
1226 }
1227 $paiement->paiementid = $paymentTypeId;
1228 $paiement->num_payment = '';
1229 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1230
1231 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1232 if ($LONGTRANSACTIONID) {
1233 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1234 } else {
1235 $paiement->ext_payment_id = $TRANSACTIONID;
1236 }
1237 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1238
1239 if (!$error) {
1240 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1241 if ($paiement_id < 0) {
1242 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1243 $ispostactionok = -1;
1244 $error++;
1245 } else {
1246 $postactionmessages[] = 'Payment created';
1247 $ispostactionok = 1;
1248 }
1249 }
1250
1251 if (!$error && isModEnabled("bank")) {
1252 $bankaccountid = 0;
1253 if ($paymentmethod == 'paybox') {
1254 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1255 } elseif ($paymentmethod == 'paypal') {
1256 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1257 } elseif ($paymentmethod == 'stripe') {
1258 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1259 }
1260
1261 //Get bank account for a specific paymentmedthod
1262 $parameters = [
1263 'paymentmethod' => $paymentmethod,
1264 ];
1265 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1266 if ($reshook >= 0) {
1267 if (isset($hookmanager->resArray['bankaccountid'])) {
1268 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1269 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1270 }
1271 }
1272 if ($bankaccountid > 0) {
1273 $label = '(CustomerInvoicePayment)';
1274 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1275 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1276 }
1277 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1278 if ($result < 0) {
1279 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1280 $ispostactionok = -1;
1281 $error++;
1282 } else {
1283 $postactionmessages[] = 'Bank transaction of payment created';
1284 $ispostactionok = 1;
1285 }
1286 } else {
1287 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1288 $ispostactionok = -1;
1289 $error++;
1290 }
1291 }
1292 } else {
1293 $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
1294 $ispostactionok = -1;
1295 $error++;
1296 }
1297
1298 if (!$error) {
1299 $db->commit();
1300 } else {
1301 $db->rollback();
1302 }
1303 } else {
1304 $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type id" (' . $paymentTypeId . ') to record the payment of order ' . $tmptag['ORD'] . '. May be payment was already recorded.';
1305 $ispostactionok = -1;
1306 }
1307 } else {
1308 $postactionmessages[] = 'Invoice module is not enable';
1309 $ispostactionok = -1;
1310 }
1311 } else {
1312 $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
1313 $ispostactionok = -1;
1314 }
1315 } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
1316 include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
1317 $don = new Don($db);
1318 $result = $don->fetch((int) $tmptag['DON']);
1319 if ($result) {
1320 $paymentTypeId = 0;
1321 if ($paymentmethod == 'paybox') {
1322 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1323 }
1324 if ($paymentmethod == 'paypal') {
1325 $paymentTypeId = getDolGlobalInt('global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1326 }
1327 if ($paymentmethod == 'stripe') {
1328 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1329 }
1330 if (empty($paymentTypeId)) {
1331 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1332
1333 if (empty($paymentType)) {
1334 $paymentType = 'CB';
1335 }
1336 // May return nothing when paymentType means nothing
1337 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1338 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1339
1340 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1341 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1342 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1343 }
1344 }
1345
1346 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1347 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1348 $db->begin();
1349
1350 // Creation of paiement line for donation
1351 include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
1352 $paiement = new PaymentDonation($db);
1353
1354 $totalpaid = $FinalPaymentAmt;
1355
1356 if ($currencyCodeType == $conf->currency) {
1357 $paiement->amounts = array($object->id => $totalpaid); // Array with all payments dispatching with donation
1358 } else {
1359 // PaymentDonation does not support multi currency
1360 $postactionmessages[] = 'Payment donation can\'t be paid with different currency than '.$conf->currency;
1361 $ispostactionok = -1;
1362 $error++; // Not yet supported
1363 }
1364
1365 $paiement->fk_donation = $don->id;
1366 $paiement->datep = $now;
1367 $paiement->paymenttype = $paymentTypeId;
1368 $paiement->num_payment = '';
1369 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1370
1371 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1372 if ($LONGTRANSACTIONID) {
1373 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1374 } else {
1375 $paiement->ext_payment_id = $TRANSACTIONID;
1376 }
1377 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1378
1379 if (!$error) {
1380 $paiement_id = $paiement->create($user, 1);
1381 if ($paiement_id < 0) {
1382 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1383 $ispostactionok = -1;
1384 $error++;
1385 } else {
1386 $postactionmessages[] = 'Payment created';
1387 $ispostactionok = 1;
1388
1389 if ($totalpaid >= $don->getRemainToPay()) {
1390 $don->valid_promesse($don->id, $user->id);
1391 $don->setPaid($don->id);
1392 }
1393 }
1394 }
1395
1396 if (!$error && isModEnabled("bank")) {
1397 $bankaccountid = 0;
1398 if ($paymentmethod == 'paybox') {
1399 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1400 } elseif ($paymentmethod == 'paypal') {
1401 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1402 } elseif ($paymentmethod == 'stripe') {
1403 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1404 }
1405
1406 //Get bank account for a specific paymentmedthod
1407 $parameters = [
1408 'paymentmethod' => $paymentmethod,
1409 ];
1410 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1411 if ($reshook >= 0) {
1412 if (isset($hookmanager->resArray['bankaccountid'])) {
1413 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1414 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1415 }
1416 }
1417 if ($bankaccountid > 0) {
1418 $label = '(DonationPayment)';
1419 $result = $paiement->addPaymentToBank($user, 'payment_donation', $label, $bankaccountid, '', '');
1420 if ($result < 0) {
1421 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1422 $ispostactionok = -1;
1423 $error++;
1424 } else {
1425 $postactionmessages[] = 'Bank transaction of payment created';
1426 $ispostactionok = 1;
1427 }
1428 } else {
1429 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1430 $ispostactionok = -1;
1431 $error++;
1432 }
1433 }
1434
1435 if (!$error) {
1436 $db->commit();
1437 } else {
1438 $db->rollback();
1439 }
1440 } else {
1441 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of donation '.$tmptag['DON'].'. May be payment was already recorded.';
1442 $ispostactionok = -1;
1443 }
1444 } else {
1445 $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
1446 $ispostactionok = -1;
1447 }
1448
1449 // TODO send email with acknowledgment for the donation
1450 // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
1451 } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
1452 // Record payment for registration to an event for an attendee
1453 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1454 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1455 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1456 $object = new Facture($db);
1457 $result = $object->fetch((int) $ref); // @phan-suppress-curren-line PhanPluginSuspiciousParamPosition
1458 if ($result) {
1459 $paymentTypeId = 0;
1460 if ($paymentmethod == 'paybox') {
1461 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1462 }
1463 if ($paymentmethod == 'paypal') {
1464 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1465 }
1466 if ($paymentmethod == 'stripe') {
1467 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1468 }
1469 if (empty($paymentTypeId)) {
1470 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1471
1472 if (empty($paymentType)) {
1473 $paymentType = 'CB';
1474 }
1475 // May return nothing when paymentType means nothing
1476 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1477 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1478
1479 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1480 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1481 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1482 }
1483 }
1484
1485 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1486 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1487 $resultvalidate = $object->validate($user);
1488 if ($resultvalidate < 0) {
1489 $postactionmessages[] = 'Cannot validate invoice';
1490 $ispostactionok = -1;
1491 $error++; // Not yet supported
1492 } else {
1493 $db->begin();
1494
1495 // Creation of payment line
1496 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1497 $paiement = new Paiement($db);
1498 $paiement->datepaye = $now;
1499 if ($currencyCodeType == $conf->currency) {
1500 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1501 } else {
1502 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1503
1504 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1505 $ispostactionok = -1;
1506 $error++; // Not yet supported
1507 }
1508 $paiement->paiementid = $paymentTypeId;
1509 $paiement->num_payment = '';
1510 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
1511
1512 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1513 if ($LONGTRANSACTIONID) {
1514 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1515 } else {
1516 $paiement->ext_payment_id = $TRANSACTIONID;
1517 }
1518 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1519
1520 if (!$error) {
1521 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1522 if ($paiement_id < 0) {
1523 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1524 $ispostactionok = -1;
1525 $error++;
1526 } else {
1527 $postactionmessages[] = 'Payment created';
1528 $ispostactionok = 1;
1529 }
1530 }
1531
1532 if (!$error && isModEnabled("bank")) {
1533 $bankaccountid = 0;
1534 if ($paymentmethod == 'paybox') {
1535 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1536 } elseif ($paymentmethod == 'paypal') {
1537 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1538 } elseif ($paymentmethod == 'stripe') {
1539 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1540 }
1541
1542 //Get bank account for a specific paymentmedthod
1543 $parameters = [
1544 'paymentmethod' => $paymentmethod,
1545 ];
1546 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1547 if ($reshook >= 0) {
1548 if (isset($hookmanager->resArray['bankaccountid'])) {
1549 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1550 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1551 }
1552 }
1553 if ($bankaccountid > 0) {
1554 $label = '(CustomerInvoicePayment)';
1555 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1556 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1557 }
1558 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1559 if ($result < 0) {
1560 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1561 $ispostactionok = -1;
1562 $error++;
1563 } else {
1564 $postactionmessages[] = 'Bank transaction of payment created';
1565 $ispostactionok = 1;
1566 }
1567 } else {
1568 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1569 $ispostactionok = -1;
1570 $error++;
1571 }
1572 }
1573
1574 $attendeetovalidate = new ConferenceOrBoothAttendee($db);
1575
1576 if (!$error) {
1577 // Validating the attendee
1578 $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
1579 if ($resultattendee < 0) {
1580 $error++;
1581 setEventMessages(null, $attendeetovalidate->errors, "errors");
1582 } else {
1583 $attendeetovalidate->validate($user);
1584
1585 $attendeetovalidate->amount = $FinalPaymentAmt;
1586 $attendeetovalidate->date_subscription = dol_now();
1587 $attendeetovalidate->update($user);
1588 }
1589 }
1590
1591 if (!$error) {
1592 $db->commit();
1593 } else {
1594 setEventMessages(null, $postactionmessages, 'warnings');
1595
1596 $db->rollback();
1597 }
1598
1599 if (! $error) {
1600 // Sending mail
1601 $thirdparty = new Societe($db);
1602 $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
1603 if ($resultthirdparty < 0) {
1604 setEventMessages($thirdparty->error, $thirdparty->errors, "errors");
1605 } else {
1606 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1607 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1608 $formmail = new FormMail($db);
1609 // Set output language
1610 $outputlangs = new Translate('', $conf);
1611 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? (string) $mysoc->default_lang : (string) $thirdparty->default_lang);
1612 // Load traductions files required by page
1613 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1614 // Get email content from template
1615 $arraydefaultmessage = null;
1616
1617 $idoftemplatetouse = getDolGlobalInt('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT'); // Email to send for Event organization registration
1618
1619 if (!empty($idoftemplatetouse)) {
1620 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1621 }
1622
1623 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1624 $subject = $arraydefaultmessage->topic;
1625 $msg = $arraydefaultmessage->content;
1626 } else {
1627 $subject = '['.$appli.'] '.$object->ref.' - '.$outputlangs->trans("NewRegistration");
1628 $msg = $outputlangs->trans("OrganizationEventPaymentOfRegistrationWasReceived");
1629 }
1630
1631 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1632 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1633
1634 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1635 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1636
1637 $sendto = $attendeetovalidate->email;
1638 $cc = '';
1639 if ($thirdparty->email) {
1640 $cc = $thirdparty->email ?? '';
1641 }
1642 if ($attendeetovalidate->email_company && $attendeetovalidate->email_company != $thirdparty->email) {
1643 $cc = ($cc ? ', ' : '').$attendeetovalidate->email_company;
1644 }
1645
1646 $from = getDolGlobalString('MAILING_EMAIL_FROM', getDolGlobalString("MAIN_MAIL_EMAIL_FROM"));
1647
1648 $urlback = $_SERVER["REQUEST_URI"];
1649
1650 $ishtml = dol_textishtml($texttosend); // May contain urls
1651
1652 // Attach a file ?
1653 $file = '';
1654 $listofpaths = array();
1655 $listofnames = array();
1656 $listofmimes = array();
1657 if (is_object($object)) {
1658 $invoicediroutput = $conf->facture->dir_output;
1659 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->ref, preg_quote($object->ref, '/').'[^\-]+');
1660 $file = $fileparams['fullname'];
1661
1662 $listofpaths = array($file);
1663 $listofnames = array(basename($file));
1664 $listofmimes = array(dol_mimetype($file));
1665 }
1666
1667 $trackid = 'inv'.$object->id;
1668
1669 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, $cc, '', 0, ($ishtml ? 1 : 0), '', '', $trackid, '', 'standard');
1670
1671 $result = $mailfile->sendfile();
1672 if ($result) {
1673 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1674 } else {
1675 dol_syslog("Failed to send EMail to ".$sendto.' - '.$mailfile->error, LOG_ERR, 0, '_payment');
1676 }
1677 }
1678 }
1679 }
1680 } else {
1681 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
1682 $ispostactionok = -1;
1683 }
1684 } else {
1685 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1686 $ispostactionok = -1;
1687 }
1688 } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
1689 // Record payment for booth or conference
1690 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1691 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1692 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1693 $object = new Facture($db);
1694 $result = $object->fetch((int) $ref); // @phan-suppress-current-line PhanPluginSuspiciousParamPosition
1695 if ($result) {
1696 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1697
1698 $paymentTypeId = 0;
1699 if ($paymentmethod == 'paybox') {
1700 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1701 }
1702 if ($paymentmethod == 'paypal') {
1703 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1704 }
1705 if ($paymentmethod == 'stripe') {
1706 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1707 }
1708 if (empty($paymentTypeId)) {
1709 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1710
1711 if (empty($paymentType)) {
1712 $paymentType = 'CB';
1713 }
1714 // May return nothing when paymentType means nothing
1715 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1716 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1717
1718 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1719 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1720 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1721 }
1722 }
1723
1724 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1725 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1726 $resultvalidate = $object->validate($user);
1727 if ($resultvalidate < 0) {
1728 $postactionmessages[] = 'Cannot validate invoice';
1729 $ispostactionok = -1;
1730 $error++; // Not yet supported
1731 } else {
1732 $db->begin();
1733
1734 // Creation of payment line
1735 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1736 $paiement = new Paiement($db);
1737 $paiement->datepaye = $now;
1738 if ($currencyCodeType == $conf->currency) {
1739 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1740 } else {
1741 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1742
1743 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1744 $ispostactionok = -1;
1745 $error++; // Not yet supported
1746 }
1747 $paiement->paiementid = $paymentTypeId;
1748 $paiement->num_payment = '';
1749 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1750
1751 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1752 if ($LONGTRANSACTIONID) {
1753 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1754 } else {
1755 $paiement->ext_payment_id = $TRANSACTIONID;
1756 }
1757 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1758
1759 if (!$error) {
1760 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1761 if ($paiement_id < 0) {
1762 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1763 $ispostactionok = -1;
1764 $error++;
1765 } else {
1766 $postactionmessages[] = 'Payment created';
1767 $ispostactionok = 1;
1768 }
1769 }
1770
1771 if (!$error && isModEnabled("bank")) {
1772 $bankaccountid = 0;
1773 if ($paymentmethod == 'paybox') {
1774 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1775 } elseif ($paymentmethod == 'paypal') {
1776 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1777 } elseif ($paymentmethod == 'stripe') {
1778 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1779 }
1780
1781 //Get bank account for a specific paymentmedthod
1782 $parameters = [
1783 'paymentmethod' => $paymentmethod,
1784 ];
1785 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1786 if ($reshook >= 0) {
1787 if (isset($hookmanager->resArray['bankaccountid'])) {
1788 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1789 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1790 }
1791 }
1792 if ($bankaccountid > 0) {
1793 $label = '(CustomerInvoicePayment)';
1794 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1795 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1796 }
1797 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1798 if ($result < 0) {
1799 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1800 $ispostactionok = -1;
1801 $error++;
1802 } else {
1803 $postactionmessages[] = 'Bank transaction of payment created';
1804 $ispostactionok = 1;
1805 }
1806 } else {
1807 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1808 $ispostactionok = -1;
1809 $error++;
1810 }
1811 }
1812
1813 if (!$error) {
1814 // Putting the booth to "suggested" state
1815 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1816 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1817 $booth = new ConferenceOrBooth($db);
1818 $resultbooth = $booth->fetch((int) $tmptag['BOO']);
1819 if ($resultbooth < 0) {
1820 $error++;
1821 setEventMessages(null, $booth->errors, "errors");
1822 } else {
1823 $booth->status = ConferenceOrBooth::STATUS_SUGGESTED;
1824 $resultboothupdate = $booth->update($user);
1825 if ($resultboothupdate < 0) {
1826 // Finding the third party by getting the invoice
1827 $invoice = new Facture($db);
1828 $resultinvoice = $invoice->fetch((int) $ref); // @phan-suppress-current-line PhanPluginSuspiciousParamPosition
1829 if ($resultinvoice < 0) {
1830 $postactionmessages[] = 'Could not find the associated invoice.';
1831 $ispostactionok = -1;
1832 $error++;
1833 } else {
1834 $thirdparty = new Societe($db);
1835 $resultthirdparty = $thirdparty->fetch($invoice->socid);
1836 if ($resultthirdparty < 0) {
1837 $error++;
1838 setEventMessages(null, $thirdparty->errors, "errors");
1839 } else {
1840 // TODO Move the send of email out of the db transaction
1841
1842 // Sending mail
1843 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1844 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1845 $formmail = new FormMail($db);
1846 // Set output language
1847 $outputlangs = new Translate('', $conf);
1848 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1849 // Load traductions files required by page
1850 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1851 // Get email content from template
1852 $arraydefaultmessage = null;
1853
1854 $idoftemplatetouse = getDolGlobalInt('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH'); // Email sent after registration for a Booth
1855
1856 if (!empty($idoftemplatetouse)) {
1857 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1858 }
1859
1860 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1861 $subject = $arraydefaultmessage->topic;
1862 $msg = $arraydefaultmessage->content;
1863 } else {
1864 $subject = '['.$appli.'] '.$booth->ref.' - '.$outputlangs->trans("NewRegistration").']';
1865 $msg = $outputlangs->trans("OrganizationEventPaymentOfBoothWasReceived");
1866 }
1867
1868 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1869 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1870
1871 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1872 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1873
1874 $sendto = $thirdparty->email;
1875 $from = getDolGlobalString('MAILING_EMAIL_FROM');
1876 $urlback = $_SERVER["REQUEST_URI"];
1877
1878 $ishtml = dol_textishtml($texttosend); // May contain urls
1879 $trackid = 'inv'.$invoice->id;
1880
1881 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
1882
1883 $result = $mailfile->sendfile();
1884 if ($result) {
1885 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1886 } else {
1887 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1888 }
1889 }
1890 }
1891 }
1892 }
1893 }
1894
1895 if (!$error) {
1896 $db->commit();
1897 } else {
1898 $db->rollback();
1899 }
1900 }
1901 } else {
1902 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
1903 $ispostactionok = -1;
1904 }
1905 } else {
1906 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1907 $ispostactionok = -1;
1908 }
1909 } elseif (array_key_exists('CON', $tmptag) && $tmptag['CON'] > 0) {
1910 include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
1911 $object = new Contrat($db);
1912 $result = $object->fetch((int) $tmptag['CON']);
1913 if ($result) {
1914 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1915
1916 $paymentTypeId = 0;
1917 if ($paymentmethod == 'paybox') {
1918 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1919 }
1920 if ($paymentmethod == 'paypal') {
1921 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1922 }
1923 if ($paymentmethod == 'stripe') {
1924 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1925 }
1926 if (empty($paymentTypeId)) {
1927 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1928
1929 if (empty($paymentType)) {
1930 $paymentType = 'CB';
1931 }
1932 // May return nothing when paymentType means nothing
1933 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1934 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1935
1936 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1937 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1938 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1939 }
1940 }
1941
1942 $currencyCodeType = $_SESSION['currencyCodeType'];
1943 $contract_lines = (array_key_exists('COL', $tmptag) && $tmptag['COL'] > 0) ? $tmptag['COL'] : null;
1944
1945 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1946 if (isModEnabled('invoice')) {
1947 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1948 $db->begin();
1949
1950 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1951 $invoice = new Facture($db);
1952 $result = $invoice->createFromContract($object, $user, array((int) $contract_lines));
1953 if ($result > 0) {
1954 // $object->classifyBilled($user);
1955 $invoice->validate($user);
1956 // Creation of payment line
1957 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1958 $paiement = new Paiement($db);
1959 $paiement->datepaye = $now;
1960 if ($currencyCodeType == $conf->currency) {
1961 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1962 } else {
1963 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1964
1965 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1966 $ispostactionok = -1;
1967 $error++;
1968 }
1969 $paiement->paiementid = $paymentTypeId;
1970 $paiement->num_payment = '';
1971 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1972
1973 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1974 if ($LONGTRANSACTIONID) {
1975 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1976 } else {
1977 $paiement->ext_payment_id = $TRANSACTIONID;
1978 }
1979 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1980
1981 if (!$error) {
1982 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1983 if ($paiement_id < 0) {
1984 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1985 $ispostactionok = -1;
1986 $error++;
1987 } else {
1988 $postactionmessages[] = 'Payment created';
1989 $ispostactionok = 1;
1990 }
1991 }
1992
1993 if (!$error && isModEnabled("bank")) {
1994 $bankaccountid = 0;
1995 if ($paymentmethod == 'paybox') {
1996 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1997 } elseif ($paymentmethod == 'paypal') {
1998 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1999 } elseif ($paymentmethod == 'stripe') {
2000 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
2001 }
2002
2003 //Get bank account for a specific paymentmedthod
2004 $parameters = [
2005 'paymentmethod' => $paymentmethod,
2006 ];
2007 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
2008 if ($reshook >= 0) {
2009 if (isset($hookmanager->resArray['bankaccountid'])) {
2010 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
2011 $bankaccountid = $hookmanager->resArray['bankaccountid'];
2012 }
2013 }
2014 if ($bankaccountid > 0) {
2015 $label = '(CustomerInvoicePayment)';
2016 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
2017 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
2018 }
2019 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
2020 if ($result < 0) {
2021 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
2022 $ispostactionok = -1;
2023 $error++;
2024 } else {
2025 $postactionmessages[] = 'Bank transaction of payment created';
2026 $ispostactionok = 1;
2027 }
2028 } else {
2029 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
2030 $ispostactionok = -1;
2031 $error++;
2032 }
2033 }
2034 } else {
2035 $msg = 'Failed to create invoice form contract ' . $tmptag['CON'];
2036 if (!empty($tmptag['COL'])) {
2037 $msg .= ' and col '. $tmptag['COL'] .'.';
2038 }
2039 $postactionmessages[] = $msg;
2040 $ispostactionok = -1;
2041 $error++;
2042 }
2043
2044 if (!$error) {
2045 $db->commit();
2046 } else {
2047 $db->rollback();
2048 }
2049 } else {
2050 $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type id" (' . $paymentTypeId . ') to record the payment of contract ' . $tmptag['CON'] .'. Maybe payment was already recorded.';
2051 $ispostactionok = -1;
2052 }
2053 } else {
2054 $postactionmessages[] = 'Invoice module is not enable';
2055 $ispostactionok = -1;
2056 }
2057 } else {
2058 $msg = 'Contract paid ' . $tmptag['CON'] . ' was not found';
2059 if (!empty($tmptag['COL'])) {
2060 $msg .= ' for col '.$tmptag['COL'] .'.';
2061 }
2062 $postactionmessages[] = $msg;
2063 $ispostactionok = -1;
2064 }
2065 } else {
2066 // Nothing done
2067 }
2068}
2069
2070dol_syslog("ispaymentok=".$ispaymentok." ispostactionok=".$ispostactionok." doactionsthenredirect=".$doactionsthenredirect, LOG_DEBUG, 0, '_payment');
2071
2072if ($ispaymentok) {
2073 // Get on url call
2074 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
2075 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
2076 // Set by newpayment.php
2077 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
2078 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
2079 $paymentType = empty($_SESSION['PaymentType']) ? '' : $_SESSION['PaymentType']; // Seems used by paypal only
2080
2081 if (is_object($object) && method_exists($object, 'call_trigger')) {
2082 '@phan-var-force CommonObject $object';
2083 // Call trigger
2084 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
2085 if ($result < 0) {
2086 $error++;
2087 }
2088 // End call triggers
2089 } elseif (get_class($object) == 'stdClass') {
2090 //In some cases $object is not instantiated (for payment on custom object) We need to deal with payment
2091 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2092 $paiement = new Paiement($db);
2093 $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
2094 if ($result < 0) {
2095 $error++;
2096 }
2097 }
2098}
2099
2100
2101// Show result message
2102if (empty($doactionsthenredirect)) {
2103 if ($ispaymentok) {
2104 print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
2105 if ($TRANSACTIONID) {
2106 print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n";
2107 }
2108
2109 print '<center>';
2110 print img_picto('', 'tick', 'class="green fa-2x"');
2111 print '</center>';
2112
2113 // Show a custom message
2114 $key = 'ONLINE_PAYMENT_MESSAGE_OK';
2115 if (getDolGlobalString($key)) {
2116 print '<br>';
2117 print getDolGlobalString($key);
2118 }
2119 } else {
2120 print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
2121 if ($ErrorLongMsg) {
2122 print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
2123 }
2124 if ($ErrorShortMsg) {
2125 print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
2126 }
2127 if ($ErrorCode) {
2128 print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
2129 }
2130 if ($ErrorSeverityCode) {
2131 print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
2132 }
2133
2134 if ($mysoc->email) {
2135 print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
2136 }
2137 }
2138}
2139
2140
2141// Send email
2142if ($ispaymentok) {
2143 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
2144
2145 $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
2146
2147 dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
2148
2149 // Send an email to the admins
2150 if ($sendemail) {
2151 // Get default language to use for the company for supervision emails
2152 $myCompanyDefaultLang = (string) $mysoc->default_lang;
2153 if (empty($myCompanyDefaultLang) || $myCompanyDefaultLang === 'auto') {
2154 // We must guess the language from the company country. We must not use the language of the visitor. This is a technical email for supervision
2155 // so it must always be into the same language.
2156 $myCompanyDefaultLang = (string) getLanguageCodeFromCountryCode($mysoc->country_code);
2157 }
2158
2159 $companylangs = new Translate('', $conf);
2160 $companylangs->setDefaultLang($myCompanyDefaultLang);
2161 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
2162
2163 $sendto = $sendemail;
2164 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
2165 // Define $urlwithroot
2166 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2167 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2168 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2169
2170 // Define link to login card
2171
2172 $urlback = $_SERVER["REQUEST_URI"];
2173 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
2174 $content = "";
2175 if (array_key_exists('MEM', $tmptag)) {
2176 $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
2177 $content .= '<strong>'.$companylangs->transnoentitiesnoconv("PaymentSubscription")."</strong><br><br>\n";
2178 $content .= $companylangs->transnoentitiesnoconv("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
2179 $content .= $companylangs->transnoentitiesnoconv("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
2180 } elseif (array_key_exists('INV', $tmptag)) {
2181 $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
2182 $content .= '<strong>'.$companylangs->transnoentitiesnoconv("Payment")."</strong><br><br>\n";
2183 $content .= $companylangs->transnoentitiesnoconv("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
2184 //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
2185 $content .= $companylangs->transnoentitiesnoconv("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
2186 } else {
2187 $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
2188 }
2189 $content .= $companylangs->transnoentitiesnoconv("PostActionAfterPayment").' : ';
2190 if ($ispostactionok > 0) {
2191 //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
2192 $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
2193 } elseif ($ispostactionok == 0) {
2194 $content .= $companylangs->transnoentitiesnoconv("None");
2195 } else {
2196 $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
2197 $content .= '<span class="star">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
2198 }
2199 $content .= '<br>'."\n";
2200 foreach ($postactionmessages as $postactionmessage) {
2201 $content .= ' * '.$postactionmessage.'<br>'."\n";
2202 }
2203 if ($ispostactionok < 0) {
2204 $content .= $langs->transnoentitiesnoconv("ARollbackWasPerformedOnPostActions");
2205 }
2206 $content .= '<br>'."\n";
2207
2208 $content .= "<br>\n";
2209 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
2210 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
2211 $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
2212 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
2213 $content .= "<br>\n";
2214 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
2215
2216 if (!empty($ErrorCode)) {
2217 $content .= "ErrorCode = ".$ErrorCode."<br>\n";
2218 }
2219 if (!empty($ErrorShortMsg)) {
2220 $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
2221 }
2222 if (!empty($ErrorLongMsg)) {
2223 $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
2224 }
2225 if (!empty($ErrorSeverityCode)) {
2226 $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
2227 }
2228
2229 dol_syslog("Content of email: ".$content, LOG_DEBUG, 0, '_payment');
2230
2231 $ishtml = dol_textishtml($content); // May contain urls
2232 $trackid = '';
2233
2234 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2235 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
2236
2237 $result = $mailfile->sendfile();
2238 if ($result) {
2239 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2240 //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
2241 } else {
2242 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2243 //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
2244 }
2245 }
2246} else {
2247 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
2248
2249 // Get on url call
2250 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
2251 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
2252 // Set by newpayment.php
2253 $paymentType = $_SESSION['PaymentType'];
2254 $currencyCodeType = $_SESSION['currencyCodeType'];
2255 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
2256
2257 if (is_object($object) && method_exists($object, 'call_trigger')) {
2258 // Call trigger
2259 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
2260 if ($result < 0) {
2261 $error++;
2262 }
2263 // End call triggers
2264 }
2265
2266 // Send warning of error to administrator
2267 if ($sendemail) {
2268 $companylangs = new Translate('', $conf);
2269 $companylangs->setDefaultLang($mysoc->default_lang);
2270 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
2271
2272 $sendto = $sendemail;
2273 $from = getDolGlobalString('MAILING_EMAIL_FROM', getDolGlobalString("MAIN_MAIL_EMAIL_FROM"));
2274 // Define $urlwithroot
2275 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2276 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2277 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2278
2279 $urlback = $_SERVER["REQUEST_URI"];
2280 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
2281 $content = "";
2282 $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
2283
2284 $content .= "<br><br>\n";
2285 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
2286 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
2287 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
2288 $content .= "<br>\n";
2289 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
2290
2291
2292 $ishtml = dol_textishtml($content); // May contain urls
2293 $trackid = '';
2294
2295 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2296 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
2297
2298 $result = $mailfile->sendfile();
2299 if ($result) {
2300 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2301 } else {
2302 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2303 }
2304 }
2305}
2306
2307
2308// Clean session variables to avoid duplicate actions if post is resent
2309unset($_SESSION["FinalPaymentAmt"]);
2310unset($_SESSION["TRANSACTIONID"]);
2311
2312
2313// Close page content id="dolpaymentdiv"
2314if (empty($doactionsthenredirect)) {
2315 print "\n</div>\n";
2316
2317 print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag((string) $paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
2318}
2319
2320
2321// Show footer
2322if (empty($doactionsthenredirect)) {
2323 htmlPrintOnlineFooter($mysoc, $langs, 0, $suffix);
2324
2325 llxFooter('', 'public');
2326}
2327
2328
2329$db->close();
2330
2331
2332// If option to do a redirect somewhere else.
2333if (!empty($doactionsthenredirect)) {
2334 if ($ispaymentok) {
2335 // Redirect to a success page
2336 $randomseckey = getRandomPassword(true, null, 20);
2337 $_SESSION['paymentoksessioncode'] = $randomseckey; // key propagated between paymentok.php to another page like a paymentok of the website.
2338
2339 // Paymentok page must be created for the specific website
2340 if (!defined('USEDOLIBARRSERVER') && !empty($ws_virtuelhost)) {
2341 $ext_urlok = $ws_virtuelhost . '/paymentok.php?paymentoksessioncode='.urlencode($randomseckey).'&fulltag='.$FULLTAG;
2342 } else {
2343 $ext_urlok = DOL_URL_ROOT.'/public/website/index.php?paymentoksessioncode='.urlencode($randomseckey).'&website='.urlencode($ws).'&pageref=paymentok&fulltag='.$FULLTAG;
2344 }
2345
2346 dol_syslog("Now do a redirect using a Location: ".$ext_urlok, LOG_DEBUG, 0, '_payment');
2347 header("Location: ".$ext_urlok);
2348 exit;
2349 } else {
2350 // Redirect to an error page
2351 $randomseckey = getRandomPassword(true, null, 20);
2352 $_SESSION['paymentkosessioncode'] = $randomseckey; // key propagated between paymentok.php to another page like a paymentko of the website.
2353
2354 // Paymentko page must be created for the specific website
2355 if (!defined('USEDOLIBARRSERVER') && !empty($ws_virtuelhost)) {
2356 $ext_urlko = $ws_virtuelhost . '/paymentko.php?paymentkosessioncode='.urlencode($randomseckey).'&fulltag='.$FULLTAG;
2357 } else {
2358 $ext_urlko = DOL_URL_ROOT.'/public/website/index.php?paymentkosessioncode='.urlencode($randomseckey).'&website='.urlencode($ws).'&pageref=paymentko&fulltag='.$FULLTAG;
2359 }
2360
2361 dol_syslog("Now do a redirect using a Location:".$ext_urlko, LOG_DEBUG, 0, '_payment');
2362 header("Location: ".$ext_urlko);
2363 exit;
2364 }
2365}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage members of a foundation.
Class to manage members type.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage customers orders.
Class for ConferenceOrBoothAttendee.
Class for ConferenceOrBooth.
Class to manage donations.
Definition don.class.php:41
Class to manage invoices.
const STATUS_DRAFT
Draft status.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
Class to manage hooks.
Class to manage payments of customer invoices.
Class to manage payments of donations.
Class to manage third parties objects (customers, suppliers, prospects...)
Stripe class @TODO No reason to extend CommonObject.
Class to manage translations.
Class to manage Dolibarr users.
Class Website.
htmlPrintOnlineFooter($fromcompany, $langs, $addformmessage=0, $suffix='', $object=null)
Show footer of company in HTML public pages.
global $mysoc
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:603
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0)
Return file(s) into a directory (by default most recent)
dol_now($mode='gmt')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
getLanguageCodeFromCountryCode($countrycode)
Return default language from country code.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag)
Validate payment.
getDetails($token)
Prepares the parameters for the GetExpressCheckoutDetails API Call.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
httponly_accessforbidden($message='1', $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.