Merge pull request #15185 from Dolibarr/scrutinizer-patch-1

Scrutinizer Auto-Fixes
This commit is contained in:
Laurent Destailleur 2020-10-27 19:47:20 +01:00 committed by GitHub
commit d7a9e0f61a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 6112 additions and 6112 deletions

View File

@ -76,26 +76,26 @@ $defaultdelay = 1;
$defaultdelayunit = 'y'; $defaultdelayunit = 'y';
if ($rowid) { if ($rowid) {
// Load member // Load member
$result = $object->fetch($rowid); $result = $object->fetch($rowid);
// Define variables to know what current user can do on users // Define variables to know what current user can do on users
$canadduser = ($user->admin || $user->rights->user->user->creer); $canadduser = ($user->admin || $user->rights->user->user->creer);
// Define variables to know what current user can do on properties of user linked to edited member // Define variables to know what current user can do on properties of user linked to edited member
if ($object->user_id) { if ($object->user_id) {
// $user is the user editing, $object->user_id is the user's id linked to the edited member // $user is the user editing, $object->user_id is the user's id linked to the edited member
$caneditfielduser = ((($user->id == $object->user_id) && $user->rights->user->self->creer) $caneditfielduser = ((($user->id == $object->user_id) && $user->rights->user->self->creer)
|| (($user->id != $object->user_id) && $user->rights->user->user->creer)); || (($user->id != $object->user_id) && $user->rights->user->user->creer));
$caneditpassworduser = ((($user->id == $object->user_id) && $user->rights->user->self->password) $caneditpassworduser = ((($user->id == $object->user_id) && $user->rights->user->self->password)
|| (($user->id != $object->user_id) && $user->rights->user->user->password)); || (($user->id != $object->user_id) && $user->rights->user->user->password));
} }
} }
// Define variables to know what current user can do on members // Define variables to know what current user can do on members
$canaddmember = $user->rights->adherent->creer; $canaddmember = $user->rights->adherent->creer;
// Define variables to know what current user can do on properties of a member // Define variables to know what current user can do on properties of a member
if ($rowid) { if ($rowid) {
$caneditfieldmember = $user->rights->adherent->creer; $caneditfieldmember = $user->rights->adherent->creer;
} }
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -130,242 +130,242 @@ if ($action == 'confirm_create_thirdparty' && $confirm == 'yes' && $user->rights
} }
if ($action == 'setuserid' && ($user->rights->user->self->creer || $user->rights->user->user->creer)) { if ($action == 'setuserid' && ($user->rights->user->self->creer || $user->rights->user->user->creer)) {
$error = 0; $error = 0;
if (empty($user->rights->user->user->creer)) { // If can edit only itself user, we can link to itself only if (empty($user->rights->user->user->creer)) { // If can edit only itself user, we can link to itself only
if ($_POST["userid"] != $user->id && $_POST["userid"] != $object->user_id) { if ($_POST["userid"] != $user->id && $_POST["userid"] != $object->user_id) {
$error++; $error++;
setEventMessages($langs->trans("ErrorUserPermissionAllowsToLinksToItselfOnly"), null, 'errors'); setEventMessages($langs->trans("ErrorUserPermissionAllowsToLinksToItselfOnly"), null, 'errors');
} }
} }
if (!$error) { if (!$error) {
if ($_POST["userid"] != $object->user_id) { // If link differs from currently in database if ($_POST["userid"] != $object->user_id) { // If link differs from currently in database
$result = $object->setUserId($_POST["userid"]); $result = $object->setUserId($_POST["userid"]);
if ($result < 0) dol_print_error('', $object->error); if ($result < 0) dol_print_error('', $object->error);
$_POST['action'] = ''; $_POST['action'] = '';
$action = ''; $action = '';
} }
} }
} }
if ($action == 'setsocid') { if ($action == 'setsocid') {
$error = 0; $error = 0;
if (!$error) { if (!$error) {
if (GETPOST('socid', 'int') != $object->fk_soc) { // If link differs from currently in database if (GETPOST('socid', 'int') != $object->fk_soc) { // If link differs from currently in database
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
$sql .= " WHERE fk_soc = '".GETPOST('socid', 'int')."'"; $sql .= " WHERE fk_soc = '".GETPOST('socid', 'int')."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) { if ($resql) {
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj && $obj->rowid > 0) { if ($obj && $obj->rowid > 0) {
$othermember = new Adherent($db); $othermember = new Adherent($db);
$othermember->fetch($obj->rowid); $othermember->fetch($obj->rowid);
$thirdparty = new Societe($db); $thirdparty = new Societe($db);
$thirdparty->fetch(GETPOST('socid', 'int')); $thirdparty->fetch(GETPOST('socid', 'int'));
$error++; $error++;
setEventMessages($langs->trans("ErrorMemberIsAlreadyLinkedToThisThirdParty", $othermember->getFullName($langs), $othermember->login, $thirdparty->name), null, 'errors'); setEventMessages($langs->trans("ErrorMemberIsAlreadyLinkedToThisThirdParty", $othermember->getFullName($langs), $othermember->login, $thirdparty->name), null, 'errors');
} }
} }
if (!$error) { if (!$error) {
$result = $object->setThirdPartyId(GETPOST('socid', 'int')); $result = $object->setThirdPartyId(GETPOST('socid', 'int'));
if ($result < 0) dol_print_error('', $object->error); if ($result < 0) dol_print_error('', $object->error);
$_POST['action'] = ''; $_POST['action'] = '';
$action = ''; $action = '';
} }
} }
} }
} }
if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !$_POST["cancel"]) { if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !$_POST["cancel"]) {
$error = 0; $error = 0;
$langs->load("banks"); $langs->load("banks");
$result = $object->fetch($rowid); $result = $object->fetch($rowid);
$result = $adht->fetch($object->typeid); $result = $adht->fetch($object->typeid);
// Subscription informations // Subscription informations
$datesubscription = 0; $datesubscription = 0;
$datesubend = 0; $datesubend = 0;
$paymentdate = 0; $paymentdate = 0;
if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"]) { if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"]) {
$datesubscription = dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); $datesubscription = dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
} }
if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"]) { if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"]) {
$datesubend = dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]); $datesubend = dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]);
} }
if ($_POST["paymentyear"] && $_POST["paymentmonth"] && $_POST["paymentday"]) { if ($_POST["paymentyear"] && $_POST["paymentmonth"] && $_POST["paymentday"]) {
$paymentdate = dol_mktime(0, 0, 0, $_POST["paymentmonth"], $_POST["paymentday"], $_POST["paymentyear"]); $paymentdate = dol_mktime(0, 0, 0, $_POST["paymentmonth"], $_POST["paymentday"], $_POST["paymentyear"]);
} }
$amount = price2num(GETPOST("subscription", 'alpha')); // Amount of subscription $amount = price2num(GETPOST("subscription", 'alpha')); // Amount of subscription
$label = $_POST["label"]; $label = $_POST["label"];
// Payment informations // Payment informations
$accountid = $_POST["accountid"]; $accountid = $_POST["accountid"];
$operation = $_POST["operation"]; // Payment mode $operation = $_POST["operation"]; // Payment mode
$num_chq = GETPOST("num_chq", "alphanohtml"); $num_chq = GETPOST("num_chq", "alphanohtml");
$emetteur_nom = $_POST["chqemetteur"]; $emetteur_nom = $_POST["chqemetteur"];
$emetteur_banque = $_POST["chqbank"]; $emetteur_banque = $_POST["chqbank"];
$option = $_POST["paymentsave"]; $option = $_POST["paymentsave"];
if (empty($option)) $option = 'none'; if (empty($option)) $option = 'none';
$sendalsoemail = GETPOST("sendmail", 'alpha'); $sendalsoemail = GETPOST("sendmail", 'alpha');
// Check parameters // Check parameters
if (!$datesubscription) { if (!$datesubscription) {
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
$errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateSubscription")); $errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateSubscription"));
setEventMessages($errmsg, null, 'errors'); setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription'; $action = 'addsubscription';
} }
if (GETPOST('end') && !$datesubend) { if (GETPOST('end') && !$datesubend) {
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
$errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateEndSubscription")); $errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateEndSubscription"));
setEventMessages($errmsg, null, 'errors'); setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription'; $action = 'addsubscription';
} }
if (!$datesubend) { if (!$datesubend) {
$datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd'); $datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd');
} }
if (($option == 'bankviainvoice' || $option == 'bankdirect') && !$paymentdate) { if (($option == 'bankviainvoice' || $option == 'bankdirect') && !$paymentdate) {
$error++; $error++;
$errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment")); $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment"));
setEventMessages($errmsg, null, 'errors'); setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription'; $action = 'addsubscription';
} }
// Check if a payment is mandatory or not // Check if a payment is mandatory or not
if (!$error && $adht->subscription) { // Member type need subscriptions if (!$error && $adht->subscription) { // Member type need subscriptions
if (!is_numeric($amount)) { if (!is_numeric($amount)) {
// If field is '' or not a numeric value // If field is '' or not a numeric value
$errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount"));
setEventMessages($errmsg, null, 'errors'); setEventMessages($errmsg, null, 'errors');
$error++; $error++;
$action = 'addsubscription'; $action = 'addsubscription';
} else { } else {
if (!empty($conf->banque->enabled) && $_POST["paymentsave"] != 'none') { if (!empty($conf->banque->enabled) && $_POST["paymentsave"] != 'none') {
if ($_POST["subscription"]) { if ($_POST["subscription"]) {
if (!$_POST["label"]) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); if (!$_POST["label"]) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label"));
if ($_POST["paymentsave"] != 'invoiceonly' && !$_POST["operation"]) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); if ($_POST["paymentsave"] != 'invoiceonly' && !$_POST["operation"]) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode"));
if ($_POST["paymentsave"] != 'invoiceonly' && !($_POST["accountid"] > 0)) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("FinancialAccount")); if ($_POST["paymentsave"] != 'invoiceonly' && !($_POST["accountid"] > 0)) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("FinancialAccount"));
} else { } else {
if ($_POST["accountid"]) $errmsg = $langs->trans("ErrorDoNotProvideAccountsIfNullAmount"); if ($_POST["accountid"]) $errmsg = $langs->trans("ErrorDoNotProvideAccountsIfNullAmount");
} }
if ($errmsg) { if ($errmsg) {
$error++; $error++;
setEventMessages($errmsg, null, 'errors'); setEventMessages($errmsg, null, 'errors');
$error++; $error++;
$action = 'addsubscription'; $action = 'addsubscription';
} }
} }
} }
} }
// Record the subscription then complementary actions // Record the subscription then complementary actions
if (!$error && $action == 'subscription') { if (!$error && $action == 'subscription') {
$db->begin(); $db->begin();
// Create subscription // Create subscription
$crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend); $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend);
if ($crowid <= 0) { if ($crowid <= 0) {
$error++; $error++;
$errmsg = $object->error; $errmsg = $object->error;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
if (!$error) { if (!$error) {
$result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque); $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque);
if ($result < 0) { if ($result < 0) {
$error++; $error++;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} else { } else {
// If an invoice was created, it is into $object->invoice // If an invoice was created, it is into $object->invoice
} }
} }
if (!$error) { if (!$error) {
$db->commit(); $db->commit();
} else { } else {
$db->rollback(); $db->rollback();
$action = 'addsubscription'; $action = 'addsubscription';
} }
if (!$error) { if (!$error) {
setEventMessages("SubscriptionRecorded", null, 'mesgs'); setEventMessages("SubscriptionRecorded", null, 'mesgs');
} }
// Send email // Send email
if (!$error) { if (!$error) {
// Send confirmation Email // Send confirmation Email
if ($object->email && $sendalsoemail) { // $object is 'Adherent' if ($object->email && $sendalsoemail) { // $object is 'Adherent'
$subject = ''; $subject = '';
$msg = ''; $msg = '';
// Send subscription email // Send subscription email
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db); $formmail = new FormMail($db);
// Set output language // Set output language
$outputlangs = new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang); $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
// Load traductions files required by page // Load traductions files required by page
$outputlangs->loadLangs(array("main", "members")); $outputlangs->loadLangs(array("main", "members"));
// Get email content from template // Get email content from template
$arraydefaultmessage = null; $arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic; $subject = $arraydefaultmessage->topic;
$msg = $arraydefaultmessage->content; $msg = $arraydefaultmessage->content;
} }
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
complete_substitutions_array($substitutionarray, $outputlangs, $object); complete_substitutions_array($substitutionarray, $outputlangs, $object);
$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs); $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs); $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
// Attach a file ? // Attach a file ?
$file = ''; $file = '';
$listofpaths = array(); $listofpaths = array();
$listofnames = array(); $listofnames = array();
$listofmimes = array(); $listofmimes = array();
if (is_object($object->invoice)) { if (is_object($object->invoice)) {
$invoicediroutput = $conf->facture->dir_output; $invoicediroutput = $conf->facture->dir_output;
$fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+'); $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
$file = $fileparams['fullname']; $file = $fileparams['fullname'];
$listofpaths = array($file); $listofpaths = array($file);
$listofnames = array(basename($file)); $listofnames = array(basename($file));
$listofmimes = array(dol_mimetype($file)); $listofmimes = array(dol_mimetype($file));
} }
$moreinheader = 'X-Dolibarr-Info: send_an_email by adherents/subscription.php'."\r\n"; $moreinheader = 'X-Dolibarr-Info: send_an_email by adherents/subscription.php'."\r\n";
$result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, '', $moreinheader); $result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, '', $moreinheader);
if ($result < 0) { if ($result < 0) {
$errmsg = $object->error; $errmsg = $object->error;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} else { } else {
setEventMessages($langs->trans("EmailSentToMember", $object->email), null, 'mesgs'); setEventMessages($langs->trans("EmailSentToMember", $object->email), null, 'mesgs');
} }
} else { } else {
setEventMessages($langs->trans("NoEmailSentToMember"), null, 'mesgs'); setEventMessages($langs->trans("NoEmailSentToMember"), null, 'mesgs');
} }
} }
// Clean some POST vars // Clean some POST vars
if (!$error) { if (!$error) {
$_POST["subscription"] = ''; $_POST["subscription"] = '';
$_POST["accountid"] = ''; $_POST["accountid"] = '';
$_POST["operation"] = ''; $_POST["operation"] = '';
$_POST["label"] = ''; $_POST["label"] = '';
$_POST["num_chq"] = ''; $_POST["num_chq"] = '';
} }
} }
} }
@ -393,32 +393,32 @@ if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
if ($rowid > 0) { if ($rowid > 0) {
$res = $object->fetch($rowid); $res = $object->fetch($rowid);
if ($res < 0) { dol_print_error($db, $object->error); exit; } if ($res < 0) { dol_print_error($db, $object->error); exit; }
$adht->fetch($object->typeid); $adht->fetch($object->typeid);
$head = member_prepare_head($object); $head = member_prepare_head($object);
$rowspan = 10; $rowspan = 10;
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++; if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++;
if (!empty($conf->societe->enabled)) $rowspan++; if (!empty($conf->societe->enabled)) $rowspan++;
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="rowid" value="'.$object->id.'">'; print '<input type="hidden" name="rowid" value="'.$object->id.'">';
print dol_get_fiche_head($head, 'subscription', $langs->trans("Member"), -1, 'user'); print dol_get_fiche_head($head, 'subscription', $langs->trans("Member"), -1, 'user');
$linkback = '<a href="'.DOL_URL_ROOT.'/adherents/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/adherents/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
dol_banner_tab($object, 'rowid', $linkback); dol_banner_tab($object, 'rowid', $linkback);
print '<div class="fichecenter">'; print '<div class="fichecenter">';
print '<div class="fichehalfleft">'; print '<div class="fichehalfleft">';
print '<div class="underbanner clearboth"></div>'; print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent tableforfield">'; print '<table class="border centpercent tableforfield">';
// Login // Login
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
@ -443,20 +443,20 @@ if ($rowid > 0) {
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
print '<tr><td>'.$langs->trans("Password").'</td><td>'.preg_replace('/./i', '*', $object->pass); print '<tr><td>'.$langs->trans("Password").'</td><td>'.preg_replace('/./i', '*', $object->pass);
if ((!empty($object->pass) || !empty($object->pass_crypted)) && empty($object->user_id)) { if ((!empty($object->pass) || !empty($object->pass_crypted)) && empty($object->user_id)) {
$langs->load("errors"); $langs->load("errors");
$htmltext = $langs->trans("WarningPasswordSetWithNoAccount"); $htmltext = $langs->trans("WarningPasswordSetWithNoAccount");
print ' '.$form->textwithpicto('', $htmltext, 1, 'warning'); print ' '.$form->textwithpicto('', $htmltext, 1, 'warning');
} }
print '</td></tr>'; print '</td></tr>';
} }
print '</table>'; print '</table>';
print '</div>'; print '</div>';
print '<div class="fichehalfright"><div class="ficheaddleft">'; print '<div class="fichehalfright"><div class="ficheaddleft">';
print '<div class="underbanner clearboth"></div>'; print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield" width="100%">'; print '<table class="border tableforfield" width="100%">';
// Birthday // Birthday
print '<tr><td class="titlefield">'.$langs->trans("Birthday").'</td><td class="valeur">'.dol_print_date($object->birth, 'day').'</td></tr>'; print '<tr><td class="titlefield">'.$langs->trans("Birthday").'</td><td class="valeur">'.dol_print_date($object->birth, 'day').'</td></tr>';
@ -472,25 +472,25 @@ if ($rowid > 0) {
print '</td></tr>'; print '</td></tr>';
} }
// Other attributes // Other attributes
$cols = 2; $cols = 2;
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
// Date end subscription // Date end subscription
print '<tr><td>'.$langs->trans("SubscriptionEndDate").'</td><td class="valeur">'; print '<tr><td>'.$langs->trans("SubscriptionEndDate").'</td><td class="valeur">';
if ($object->datefin) { if ($object->datefin) {
print dol_print_date($object->datefin, 'day'); print dol_print_date($object->datefin, 'day');
if ($object->hasDelay()) { if ($object->hasDelay()) {
print " ".img_warning($langs->trans("Late")); print " ".img_warning($langs->trans("Late"));
} }
} else { } else {
if (!$adht->subscription) { if (!$adht->subscription) {
print $langs->trans("SubscriptionNotRecorded"); print $langs->trans("SubscriptionNotRecorded");
if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled
} else { } else {
print $langs->trans("SubscriptionNotReceived"); print $langs->trans("SubscriptionNotReceived");
if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled
} }
} }
print '</td></tr>'; print '</td></tr>';
@ -660,71 +660,71 @@ if ($rowid > 0) {
$accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1); $accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
} }
$accountstatic->ref = $objp->ref; $accountstatic->ref = $objp->ref;
print $accountstatic->getNomUrl(1); print $accountstatic->getNomUrl(1);
} else { } else {
print '&nbsp;'; print '&nbsp;';
} }
print '</td>'; print '</td>';
} }
print "</tr>"; print "</tr>";
$i++; $i++;
} }
if (empty($num)) { if (empty($num)) {
$colspan = 6; $colspan = 6;
if (!empty($conf->banque->enabled)) $colspan++; if (!empty($conf->banque->enabled)) $colspan++;
print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>'; print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
} }
print "</table>"; print "</table>";
} else { } else {
dol_print_error($db); dol_print_error($db);
} }
} }
if (($action != 'addsubscription' && $action != 'create_thirdparty')) { if (($action != 'addsubscription' && $action != 'create_thirdparty')) {
// Shon online payment link // Shon online payment link
$useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled)); $useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled));
if ($useonlinepayment) { if ($useonlinepayment) {
print '<br>'; print '<br>';
require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
print showOnlinePaymentUrl('membersubscription', $object->ref); print showOnlinePaymentUrl('membersubscription', $object->ref);
print '<br>'; print '<br>';
} }
} }
/* /*
* Add new subscription form * Add new subscription form
*/ */
if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->rights->adherent->cotisation->creer) { if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->rights->adherent->cotisation->creer) {
print '<br>'; print '<br>';
print load_fiche_titre($langs->trans("NewCotisation")); print load_fiche_titre($langs->trans("NewCotisation"));
// Define default choice for complementary actions // Define default choice for complementary actions
$bankdirect = 0; // 1 means option by default is write to bank direct with no invoice $bankdirect = 0; // 1 means option by default is write to bank direct with no invoice
$invoiceonly = 0; // 1 means option by default is invoice only $invoiceonly = 0; // 1 means option by default is invoice only
$bankviainvoice = 0; // 1 means option by default is write to bank via invoice $bankviainvoice = 0; // 1 means option by default is write to bank via invoice
if (GETPOST('paymentsave')) { if (GETPOST('paymentsave')) {
if (GETPOST('paymentsave') == 'bankdirect') $bankdirect = 1; if (GETPOST('paymentsave') == 'bankdirect') $bankdirect = 1;
if (GETPOST('paymentsave') == 'invoiceonly') $invoiceonly = 1; if (GETPOST('paymentsave') == 'invoiceonly') $invoiceonly = 1;
if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice = 1; if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice = 1;
} else { } else {
if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $bankviainvoice = 1; if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $bankviainvoice = 1;
elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) $bankdirect = 1; elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) $bankdirect = 1;
elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $invoiceonly = 1; elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $invoiceonly = 1;
} }
print "\n\n<!-- Form add subscription -->\n"; print "\n\n<!-- Form add subscription -->\n";
if ($conf->use_javascript_ajax) { if ($conf->use_javascript_ajax) {
//var_dump($bankdirect.'-'.$bankviainvoice.'-'.$invoiceonly.'-'.empty($conf->global->ADHERENT_BANK_USE)); //var_dump($bankdirect.'-'.$bankviainvoice.'-'.$invoiceonly.'-'.empty($conf->global->ADHERENT_BANK_USE));
print "\n".'<script type="text/javascript" language="javascript">'; print "\n".'<script type="text/javascript" language="javascript">';
print '$(document).ready(function () { print '$(document).ready(function () {
$(".bankswitchclass, .bankswitchclass2").'.(($bankdirect || $bankviainvoice) ? 'show()' : 'hide()').'; $(".bankswitchclass, .bankswitchclass2").'.(($bankdirect || $bankviainvoice) ? 'show()' : 'hide()').';
$("#none, #invoiceonly").click(function() { $("#none, #invoiceonly").click(function() {
$(".bankswitchclass").hide(); $(".bankswitchclass").hide();
@ -750,10 +750,10 @@ if ($rowid > 0) {
} }
}); });
'; ';
if (GETPOST('paymentsave')) print '$("#'.GETPOST('paymentsave').'").prop("checked",true);'; if (GETPOST('paymentsave')) print '$("#'.GETPOST('paymentsave').'").prop("checked",true);';
print '});'; print '});';
print '</script>'."\n"; print '</script>'."\n";
} }
// Confirm create third party // Confirm create third party
@ -778,16 +778,16 @@ if ($rowid > 0) {
if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED)) { if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED)) {
$tmpcompany = new Societe($db); $tmpcompany = new Societe($db);
$tmpcompany->name = $companyname; $tmpcompany->name = $companyname;
$tmpcompany->get_codeclient($tmpcompany, 0); $tmpcompany->get_codeclient($tmpcompany, 0);
$customercode = $tmpcompany->code_client; $customercode = $tmpcompany->code_client;
$formquestion[] = array( $formquestion[] = array(
'label' => $langs->trans("CustomerCode"), 'label' => $langs->trans("CustomerCode"),
'type' => 'text', 'type' => 'text',
'name' => 'customercode', 'name' => 'customercode',
'value' => $customercode, 'value' => $customercode,
'morecss' => 'minwidth300', 'morecss' => 'minwidth300',
'moreattr' => 'maxlength="128"', 'moreattr' => 'maxlength="128"',
); );
} }
// @todo Add other extrafields mandatory for thirdparty creation // @todo Add other extrafields mandatory for thirdparty creation
@ -795,99 +795,99 @@ if ($rowid > 0) {
} }
print '<form name="subscription" method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form name="subscription" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="subscription">'; print '<input type="hidden" name="action" value="subscription">';
print '<input type="hidden" name="rowid" value="'.$rowid.'">'; print '<input type="hidden" name="rowid" value="'.$rowid.'">';
print '<input type="hidden" name="memberlabel" id="memberlabel" value="'.dol_escape_htmltag($object->getFullName($langs)).'">'; print '<input type="hidden" name="memberlabel" id="memberlabel" value="'.dol_escape_htmltag($object->getFullName($langs)).'">';
print '<input type="hidden" name="thirdpartylabel" id="thirdpartylabel" value="'.dol_escape_htmltag($object->company).'">'; print '<input type="hidden" name="thirdpartylabel" id="thirdpartylabel" value="'.dol_escape_htmltag($object->company).'">';
print dol_get_fiche_head(''); print dol_get_fiche_head('');
print "<table class=\"border\" width=\"100%\">\n"; print "<table class=\"border\" width=\"100%\">\n";
print '<tbody>'; print '<tbody>';
$today = dol_now(); $today = dol_now();
$datefrom = 0; $datefrom = 0;
$dateto = 0; $dateto = 0;
$paymentdate = -1; $paymentdate = -1;
// Date payment // Date payment
if (GETPOST('paymentyear') && GETPOST('paymentmonth') && GETPOST('paymentday')) { if (GETPOST('paymentyear') && GETPOST('paymentmonth') && GETPOST('paymentday')) {
$paymentdate = dol_mktime(0, 0, 0, GETPOST('paymentmonth'), GETPOST('paymentday'), GETPOST('paymentyear')); $paymentdate = dol_mktime(0, 0, 0, GETPOST('paymentmonth'), GETPOST('paymentday'), GETPOST('paymentyear'));
} }
print '<tr>'; print '<tr>';
// Date start subscription // Date start subscription
print '<td class="fieldrequired">'.$langs->trans("DateSubscription").'</td><td>'; print '<td class="fieldrequired">'.$langs->trans("DateSubscription").'</td><td>';
if (GETPOST('reday')) { if (GETPOST('reday')) {
$datefrom = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $datefrom = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
} }
if (!$datefrom) { if (!$datefrom) {
$datefrom = $object->datevalid; $datefrom = $object->datevalid;
if ($object->datefin > 0) { if ($object->datefin > 0) {
$datefrom = dol_time_plus_duree($object->datefin, 1, 'd'); $datefrom = dol_time_plus_duree($object->datefin, 1, 'd');
} }
} }
print $form->selectDate($datefrom, '', '', '', '', "subscription", 1, 1); print $form->selectDate($datefrom, '', '', '', '', "subscription", 1, 1);
print "</td></tr>"; print "</td></tr>";
// Date end subscription // Date end subscription
if (GETPOST('endday')) { if (GETPOST('endday')) {
$dateto = dol_mktime(0, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); $dateto = dol_mktime(0, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
} }
if (!$dateto) { if (!$dateto) {
$dateto = -1; // By default, no date is suggested $dateto = -1; // By default, no date is suggested
} }
print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td>'; print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td>';
print $form->selectDate($dateto, 'end', '', '', '', "subscription", 1, 0); print $form->selectDate($dateto, 'end', '', '', '', "subscription", 1, 0);
print "</td></tr>"; print "</td></tr>";
if ($adht->subscription) { if ($adht->subscription) {
// Amount // Amount
print '<tr><td class="fieldrequired">'.$langs->trans("Amount").'</td><td><input type="text" name="subscription" size="6" value="'.GETPOST('subscription').'"> '.$langs->trans("Currency".$conf->currency).'</td></tr>'; print '<tr><td class="fieldrequired">'.$langs->trans("Amount").'</td><td><input type="text" name="subscription" size="6" value="'.GETPOST('subscription').'"> '.$langs->trans("Currency".$conf->currency).'</td></tr>';
// Label // Label
print '<tr><td>'.$langs->trans("Label").'</td>'; print '<tr><td>'.$langs->trans("Label").'</td>';
print '<td><input name="label" type="text" size="32" value="'; print '<td><input name="label" type="text" size="32" value="';
if (empty($conf->global->MEMBER_NO_DEFAULT_LABEL)) print $langs->trans("Subscription").' '.dol_print_date(($datefrom ? $datefrom : time()), "%Y"); if (empty($conf->global->MEMBER_NO_DEFAULT_LABEL)) print $langs->trans("Subscription").' '.dol_print_date(($datefrom ? $datefrom : time()), "%Y");
print '"></td></tr>'; print '"></td></tr>';
// Complementary action // Complementary action
if ((!empty($conf->banque->enabled) || !empty($conf->facture->enabled)) && empty($conf->global->ADHERENT_SUBSCRIPTION_HIDECOMPLEMENTARYACTIONS)) { if ((!empty($conf->banque->enabled) || !empty($conf->facture->enabled)) && empty($conf->global->ADHERENT_SUBSCRIPTION_HIDECOMPLEMENTARYACTIONS)) {
$company = new Societe($db); $company = new Societe($db);
if ($object->fk_soc) { if ($object->fk_soc) {
$result = $company->fetch($object->fk_soc); $result = $company->fetch($object->fk_soc);
} }
// Title payments // Title payments
//print '<tr><td colspan="2"><b>'.$langs->trans("Payment").'</b></td></tr>'; //print '<tr><td colspan="2"><b>'.$langs->trans("Payment").'</b></td></tr>';
// No more action // No more action
print '<tr><td class="tdtop fieldrequired">'.$langs->trans('MoreActions'); print '<tr><td class="tdtop fieldrequired">'.$langs->trans('MoreActions');
print '</td>'; print '</td>';
print '<td>'; print '<td>';
print '<input type="radio" class="moreaction" id="none" name="paymentsave" value="none"'.(empty($bankdirect) && empty($invoiceonly) && empty($bankviainvoice) ? ' checked' : '').'> '.$langs->trans("None").'<br>'; print '<input type="radio" class="moreaction" id="none" name="paymentsave" value="none"'.(empty($bankdirect) && empty($invoiceonly) && empty($bankviainvoice) ? ' checked' : '').'> '.$langs->trans("None").'<br>';
// Add entry into bank accoun // Add entry into bank accoun
if (!empty($conf->banque->enabled)) { if (!empty($conf->banque->enabled)) {
print '<input type="radio" class="moreaction" id="bankdirect" name="paymentsave" value="bankdirect"'.(!empty($bankdirect) ? ' checked' : ''); print '<input type="radio" class="moreaction" id="bankdirect" name="paymentsave" value="bankdirect"'.(!empty($bankdirect) ? ' checked' : '');
print '> '.$langs->trans("MoreActionBankDirect").'<br>'; print '> '.$langs->trans("MoreActionBankDirect").'<br>';
} }
// Add invoice with no payments // Add invoice with no payments
if (!empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { if (!empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(!empty($invoiceonly) ? ' checked' : ''); print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(!empty($invoiceonly) ? ' checked' : '');
//if (empty($object->fk_soc)) print ' disabled'; //if (empty($object->fk_soc)) print ' disabled';
print '> '.$langs->trans("MoreActionInvoiceOnly"); print '> '.$langs->trans("MoreActionInvoiceOnly");
if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')'; if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
else { else {
print ' ('; print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
print $langs->trans("NoThirdPartyAssociatedToMember"); print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">'; print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty"); print $langs->trans("CreateDolibarrThirdParty");
print '</a>)'; print '</a>)';
} }
if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>'; if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>';
if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
$prodtmp = new Product($db); $prodtmp = new Product($db);
$result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS); $result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS);
@ -896,23 +896,23 @@ if ($rowid > 0) {
} }
print '. '.$langs->transnoentitiesnoconv("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS", $prodtmp->getNomUrl(1)); // must use noentitiesnoconv to avoid to encode html into getNomUrl of product print '. '.$langs->transnoentitiesnoconv("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS", $prodtmp->getNomUrl(1)); // must use noentitiesnoconv to avoid to encode html into getNomUrl of product
} }
print '<br>'; print '<br>';
} }
// Add invoice with payments // Add invoice with payments
if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
print '<input type="radio" class="moreaction" id="bankviainvoice" name="paymentsave" value="bankviainvoice"'.(!empty($bankviainvoice) ? ' checked' : ''); print '<input type="radio" class="moreaction" id="bankviainvoice" name="paymentsave" value="bankviainvoice"'.(!empty($bankviainvoice) ? ' checked' : '');
//if (empty($object->fk_soc)) print ' disabled'; //if (empty($object->fk_soc)) print ' disabled';
print '> '.$langs->trans("MoreActionBankViaInvoice"); print '> '.$langs->trans("MoreActionBankViaInvoice");
if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')'; if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
else { else {
print ' ('; print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
print $langs->trans("NoThirdPartyAssociatedToMember"); print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">'; print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty"); print $langs->trans("CreateDolibarrThirdParty");
print '</a>)'; print '</a>)';
} }
if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>'; if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>';
if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
$prodtmp = new Product($db); $prodtmp = new Product($db);
$result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS); $result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS);

View File

@ -88,9 +88,9 @@ if (($action == 'update' && !GETPOST("cancel", 'alpha'))
dolibarr_del_const($db, "MAIN_INFO_SOCIETE_STATE", $conf->entity); dolibarr_del_const($db, "MAIN_INFO_SOCIETE_STATE", $conf->entity);
} }
$db->begin(); $db->begin();
dolibarr_set_const($db, "MAIN_INFO_SOCIETE_NOM", GETPOST("nom", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_NOM", GETPOST("nom", 'nohtml'), 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ADDRESS", GETPOST("MAIN_INFO_SOCIETE_ADDRESS", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ADDRESS", GETPOST("MAIN_INFO_SOCIETE_ADDRESS", 'nohtml'), 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TOWN", GETPOST("MAIN_INFO_SOCIETE_TOWN", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TOWN", GETPOST("MAIN_INFO_SOCIETE_TOWN", 'nohtml'), 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ZIP", GETPOST("MAIN_INFO_SOCIETE_ZIP", 'alphanohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ZIP", GETPOST("MAIN_INFO_SOCIETE_ZIP", 'alphanohtml'), 'chaine', 0, '', $conf->entity);
@ -141,8 +141,8 @@ if (($action == 'update' && !GETPOST("cancel", 'alpha'))
// Create thumbs of logo (Note that PDF use original file and not thumbs) // Create thumbs of logo (Note that PDF use original file and not thumbs)
if ($isimage > 0) if ($isimage > 0)
{ {
// Create thumbs // Create thumbs
//$object->addThumbs($newfile); // We can't use addThumbs here yet because we need name of generated thumbs to add them into constants. TODO Check if need such constants. We should be able to retrieve value with get... //$object->addThumbs($newfile); // We can't use addThumbs here yet because we need name of generated thumbs to add them into constants. TODO Check if need such constants. We should be able to retrieve value with get...
// Create small thumb, Used on logon for example // Create small thumb, Used on logon for example
$imgThumbSmall = vignette($dirforimage.$original_file, $maxwidthsmall, $maxheightsmall, '_small', $quality); $imgThumbSmall = vignette($dirforimage.$original_file, $maxwidthsmall, $maxheightsmall, '_small', $quality);
@ -269,7 +269,7 @@ if ($action == 'addthumb' || $action == 'addthumbsquarred') // Regenerate thumb
$reg = array(); $reg = array();
// Create thumbs // Create thumbs
//$object->addThumbs($newfile); // We can't use addThumbs here yet because we need name of generated thumbs to add them into constants. TODO Check if need such constants. We should be able to retrieve value with get... //$object->addThumbs($newfile); // We can't use addThumbs here yet because we need name of generated thumbs to add them into constants. TODO Check if need such constants. We should be able to retrieve value with get...
// Create small thumb. Used on logon for example // Create small thumb. Used on logon for example
@ -777,8 +777,8 @@ if ($mysoc->useLocalTax(2))
$tooltiphelp = ($tooltiphelp != "LocalTax2IsUsedExample" ? "<i>".$langs->trans("Example").': '.$langs->transcountry("LocalTax2IsUsedExample", $mysoc->country_code)."</i>\n" : ""); $tooltiphelp = ($tooltiphelp != "LocalTax2IsUsedExample" ? "<i>".$langs->trans("Example").': '.$langs->transcountry("LocalTax2IsUsedExample", $mysoc->country_code)."</i>\n" : "");
if (!isOnlyOneLocalTax(2)) if (!isOnlyOneLocalTax(2))
{ {
print '<br><label for="lt2">'.$langs->trans("LTRate").'</label>: '; print '<br><label for="lt2">'.$langs->trans("LTRate").'</label>: ';
$formcompany->select_localtax(2, $conf->global->MAIN_INFO_VALUE_LOCALTAX2, "lt2"); $formcompany->select_localtax(2, $conf->global->MAIN_INFO_VALUE_LOCALTAX2, "lt2");
} }
print '<br><label for="clt2">'.$langs->trans("CalcLocaltax").'</label>: '; print '<br><label for="clt2">'.$langs->trans("CalcLocaltax").'</label>: ';
print $form->selectarray("clt2", $opcions, $conf->global->MAIN_INFO_LOCALTAX_CALC2); print $form->selectarray("clt2", $opcions, $conf->global->MAIN_INFO_LOCALTAX_CALC2);

View File

@ -881,7 +881,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify'))
if (in_array($rowidcol, array('code', 'code_iso'))) { if (in_array($rowidcol, array('code', 'code_iso'))) {
$sql .= " WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; $sql .= " WHERE ".$rowidcol." = '".$db->escape($rowid)."'";
} else { } else {
$sql .= " WHERE ".$rowidcol." = ".((int) $rowid); $sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
} }
if (in_array('entity', $listfieldmodify)) $sql .= " AND entity = '".getEntity($tabname[$id])."'"; if (in_array('entity', $listfieldmodify)) $sql .= " AND entity = '".getEntity($tabname[$id])."'";

View File

@ -113,17 +113,17 @@ class Asset extends CommonObject
*/ */
public $entity; public $entity;
/** /**
* @var string Asset label * @var string Asset label
*/ */
public $label; public $label;
public $amount; public $amount;
/** /**
* @var int Thirdparty ID * @var int Thirdparty ID
*/ */
public $fk_soc; public $fk_soc;
/** /**
* @var string description * @var string description
@ -134,21 +134,21 @@ class Asset extends CommonObject
public $note_private; public $note_private;
/** /**
* @var integer|string date_creation * @var integer|string date_creation
*/ */
public $date_creation; public $date_creation;
public $tms; public $tms;
/** /**
* @var int ID * @var int ID
*/ */
public $fk_user_creat; public $fk_user_creat;
/** /**
* @var int ID * @var int ID
*/ */
public $fk_user_modif; public $fk_user_modif;
public $import_key; public $import_key;
@ -381,7 +381,7 @@ class Asset extends CommonObject
return $this->LibStatut($this->status, $mode); return $this->LibStatut($this->status, $mode);
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/** /**
* Return the status * Return the status
* *
@ -391,14 +391,14 @@ class Asset extends CommonObject
*/ */
public static function LibStatut($status, $mode = 0) public static function LibStatut($status, $mode = 0)
{ {
// phpcs:enable // phpcs:enable
global $langs; global $langs;
$langs->load("contracts"); $langs->load("contracts");
$labelStatus = array(); $labelStatus = array();
$labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled'); $labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled');
$labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled'); $labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
$labelStatusShort = array(); $labelStatusShort = array();
$labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Disabled'); $labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Disabled');
$labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled'); $labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');

File diff suppressed because it is too large Load Diff

View File

@ -61,44 +61,44 @@ if ($_POST["cancel"] == $langs->trans("Cancel") && !$id)
if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel"))
{ {
$db->begin(); $db->begin();
$datev = dol_mktime(12, 0, 0, $_POST["datevmonth"], $_POST["datevday"], $_POST["datevyear"]); $datev = dol_mktime(12, 0, 0, $_POST["datevmonth"], $_POST["datevday"], $_POST["datevyear"]);
$datep = dol_mktime(12, 0, 0, $_POST["datepmonth"], $_POST["datepday"], $_POST["datepyear"]); $datep = dol_mktime(12, 0, 0, $_POST["datepmonth"], $_POST["datepday"], $_POST["datepyear"]);
$object->accountid = GETPOST("accountid"); $object->accountid = GETPOST("accountid");
$object->paymenttype = GETPOST("paiementtype"); $object->paymenttype = GETPOST("paiementtype");
$object->datev = $datev; $object->datev = $datev;
$object->datep = $datep; $object->datep = $datep;
$object->amount = price2num(GETPOST("amount")); $object->amount = price2num(GETPOST("amount"));
$object->label = GETPOST("label"); $object->label = GETPOST("label");
$object->ltt = $lttype; $object->ltt = $lttype;
$ret = $object->addPayment($user); $ret = $object->addPayment($user);
if ($ret > 0) if ($ret > 0)
{ {
$db->commit(); $db->commit();
header("Location: list.php?localTaxType=".$lttype); header("Location: list.php?localTaxType=".$lttype);
exit; exit;
} else { } else {
$db->rollback(); $db->rollback();
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
$_GET["action"] = "create"; $_GET["action"] = "create";
} }
} }
//delete payment of localtax //delete payment of localtax
if ($action == 'delete') if ($action == 'delete')
{ {
$result = $object->fetch($id); $result = $object->fetch($id);
if ($object->rappro == 0) if ($object->rappro == 0)
{ {
$db->begin(); $db->begin();
$ret = $object->delete($user); $ret = $object->delete($user);
if ($ret > 0) if ($ret > 0)
{ {
if ($object->fk_bank) if ($object->fk_bank)
{ {
$accountline = new AccountLine($db); $accountline = new AccountLine($db);
@ -116,13 +116,13 @@ if ($action == 'delete')
$db->rollback(); $db->rollback();
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
} else { } else {
$db->rollback(); $db->rollback();
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
} else { } else {
$mesg = 'Error try do delete a line linked to a conciliated bank transaction'; $mesg = 'Error try do delete a line linked to a conciliated bank transaction';
setEventMessages($mesg, null, 'errors'); setEventMessages($mesg, null, 'errors');
} }
} }
@ -149,25 +149,25 @@ llxHeader("", $title, $helpurl);
if ($action == 'create') if ($action == 'create')
{ {
print load_fiche_titre($langs->transcountry($lttype == 2 ? "newLT2Payment" : "newLT1Payment", $mysoc->country_code)); print load_fiche_titre($langs->transcountry($lttype == 2 ? "newLT2Payment" : "newLT1Payment", $mysoc->country_code));
print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" name="formlocaltax" method="post">'."\n"; print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" name="formlocaltax" method="post">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="localTaxType" value="'.$lttype.'">'; print '<input type="hidden" name="localTaxType" value="'.$lttype.'">';
print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="action" value="add">';
print dol_get_fiche_head(); print dol_get_fiche_head();
print '<table class="border centpercent">'; print '<table class="border centpercent">';
print "<tr>"; print "<tr>";
print '<td class="titlefieldcreate fieldrequired">'.$langs->trans("DatePayment").'</td><td>'; print '<td class="titlefieldcreate fieldrequired">'.$langs->trans("DatePayment").'</td><td>';
print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1); print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1);
print '</td></tr>'; print '</td></tr>';
print '<tr><td class="fieldrequired">'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).'</td><td>'; print '<tr><td class="fieldrequired">'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).'</td><td>';
print $form->selectDate($datev, "datev", '', '', '', 'add', 1, 1); print $form->selectDate($datev, "datev", '', '', '', 'add', 1, 1);
print '</td></tr>'; print '</td></tr>';
// Label // Label
print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input name="label" class="minwidth200" value="'.($_POST["label"] ?GETPOST("label", '', 2) : $langs->transcountry(($lttype == 2 ? "LT2Payment" : "LT1Payment"), $mysoc->country_code)).'"></td></tr>'; print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input name="label" class="minwidth200" value="'.($_POST["label"] ?GETPOST("label", '', 2) : $langs->transcountry(($lttype == 2 ? "LT2Payment" : "LT1Payment"), $mysoc->country_code)).'"></td></tr>';

File diff suppressed because it is too large Load Diff

View File

@ -33,36 +33,36 @@ abstract class CommonInvoice extends CommonObject
{ {
use CommonIncoterm; use CommonIncoterm;
/** /**
* Standard invoice * Standard invoice
*/ */
const TYPE_STANDARD = 0; const TYPE_STANDARD = 0;
/** /**
* Replacement invoice * Replacement invoice
*/ */
const TYPE_REPLACEMENT = 1; const TYPE_REPLACEMENT = 1;
/** /**
* Credit note invoice * Credit note invoice
*/ */
const TYPE_CREDIT_NOTE = 2; const TYPE_CREDIT_NOTE = 2;
/** /**
* Deposit invoice * Deposit invoice
*/ */
const TYPE_DEPOSIT = 3; const TYPE_DEPOSIT = 3;
/** /**
* Proforma invoice. * Proforma invoice.
* @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice ! * @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice !
*/ */
const TYPE_PROFORMA = 4; const TYPE_PROFORMA = 4;
/** /**
* Situation invoice * Situation invoice
*/ */
const TYPE_SITUATION = 5; const TYPE_SITUATION = 5;
/** /**
* Draft status * Draft status
@ -102,16 +102,16 @@ abstract class CommonInvoice extends CommonObject
*/ */
public function getRemainToPay($multicurrency = 0) public function getRemainToPay($multicurrency = 0)
{ {
$alreadypaid = 0.0; $alreadypaid = 0.0;
$alreadypaid += $this->getSommePaiement($multicurrency); $alreadypaid += $this->getSommePaiement($multicurrency);
$alreadypaid += $this->getSumDepositsUsed($multicurrency); $alreadypaid += $this->getSumDepositsUsed($multicurrency);
$alreadypaid += $this->getSumCreditNotesUsed($multicurrency); $alreadypaid += $this->getSumCreditNotesUsed($multicurrency);
$remaintopay = price2num($this->total_ttc - $alreadypaid, 'MT'); $remaintopay = price2num($this->total_ttc - $alreadypaid, 'MT');
if ($this->statut == self::STATUS_CLOSED && $this->close_code == 'discount_vat') { // If invoice closed with discount for anticipated payment if ($this->statut == self::STATUS_CLOSED && $this->close_code == 'discount_vat') { // If invoice closed with discount for anticipated payment
$remaintopay = 0.0; $remaintopay = 0.0;
} }
return $remaintopay; return $remaintopay;
} }
/** /**
@ -151,7 +151,7 @@ abstract class CommonInvoice extends CommonObject
/** /**
* Return amount (with tax) of all deposits invoices used by invoice. * Return amount (with tax) of all deposits invoices used by invoice.
* Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended). * Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended).
* *
* @param int $multicurrency Return multicurrency_amount instead of amount * @param int $multicurrency Return multicurrency_amount instead of amount
* @return float <0 if KO, Sum of deposits amount otherwise * @return float <0 if KO, Sum of deposits amount otherwise
@ -159,21 +159,21 @@ abstract class CommonInvoice extends CommonObject
public function getSumDepositsUsed($multicurrency = 0) public function getSumDepositsUsed($multicurrency = 0)
{ {
if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
{ {
// TODO // TODO
return 0.0; return 0.0;
} }
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
$discountstatic = new DiscountAbsolute($this->db); $discountstatic = new DiscountAbsolute($this->db);
$result = $discountstatic->getSumDepositsUsed($this, $multicurrency); $result = $discountstatic->getSumDepositsUsed($this, $multicurrency);
if ($result >= 0) { if ($result >= 0) {
return $result; return $result;
} else { } else {
$this->error = $discountstatic->error; $this->error = $discountstatic->error;
return -1; return -1;
} }
} }
/** /**
@ -184,16 +184,16 @@ abstract class CommonInvoice extends CommonObject
*/ */
public function getSumCreditNotesUsed($multicurrency = 0) public function getSumCreditNotesUsed($multicurrency = 0)
{ {
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
$discountstatic = new DiscountAbsolute($this->db); $discountstatic = new DiscountAbsolute($this->db);
$result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency); $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency);
if ($result >= 0) { if ($result >= 0) {
return $result; return $result;
} else { } else {
$this->error = $discountstatic->error; $this->error = $discountstatic->error;
return -1; return -1;
} }
} }
/** /**
@ -204,16 +204,16 @@ abstract class CommonInvoice extends CommonObject
*/ */
public function getSumFromThisCreditNotesNotUsed($multicurrency = 0) public function getSumFromThisCreditNotesNotUsed($multicurrency = 0)
{ {
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
$discountstatic = new DiscountAbsolute($this->db); $discountstatic = new DiscountAbsolute($this->db);
$result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency); $result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency);
if ($result >= 0) { if ($result >= 0) {
return $result; return $result;
} else { } else {
$this->error = $discountstatic->error; $this->error = $discountstatic->error;
return -1; return -1;
} }
} }
/** /**
@ -329,7 +329,7 @@ abstract class CommonInvoice extends CommonObject
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$tmp = array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref); $tmp = array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
if (!empty($field3)) { if (!empty($field3)) {
$tmp['ref_ext'] = $obj->ref_ext; $tmp['ref_ext'] = $obj->ref_ext;
} }
$retarray[]=$tmp; $retarray[]=$tmp;
$i++; $i++;
@ -385,7 +385,7 @@ abstract class CommonInvoice extends CommonObject
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/** /**
* Return if an invoice can be deleted * Return if an invoice can be deleted
* Rule is: * Rule is:
@ -399,9 +399,9 @@ abstract class CommonInvoice extends CommonObject
* *
* @return int <=0 if no, >0 if yes * @return int <=0 if no, >0 if yes
*/ */
public function is_erasable() public function is_erasable()
{ {
// phpcs:enable // phpcs:enable
global $conf; global $conf;
// We check if invoice is a temporary number (PROVxxxx) // We check if invoice is a temporary number (PROVxxxx)
@ -486,15 +486,15 @@ abstract class CommonInvoice extends CommonObject
* *
* @return string Label of type of invoice * @return string Label of type of invoice
*/ */
public function getLibType() public function getLibType()
{ {
global $langs; global $langs;
if ($this->type == CommonInvoice::TYPE_STANDARD) return $langs->trans("InvoiceStandard"); if ($this->type == CommonInvoice::TYPE_STANDARD) return $langs->trans("InvoiceStandard");
elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement"); elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement");
elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir"); elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir");
elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit"); elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit");
elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma"); // Not used. elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma"); // Not used.
elseif ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation"); elseif ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation");
return $langs->trans("Unknown"); return $langs->trans("Unknown");
} }
@ -510,7 +510,7 @@ abstract class CommonInvoice extends CommonObject
return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type); return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type);
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/** /**
* Return label of a status * Return label of a status
* *
@ -523,52 +523,52 @@ abstract class CommonInvoice extends CommonObject
*/ */
public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = 0) public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = 0)
{ {
// phpcs:enable // phpcs:enable
global $langs; global $langs;
$langs->load('bills'); $langs->load('bills');
$statusType = 'status0'; $statusType = 'status0';
$prefix = 'Short'; $prefix = 'Short';
if (!$paye) { if (!$paye) {
if ($status == 0) { if ($status == 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft'); $labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft'); $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft');
} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) { } elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid'); $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid'); $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid');
$statusType = 'status5'; $statusType = 'status5';
} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) { } elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially'); $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially'); $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially');
$statusType = 'status9'; $statusType = 'status9';
} elseif ($alreadypaid == 0) { } elseif ($alreadypaid == 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid'); $labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid'); $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid');
$statusType = 'status1'; $statusType = 'status1';
} else { } else {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted'); $labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted'); $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted');
$statusType = 'status3'; $statusType = 'status3';
} }
} else { } else {
$statusType = 'status6'; $statusType = 'status6';
if ($type == self::TYPE_CREDIT_NOTE) { if ($type == self::TYPE_CREDIT_NOTE) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note
} elseif ($type == self::TYPE_DEPOSIT) { } elseif ($type == self::TYPE_DEPOSIT) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice $labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice
} else { } else {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid'); $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid'); $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid');
} }
} }
return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/** /**
* Returns an invoice payment deadline based on the invoice settlement * Returns an invoice payment deadline based on the invoice settlement
* conditions and billing date. * conditions and billing date.
@ -576,15 +576,15 @@ abstract class CommonInvoice extends CommonObject
* @param integer $cond_reglement Condition of payment (code or id) to use. If 0, we use current condition. * @param integer $cond_reglement Condition of payment (code or id) to use. If 0, we use current condition.
* @return integer Date limite de reglement si ok, <0 si ko * @return integer Date limite de reglement si ok, <0 si ko
*/ */
public function calculate_date_lim_reglement($cond_reglement = 0) public function calculate_date_lim_reglement($cond_reglement = 0)
{ {
// phpcs:enable // phpcs:enable
if (!$cond_reglement) $cond_reglement = $this->cond_reglement_code; if (!$cond_reglement) $cond_reglement = $this->cond_reglement_code;
if (!$cond_reglement) $cond_reglement = $this->cond_reglement_id; if (!$cond_reglement) $cond_reglement = $this->cond_reglement_id;
$cdr_nbjour = 0; $cdr_nbjour = 0;
$cdr_type = 0; $cdr_type = 0;
$cdr_decalage = 0; $cdr_decalage = 0;
$sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage'; $sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
$sqltemp .= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; $sqltemp .= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
@ -643,7 +643,7 @@ abstract class CommonInvoice extends CommonObject
// 2 : application of the rule, the N of the current or next month // 2 : application of the rule, the N of the current or next month
elseif ($cdr_type == 2 && !empty($cdr_decalage)) elseif ($cdr_type == 2 && !empty($cdr_decalage))
{ {
include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
$datelim = $this->date + ($cdr_nbjour * 3600 * 24); $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
$date_piece = dol_mktime(0, 0, 0, date('m', $datelim), date('d', $datelim), date('Y', $datelim)); // Sans les heures minutes et secondes $date_piece = dol_mktime(0, 0, 0, date('m', $datelim), date('d', $datelim), date('Y', $datelim)); // Sans les heures minutes et secondes

View File

@ -6701,10 +6701,10 @@ function setEventMessage($mesgs, $style = 'mesgs')
{ {
//dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
if (!is_array($mesgs)) { if (!is_array($mesgs)) {
// If mesgs is a string // If mesgs is a string
if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs; if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
} else { } else {
// If mesgs is an array // If mesgs is an array
foreach ($mesgs as $mesg) foreach ($mesgs as $mesg)
{ {
if ($mesg) $_SESSION['dol_events'][$style][] = $mesg; if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;

View File

@ -1641,7 +1641,7 @@ function getListOfModels($db, $type, $maxfilenamelength = 0)
$liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name']; $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name'];
} }
} else { } else {
// Common usage // Common usage
$liste[$obj->id] = $obj->label ? $obj->label : $obj->doc_template_name; $liste[$obj->id] = $obj->label ? $obj->label : $obj->doc_template_name;
} }
} }

View File

@ -32,10 +32,10 @@
*/ */
function loan_prepare_head($object) function loan_prepare_head($object)
{ {
global $db, $langs, $conf; global $db, $langs, $conf;
$tab = 0; $tab = 0;
$head = array(); $head = array();
$head[$tab][0] = DOL_URL_ROOT.'/loan/card.php?id='.$object->id; $head[$tab][0] = DOL_URL_ROOT.'/loan/card.php?id='.$object->id;
$head[$tab][1] = $langs->trans('Card'); $head[$tab][1] = $langs->trans('Card');
@ -47,17 +47,17 @@ function loan_prepare_head($object)
$head[$tab][2] = 'FinancialCommitment'; $head[$tab][2] = 'FinancialCommitment';
$tab++; $tab++;
// Show more tabs from modules // Show more tabs from modules
// Entries must be declared in modules descriptor with line // Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab // $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $tab, 'loan'); complete_head_from_modules($conf, $langs, $object, $head, $tab, 'loan');
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$upload_dir = $conf->loan->dir_output."/".dol_sanitizeFileName($object->ref); $upload_dir = $conf->loan->dir_output."/".dol_sanitizeFileName($object->ref);
$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
$nbLinks = Link::count($db, $object->element, $object->id); $nbLinks = Link::count($db, $object->element, $object->id);
$head[$tab][0] = DOL_URL_ROOT.'/loan/document.php?id='.$object->id; $head[$tab][0] = DOL_URL_ROOT.'/loan/document.php?id='.$object->id;
$head[$tab][1] = $langs->trans("Documents"); $head[$tab][1] = $langs->trans("Documents");
if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
@ -73,14 +73,14 @@ function loan_prepare_head($object)
$tab++; $tab++;
} }
$head[$tab][0] = DOL_URL_ROOT.'/loan/info.php?id='.$object->id; $head[$tab][0] = DOL_URL_ROOT.'/loan/info.php?id='.$object->id;
$head[$tab][1] = $langs->trans("Info"); $head[$tab][1] = $langs->trans("Info");
$head[$tab][2] = 'info'; $head[$tab][2] = 'info';
$tab++; $tab++;
complete_head_from_modules($conf, $langs, $object, $head, $tab, 'loan', 'remove'); complete_head_from_modules($conf, $langs, $object, $head, $tab, 'loan', 'remove');
return $head; return $head;
} }
/** /**
@ -95,42 +95,42 @@ function loan_prepare_head($object)
*/ */
function loanCalcMonthlyPayment($mens, $capital, $rate, $echance, $nbterm) function loanCalcMonthlyPayment($mens, $capital, $rate, $echance, $nbterm)
{ {
global $conf, $db; global $conf, $db;
require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php';
$object = new LoanSchedule($db); $object = new LoanSchedule($db);
$output = array(); $output = array();
// If mensuality is 0 we don't pay interests and remaining capital not modified // If mensuality is 0 we don't pay interests and remaining capital not modified
if ($mens == 0) { if ($mens == 0) {
$int = 0; $int = 0;
$cap_rest = $capital; $cap_rest = $capital;
} else { } else {
$int = ($capital * ($rate / 12)); $int = ($capital * ($rate / 12));
$int = round($int, 2, PHP_ROUND_HALF_UP); $int = round($int, 2, PHP_ROUND_HALF_UP);
$cap_rest = round($capital - ($mens - $int), 2, PHP_ROUND_HALF_UP); $cap_rest = round($capital - ($mens - $int), 2, PHP_ROUND_HALF_UP);
} }
$output[$echance] = array('cap_rest'=>$cap_rest, 'cap_rest_str'=>price($cap_rest, 0, '', 1, -1, -1, $conf->currency), 'interet'=>$int, 'interet_str'=>price($int, 0, '', 1, -1, -1, $conf->currency), 'mens'=>$mens); $output[$echance] = array('cap_rest'=>$cap_rest, 'cap_rest_str'=>price($cap_rest, 0, '', 1, -1, -1, $conf->currency), 'interet'=>$int, 'interet_str'=>price($int, 0, '', 1, -1, -1, $conf->currency), 'mens'=>$mens);
$echance++; $echance++;
$capital = $cap_rest; $capital = $cap_rest;
while ($echance <= $nbterm) { while ($echance <= $nbterm) {
$mens = round($object->calcMonthlyPayments($capital, $rate, $nbterm - $echance + 1), 2, PHP_ROUND_HALF_UP); $mens = round($object->calcMonthlyPayments($capital, $rate, $nbterm - $echance + 1), 2, PHP_ROUND_HALF_UP);
$int = ($capital * ($rate / 12)); $int = ($capital * ($rate / 12));
$int = round($int, 2, PHP_ROUND_HALF_UP); $int = round($int, 2, PHP_ROUND_HALF_UP);
$cap_rest = round($capital - ($mens - $int), 2, PHP_ROUND_HALF_UP); $cap_rest = round($capital - ($mens - $int), 2, PHP_ROUND_HALF_UP);
$output[$echance] = array( $output[$echance] = array(
'cap_rest' => $cap_rest, 'cap_rest' => $cap_rest,
'cap_rest_str' => price($cap_rest, 0, '', 1, -1, -1, $conf->currency), 'cap_rest_str' => price($cap_rest, 0, '', 1, -1, -1, $conf->currency),
'interet' => $int, 'interet' => $int,
'interet_str' => price($int, 0, '', 1, -1, -1, $conf->currency), 'interet_str' => price($int, 0, '', 1, -1, -1, $conf->currency),
'mens' => $mens, 'mens' => $mens,
); );
$capital = $cap_rest; $capital = $cap_rest;
$echance++; $echance++;
} }
return $output; return $output;
} }

View File

@ -31,15 +31,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
class mod_task_universal extends ModeleNumRefTask class mod_task_universal extends ModeleNumRefTask
{ {
/** /**
* Dolibarr version of the loaded document * Dolibarr version of the loaded document
* @var string * @var string
*/ */
public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr'
/** /**
* @var string Error code (or message) * @var string Error code (or message)
*/ */
public $error = ''; public $error = '';
/** /**
* @var string * @var string
@ -54,17 +54,17 @@ class mod_task_universal extends ModeleNumRefTask
public $name = 'Universal'; public $name = 'Universal';
/** /**
* Returns the description of the numbering model * Returns the description of the numbering model
* *
* @return string Texte descripif * @return string Texte descripif
*/ */
public function info() public function info()
{ {
global $conf, $langs, $db; global $conf, $langs, $db;
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("projects", "admin")); $langs->loadLangs(array("projects", "admin"));
$form = new Form($db); $form = new Form($db);
@ -93,37 +93,37 @@ class mod_task_universal extends ModeleNumRefTask
$texte .= '</form>'; $texte .= '</form>';
return $texte; return $texte;
} }
/** /**
* Return an example of numbering * Return an example of numbering
* *
* @return string Example * @return string Example
*/ */
public function getExample() public function getExample()
{ {
global $conf, $langs, $mysoc; global $conf, $langs, $mysoc;
$old_code_client = $mysoc->code_client; $old_code_client = $mysoc->code_client;
$mysoc->code_client = 'CCCCCCCCCC'; $mysoc->code_client = 'CCCCCCCCCC';
$numExample = $this->getNextValue($mysoc, ''); $numExample = $this->getNextValue($mysoc, '');
$mysoc->code_client = $old_code_client; $mysoc->code_client = $old_code_client;
if (!$numExample) { if (!$numExample) {
$numExample = $langs->trans('NotConfigured'); $numExample = $langs->trans('NotConfigured');
} }
return $numExample; return $numExample;
} }
/** /**
* Return next value * Return next value
* *
* @param Societe $objsoc Object third party * @param Societe $objsoc Object third party
* @param Task $object Object task * @param Task $object Object task
* @return string Value if OK, 0 if KO * @return string Value if OK, 0 if KO
*/ */
public function getNextValue($objsoc, $object) public function getNextValue($objsoc, $object)
{ {
global $db, $conf; global $db, $conf;
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
@ -143,17 +143,17 @@ class mod_task_universal extends ModeleNumRefTask
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/** /**
* Return next reference not yet used as a reference * Return next reference not yet used as a reference
* *
* @param Societe $objsoc Object third party * @param Societe $objsoc Object third party
* @param Task $object Object task * @param Task $object Object task
* @return string Next not used reference * @return string Next not used reference
*/ */
public function project_get_num($objsoc = 0, $object = '') public function project_get_num($objsoc = 0, $object = '')
{ {
// phpcs:enable // phpcs:enable
return $this->getNextValue($objsoc, $object); return $this->getNextValue($objsoc, $object);
} }
} }

View File

@ -685,7 +685,7 @@ class Don extends CommonObject
$this->note_private = $obj->note_private; $this->note_private = $obj->note_private;
$this->note_public = $obj->note_public; $this->note_public = $obj->note_public;
$this->model_pdf = $obj->model_pdf; $this->model_pdf = $obj->model_pdf;
$this->modelpdf = $obj->model_pdf; // deprecated $this->modelpdf = $obj->model_pdf; // deprecated
// Retrieve all extrafield // Retrieve all extrafield
// fetch optionals attributes and labels // fetch optionals attributes and labels

View File

@ -80,11 +80,11 @@ if ($action == 'add_payment')
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors');
$error++; $error++;
} }
if (!empty($conf->banque->enabled) && !($accountid > 0)) if (!empty($conf->banque->enabled) && !($accountid > 0))
{ {
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToDebit")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToDebit")), null, 'errors');
$error++; $error++;
} }
if (!$error) if (!$error)
{ {
@ -101,67 +101,67 @@ if ($action == 'add_payment')
} }
} }
if (count($amounts) <= 0) if (count($amounts) <= 0)
{ {
$error++; $error++;
$errmsg = 'ErrorNoPaymentDefined'; $errmsg = 'ErrorNoPaymentDefined';
} }
if (!$error) if (!$error)
{ {
$db->begin(); $db->begin();
// Create a line of payments // Create a line of payments
$payment = new PaymentExpenseReport($db); $payment = new PaymentExpenseReport($db);
$payment->fk_expensereport = $expensereport->id; $payment->fk_expensereport = $expensereport->id;
$payment->datepaid = $datepaid; $payment->datepaid = $datepaid;
$payment->amounts = $amounts; // Tableau de montant $payment->amounts = $amounts; // Tableau de montant
$payment->total = $total; $payment->total = $total;
$payment->fk_typepayment = GETPOST("fk_typepayment", 'int'); $payment->fk_typepayment = GETPOST("fk_typepayment", 'int');
$payment->num_payment = GETPOST("num_payment", 'alphanothtml'); $payment->num_payment = GETPOST("num_payment", 'alphanothtml');
$payment->note_public = GETPOST("note_public", 'restricthtml'); $payment->note_public = GETPOST("note_public", 'restricthtml');
if (!$error) if (!$error)
{ {
$paymentid = $payment->create($user); $paymentid = $payment->create($user);
if ($paymentid < 0) if ($paymentid < 0)
{ {
setEventMessages($payment->error, $payment->errors, 'errors'); setEventMessages($payment->error, $payment->errors, 'errors');
$error++; $error++;
} }
} }
if (!$error) if (!$error)
{ {
$result = $payment->addPaymentToBank($user, 'payment_expensereport', '(ExpenseReportPayment)', $accountid, '', ''); $result = $payment->addPaymentToBank($user, 'payment_expensereport', '(ExpenseReportPayment)', $accountid, '', '');
if (!$result > 0) if (!$result > 0)
{ {
setEventMessages($payment->error, $payment->errors, 'errors'); setEventMessages($payment->error, $payment->errors, 'errors');
$error++; $error++;
} }
} }
if (!$error) { if (!$error) {
$payment->fetch($paymentid); $payment->fetch($paymentid);
if ($expensereport->total_ttc - $payment->amount == 0) { if ($expensereport->total_ttc - $payment->amount == 0) {
$result = $expensereport->set_paid($expensereport->id, $user); $result = $expensereport->set_paid($expensereport->id, $user);
if (!$result > 0) { if (!$result > 0) {
setEventMessages($payment->error, $payment->errors, 'errors'); setEventMessages($payment->error, $payment->errors, 'errors');
$error++; $error++;
} }
} }
} }
if (!$error) if (!$error)
{ {
$db->commit(); $db->commit();
$loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id; $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id;
header('Location: '.$loc); header('Location: '.$loc);
exit; exit;
} else { } else {
$db->rollback(); $db->rollback();
} }
} }
} }
$action = 'create'; $action = 'create';
@ -194,9 +194,9 @@ if ($action == 'create' || empty($action))
var amount = $(this).data("value"); var amount = $(this).data("value");
document.getElementById($(this).data(\'rowid\')).value = amount ; document.getElementById($(this).data(\'rowid\')).value = amount ;
});'; });';
print "\t});\n"; print "\t});\n";
print "</script>\n"; print "</script>\n";
} }
print load_fiche_titre($langs->trans("DoPayment")); print load_fiche_titre($langs->trans("DoPayment"));
@ -206,17 +206,17 @@ if ($action == 'create' || empty($action))
print '<input type="hidden" name="chid" value="'.$expensereport->id.'">'; print '<input type="hidden" name="chid" value="'.$expensereport->id.'">';
print '<input type="hidden" name="action" value="add_payment">'; print '<input type="hidden" name="action" value="add_payment">';
print dol_get_fiche_head(null, '0', '', -1); print dol_get_fiche_head(null, '0', '', -1);
$linkback = ''; $linkback = '';
// $linkback = '<a href="' . DOL_URL_ROOT . '/expensereport/payment/list.php">' . $langs->trans("BackToList") . '</a>'; // $linkback = '<a href="' . DOL_URL_ROOT . '/expensereport/payment/list.php">' . $langs->trans("BackToList") . '</a>';
dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', ''); dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', '');
print '<div class="fichecenter">'; print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>'; print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent">'."\n"; print '<table class="border centpercent">'."\n";
print '<tr><td class="titlefield">'.$langs->trans("Period").'</td><td>'.get_date_range($expensereport->date_debut, $expensereport->date_fin, "", $langs, 0).'</td></tr>'; print '<tr><td class="titlefield">'.$langs->trans("Period").'</td><td>'.get_date_range($expensereport->date_debut, $expensereport->date_fin, "", $langs, 0).'</td></tr>';
print '<tr><td>'.$langs->trans("Amount").'</td><td>'.price($expensereport->total_ttc, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>'; print '<tr><td>'.$langs->trans("Amount").'</td><td>'.price($expensereport->total_ttc, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>';
@ -224,7 +224,7 @@ if ($action == 'create' || empty($action))
$sql = "SELECT sum(p.amount) as total"; $sql = "SELECT sum(p.amount) as total";
$sql .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as p, ".MAIN_DB_PREFIX."expensereport as e"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as p, ".MAIN_DB_PREFIX."expensereport as e";
$sql .= " WHERE p.fk_expensereport = e.rowid AND p.fk_expensereport = ".$id; $sql .= " WHERE p.fk_expensereport = e.rowid AND p.fk_expensereport = ".$id;
$sql .= ' AND e.entity IN ('.getEntity('expensereport').')'; $sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql)
{ {
@ -259,11 +259,11 @@ if ($action == 'create' || empty($action))
if (!empty($conf->banque->enabled)) if (!empty($conf->banque->enabled))
{ {
print '<tr>'; print '<tr>';
print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>'; print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>';
print '<td colspan="2">'; print '<td colspan="2">';
$form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", "int") : $expensereport->accountid, "accountid", 0, '', 2); // Show open bank account list $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", "int") : $expensereport->accountid, "accountid", 0, '', 2); // Show open bank account list
print '</td></tr>'; print '</td></tr>';
} }
// Number // Number

File diff suppressed because it is too large Load Diff

View File

@ -42,15 +42,15 @@ function paypaladmin_prepare_head()
$object = new stdClass(); $object = new stdClass();
// Show more tabs from modules // Show more tabs from modules
// Entries must be declared in modules descriptor with line // Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab // $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'paypaladmin'); complete_head_from_modules($conf, $langs, $object, $head, $h, 'paypaladmin');
complete_head_from_modules($conf, $langs, $object, $head, $h, 'paypaladmin', 'remove'); complete_head_from_modules($conf, $langs, $object, $head, $h, 'paypaladmin', 'remove');
return $head; return $head;
} }
@ -67,14 +67,14 @@ function showPaypalPaymentUrl($type, $ref)
global $conf, $langs; global $conf, $langs;
$langs->load("paypal"); $langs->load("paypal");
$langs->load("paybox"); $langs->load("paybox");
$servicename = 'PayPal'; $servicename = 'PayPal';
$out = '<br><br>'; $out = '<br><br>';
$out .= img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'<br>'; $out .= img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'<br>';
$url = getPaypalPaymentUrl(0, $type, $ref); $url = getPaypalPaymentUrl(0, $type, $ref);
$out .= '<input type="text" id="paypalurl" class="quatrevingtpercent" value="'.$url.'">'; $out .= '<input type="text" id="paypalurl" class="quatrevingtpercent" value="'.$url.'">';
$out .= ajax_autoselect("paypalurl", 0); $out .= ajax_autoselect("paypalurl", 0);
return $out; return $out;
} }
@ -94,88 +94,88 @@ function getPaypalPaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
$ref = str_replace(' ', '', $ref); $ref = str_replace(' ', '', $ref);
if ($type == 'free') if ($type == 'free')
{ {
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?amount='.($mode ? '<font color="#666666">' : '').$amount.($mode ? '</font>' : '').'&tag='.($mode ? '<font color="#666666">' : '').$freetag.($mode ? '</font>' : ''); $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?amount='.($mode ? '<font color="#666666">' : '').$amount.($mode ? '</font>' : '').'&tag='.($mode ? '<font color="#666666">' : '').$freetag.($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{ {
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else $out .= '&securekey='.dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); else $out .= '&securekey='.dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
} }
} }
if ($type == 'order') if ($type == 'order')
{ {
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=order&ref='.($mode ? '<font color="#666666">' : ''); $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=order&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'order_ref'; if ($mode == 1) $out .= 'order_ref';
if ($mode == 0) $out .= urlencode($ref); if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{ {
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else { else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : ''); $out .= '&securekey='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + order_ref)"; if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + order_ref)";
if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
} }
} }
} }
if ($type == 'invoice') if ($type == 'invoice')
{ {
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode ? '<font color="#666666">' : ''); $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'invoice_ref'; if ($mode == 1) $out .= 'invoice_ref';
if ($mode == 0) $out .= urlencode($ref); if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{ {
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else { else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : ''); $out .= '&securekey='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + invoice_ref)"; if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + invoice_ref)";
if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
} }
} }
} }
if ($type == 'contractline') if ($type == 'contractline')
{ {
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode ? '<font color="#666666">' : ''); $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'contractline_ref'; if ($mode == 1) $out .= 'contractline_ref';
if ($mode == 0) $out .= urlencode($ref); if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{ {
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else { else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : ''); $out .= '&securekey='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + contractline_ref)"; if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + contractline_ref)";
if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
} }
} }
} }
if ($type == 'membersubscription') if ($type == 'membersubscription')
{ {
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode ? '<font color="#666666">' : ''); $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'member_ref'; if ($mode == 1) $out .= 'member_ref';
if ($mode == 0) $out .= urlencode($ref); if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{ {
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else { else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : ''); $out .= '&securekey='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + member_ref)"; if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + member_ref)";
if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2);
$out .= ($mode ? '</font>' : ''); $out .= ($mode ? '</font>' : '');
} }
} }
} }
// For multicompany // For multicompany
$out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities $out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities
return $out; return $out;
} }
@ -192,93 +192,93 @@ function getPaypalPaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
*/ */
function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag) function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag)
{ {
//declaring of global variables //declaring of global variables
global $conf, $langs; global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT; global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
global $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum; global $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum;
global $email, $desc; global $email, $desc;
//'------------------------------------ //'------------------------------------
//' Calls the SetExpressCheckout API call //' Calls the SetExpressCheckout API call
//' //'
//'------------------------------------------------- //'-------------------------------------------------
if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral';
$solutionType = 'Sole'; $solutionType = 'Sole';
$landingPage = 'Billing'; $landingPage = 'Billing';
// For payment with Paypal only // For payment with Paypal only
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly')
{ {
$solutionType = 'Mark'; $solutionType = 'Mark';
$landingPage = 'Login'; $landingPage = 'Login';
} }
// For payment with Credit card or Paypal // For payment with Credit card or Paypal
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral')
{ {
$solutionType = 'Sole'; $solutionType = 'Sole';
$landingPage = 'Billing'; $landingPage = 'Billing';
} }
// For payment with Credit card // For payment with Credit card
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly') if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly')
{ {
$solutionType = 'Sole'; $solutionType = 'Sole';
$landingPage = 'Billing'; $landingPage = 'Billing';
} }
dol_syslog("expresscheckout redirect with callSetExpressCheckout $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum"); dol_syslog("expresscheckout redirect with callSetExpressCheckout $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum");
$resArray = callSetExpressCheckout( $resArray = callSetExpressCheckout(
$paymentAmount, $paymentAmount,
$currencyCodeType, $currencyCodeType,
$paymentType, $paymentType,
$returnURL, $returnURL,
$cancelURL, $cancelURL,
$tag, $tag,
$solutionType, $solutionType,
$landingPage, $landingPage,
$shipToName, $shipToName,
$shipToStreet, $shipToStreet,
$shipToCity, $shipToCity,
$shipToState, $shipToState,
$shipToCountryCode, $shipToCountryCode,
$shipToZip, $shipToZip,
$shipToStreet2, $shipToStreet2,
$phoneNum, $phoneNum,
$email, $email,
$desc $desc
); );
$ack = strtoupper($resArray["ACK"]); $ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{ {
$token = $resArray["TOKEN"]; $token = $resArray["TOKEN"];
// Redirect to paypal.com here // Redirect to paypal.com here
$payPalURL = $API_Url.$token; $payPalURL = $API_Url.$token;
header("Location: ".$payPalURL); header("Location: ".$payPalURL);
exit; exit;
} else { } else {
//Display a user friendly Error on the page using any of the following error information returned by PayPal //Display a user friendly Error on the page using any of the following error information returned by PayPal
$ErrorCode = urldecode($resArray["L_ERRORCODE0"]); $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]); $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]); $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]); $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
if ($ErrorCode == 10729) if ($ErrorCode == 10729)
{ {
$mesg .= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).<br>Ask system administrator to fix address or to setup Paypal module to accept payments even on not complete addresses (remove option PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS).<br>\n"; $mesg .= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).<br>Ask system administrator to fix address or to setup Paypal module to accept payments even on not complete addresses (remove option PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS).<br>\n";
} else { } else {
$mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."<br>\n"; $mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."<br>\n";
$mesg .= $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n"; $mesg .= $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
$mesg .= $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n"; $mesg .= $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
$mesg .= $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n"; $mesg .= $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
$mesg .= $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n"; $mesg .= $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
} }
return $mesg; return $mesg;
} }
} }
/** /**
@ -324,103 +324,103 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType,
*/ */
function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum, $email = '', $desc = '') function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum, $email = '', $desc = '')
{ {
//------------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
//declaring of global variables //declaring of global variables
global $conf, $langs, $mysoc; global $conf, $langs, $mysoc;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT; global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
$nvpstr = ''; $nvpstr = '';
//$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call //$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call
$nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL); $nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL);
$nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL); $nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL);
if (!empty($conf->global->PAYPAL_ALLOW_NOTES)) if (!empty($conf->global->PAYPAL_ALLOW_NOTES))
{ {
$nvpstr = $nvpstr."&ALLOWNOTE=0"; $nvpstr = $nvpstr."&ALLOWNOTE=0";
} }
if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS)) if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS))
{ {
$nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted $nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted
} else { } else {
$nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory) $nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory)
} }
$nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType); $nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType);
$nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage); $nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage);
if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER)) if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER))
{ {
$nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number $nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number
} }
$paypalprefix = 'PAYMENTREQUEST_0_'; $paypalprefix = 'PAYMENTREQUEST_0_';
//$paypalprefix = ''; //$paypalprefix = '';
if (!empty($paypalprefix) && $paymentType == 'Sole') $paymentType = 'Sale'; if (!empty($paypalprefix) && $paymentType == 'Sole') $paymentType = 'Sale';
$nvpstr = $nvpstr."&AMT=".urlencode($paymentAmount); // Total for all elements $nvpstr = $nvpstr."&AMT=".urlencode($paymentAmount); // Total for all elements
$nvpstr = $nvpstr."&".$paypalprefix."INVNUM=".urlencode($tag); $nvpstr = $nvpstr."&".$paypalprefix."INVNUM=".urlencode($tag);
$nvpstr = $nvpstr."&".$paypalprefix."AMT=".urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT $nvpstr = $nvpstr."&".$paypalprefix."AMT=".urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT
$nvpstr = $nvpstr."&".$paypalprefix."ITEMAMT=".urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT $nvpstr = $nvpstr."&".$paypalprefix."ITEMAMT=".urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT
$nvpstr = $nvpstr."&".$paypalprefix."PAYMENTACTION=".urlencode($paymentType); // PAYMENTACTION deprecated by paypal -> PAYMENTREQUEST_n_PAYMENTACTION $nvpstr = $nvpstr."&".$paypalprefix."PAYMENTACTION=".urlencode($paymentType); // PAYMENTACTION deprecated by paypal -> PAYMENTREQUEST_n_PAYMENTACTION
$nvpstr = $nvpstr."&".$paypalprefix."CURRENCYCODE=".urlencode($currencyCodeType); // CURRENCYCODE deprecated by paypal -> PAYMENTREQUEST_n_CURRENCYCODE $nvpstr = $nvpstr."&".$paypalprefix."CURRENCYCODE=".urlencode($currencyCodeType); // CURRENCYCODE deprecated by paypal -> PAYMENTREQUEST_n_CURRENCYCODE
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_QTY0=1"; $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_QTY0=1";
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_AMT0=".urlencode($paymentAmount); $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_AMT0=".urlencode($paymentAmount);
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NAME0=".urlencode($desc); $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NAME0=".urlencode($desc);
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NUMBER0=0"; $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NUMBER0=0";
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTONAME=".urlencode($shipToName); // SHIPTONAME deprecated by paypal -> PAYMENTREQUEST_n_SHIPTONAME $nvpstr = $nvpstr."&".$paypalprefix."SHIPTONAME=".urlencode($shipToName); // SHIPTONAME deprecated by paypal -> PAYMENTREQUEST_n_SHIPTONAME
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET=".urlencode($shipToStreet); // $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET=".urlencode($shipToStreet); //
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET2=".urlencode($shipToStreet2); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET2=".urlencode($shipToStreet2);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCITY=".urlencode($shipToCity); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCITY=".urlencode($shipToCity);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTATE=".urlencode($shipToState); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTATE=".urlencode($shipToState);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip);
$nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum); $nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum);
if (!empty($email)) $nvpstr = $nvpstr."&".$paypalprefix."EMAIL=".urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL if (!empty($email)) $nvpstr = $nvpstr."&".$paypalprefix."EMAIL=".urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL
if (!empty($desc)) $nvpstr = $nvpstr."&".$paypalprefix."DESC=".urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC if (!empty($desc)) $nvpstr = $nvpstr."&".$paypalprefix."DESC=".urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC
if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo) if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo)
{ {
global $dolibarr_main_url_root; global $dolibarr_main_url_root;
// Define $urlwithroot // Define $urlwithroot
$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
$urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo); $urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo);
$nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo); $nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo);
} }
if (!empty($conf->global->PAYPAL_BRANDNAME)) if (!empty($conf->global->PAYPAL_BRANDNAME))
{ {
$nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME $nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME
} }
if (!empty($conf->global->PAYPAL_NOTETOBUYER)) if (!empty($conf->global->PAYPAL_NOTETOBUYER))
{ {
$nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER $nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER
} }
$_SESSION["FinalPaymentAmt"] = $paymentAmount; $_SESSION["FinalPaymentAmt"] = $paymentAmount;
$_SESSION["currencyCodeType"] = $currencyCodeType; $_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType; // 'Mark', 'Sole' $_SESSION["PaymentType"] = $paymentType; // 'Mark', 'Sole'
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip
//'--------------------------------------------------------------------------------------------------------------- //'---------------------------------------------------------------------------------------------------------------
//' Make the API call to PayPal //' Make the API call to PayPal
//' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment. //' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
//' If an error occured, show the resulting errors //' If an error occured, show the resulting errors
//'--------------------------------------------------------------------------------------------------------------- //'---------------------------------------------------------------------------------------------------------------
$resArray = hash_call("SetExpressCheckout", $nvpstr); $resArray = hash_call("SetExpressCheckout", $nvpstr);
$ack = strtoupper($resArray["ACK"]); $ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{ {
$token = urldecode($resArray["TOKEN"]); $token = urldecode($resArray["TOKEN"]);
$_SESSION['TOKEN'] = $token; $_SESSION['TOKEN'] = $token;
} }
return $resArray; return $resArray;
} }
/** /**
@ -431,39 +431,39 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType,
*/ */
function getDetails($token) function getDetails($token)
{ {
//'-------------------------------------------------------------- //'--------------------------------------------------------------
//' At this point, the buyer has completed authorizing the payment //' At this point, the buyer has completed authorizing the payment
//' at PayPal. The function will call PayPal to obtain the details //' at PayPal. The function will call PayPal to obtain the details
//' of the authorization, incuding any shipping information of the //' of the authorization, incuding any shipping information of the
//' buyer. Remember, the authorization is not a completed transaction //' buyer. Remember, the authorization is not a completed transaction
//' at this state - the buyer still needs an additional step to finalize //' at this state - the buyer still needs an additional step to finalize
//' the transaction //' the transaction
//'-------------------------------------------------------------- //'--------------------------------------------------------------
//declaring of global variables //declaring of global variables
global $conf, $langs; global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT; global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
//'--------------------------------------------------------------------------- //'---------------------------------------------------------------------------
//' Build a second API request to PayPal, using the token as the //' Build a second API request to PayPal, using the token as the
//' ID to get the details on the payment authorization //' ID to get the details on the payment authorization
//'--------------------------------------------------------------------------- //'---------------------------------------------------------------------------
$nvpstr = "&TOKEN=".$token; $nvpstr = "&TOKEN=".$token;
//'--------------------------------------------------------------------------- //'---------------------------------------------------------------------------
//' Make the API call and store the results in an array. //' Make the API call and store the results in an array.
//' If the call was a success, show the authorization details, and provide //' If the call was a success, show the authorization details, and provide
//' an action to complete the payment. //' an action to complete the payment.
//' If failed, show the error //' If failed, show the error
//'--------------------------------------------------------------------------- //'---------------------------------------------------------------------------
$resArray = hash_call("GetExpressCheckoutDetails", $nvpstr); $resArray = hash_call("GetExpressCheckoutDetails", $nvpstr);
$ack = strtoupper($resArray["ACK"]); $ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{ {
$_SESSION['payer_id'] = $resArray['PAYERID']; $_SESSION['payer_id'] = $resArray['PAYERID'];
} }
return $resArray; return $resArray;
} }
@ -481,37 +481,37 @@ function getDetails($token)
*/ */
function confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag) function confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag)
{ {
/* Gather the information to make the final call to /* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr finalize the PayPal payment. The variable nvpstr
holds the name value pairs holds the name value pairs
*/ */
//declaring of global variables //declaring of global variables
global $conf, $langs; global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT; global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
$nvpstr = ''; $nvpstr = '';
$nvpstr .= '&TOKEN='.urlencode($token); $nvpstr .= '&TOKEN='.urlencode($token);
$nvpstr .= '&PAYERID='.urlencode($payerID); $nvpstr .= '&PAYERID='.urlencode($payerID);
$nvpstr .= '&PAYMENTACTION='.urlencode($paymentType); $nvpstr .= '&PAYMENTACTION='.urlencode($paymentType);
$nvpstr .= '&AMT='.urlencode($FinalPaymentAmt); $nvpstr .= '&AMT='.urlencode($FinalPaymentAmt);
$nvpstr .= '&CURRENCYCODE='.urlencode($currencyCodeType); $nvpstr .= '&CURRENCYCODE='.urlencode($currencyCodeType);
$nvpstr .= '&IPADDRESS='.urlencode($ipaddress); $nvpstr .= '&IPADDRESS='.urlencode($ipaddress);
$nvpstr .= '&INVNUM='.urlencode($tag); $nvpstr .= '&INVNUM='.urlencode($tag);
/* Make the call to PayPal to finalize payment /* Make the call to PayPal to finalize payment
If an error occured, show the resulting errors If an error occured, show the resulting errors
*/ */
$resArray = hash_call("DoExpressCheckoutPayment", $nvpstr); $resArray = hash_call("DoExpressCheckoutPayment", $nvpstr);
/* Display the API response back to the browser. /* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters' If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php. If the response was an error, display the errors received using APIError.php.
*/ */
$ack = strtoupper($resArray["ACK"]); $ack = strtoupper($resArray["ACK"]);
return $resArray; return $resArray;
} }
/** /**
@ -575,20 +575,20 @@ function DirectPayment($paymentType, $paymentAmount, $creditCardType, $creditCar
*/ */
function hash_call($methodName, $nvpStr) function hash_call($methodName, $nvpStr)
{ {
//declaring of global variables //declaring of global variables
global $conf, $langs; global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT, $PROXY_USER, $PROXY_PASS; global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT, $PROXY_USER, $PROXY_PASS;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
// TODO problem with triggers // TODO problem with triggers
$API_version = "98.0"; $API_version = "98.0";
if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox' if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox'
{ {
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
} else { } else {
$API_Endpoint = "https://api-3t.paypal.com/nvp"; $API_Endpoint = "https://api-3t.paypal.com/nvp";
$API_Url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="; $API_Url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
} }
// Clean parameters // Clean parameters
@ -602,73 +602,73 @@ function hash_call($methodName, $nvpStr)
if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX;
// TODO END problem with triggers // TODO END problem with triggers
dol_syslog("Paypal API endpoint ".$API_Endpoint); dol_syslog("Paypal API endpoint ".$API_Endpoint);
//setting the curl parameters. //setting the curl parameters.
$ch = curl_init(); $ch = curl_init();
/*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."<br>"; /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."<br>";
print $USE_PROXY."-".$gv_ApiErrorURL."<br>"; print $USE_PROXY."-".$gv_ApiErrorURL."<br>";
print $nvpStr; print $nvpStr;
exit;*/ exit;*/
curl_setopt($ch, CURLOPT_URL, $API_Endpoint); curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_VERBOSE, 1);
// TLSv1 by default or change to TLSv1.2 in module configuration // TLSv1 by default or change to TLSv1.2 in module configuration
curl_setopt($ch, CURLOPT_SSLVERSION, (empty($conf->global->PAYPAL_SSLVERSION) ? 1 : $conf->global->PAYPAL_SSLVERSION)); curl_setopt($ch, CURLOPT_SSLVERSION, (empty($conf->global->PAYPAL_SSLVERSION) ? 1 : $conf->global->PAYPAL_SSLVERSION));
//turning off the server and peer verification(TrustManager Concept). //turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 5 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 5 : $conf->global->MAIN_USE_CONNECT_TIMEOUT);
curl_setopt($ch, CURLOPT_TIMEOUT, empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); curl_setopt($ch, CURLOPT_TIMEOUT, empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POST, 1);
//if USE_PROXY constant set to true in Constants.php, then only proxy will be enabled. //if USE_PROXY constant set to true in Constants.php, then only proxy will be enabled.
if ($USE_PROXY) if ($USE_PROXY)
{ {
dol_syslog("Paypal API hash_call set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS); dol_syslog("Paypal API hash_call set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS);
//curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10 //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10
curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT); curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
} }
//NVPRequest for submitting to server //NVPRequest for submitting to server
$nvpreq = "METHOD=".urlencode($methodName)."&VERSION=".urlencode($API_version)."&PWD=".urlencode($PAYPAL_API_PASSWORD)."&USER=".urlencode($PAYPAL_API_USER)."&SIGNATURE=".urlencode($PAYPAL_API_SIGNATURE).$nvpStr; $nvpreq = "METHOD=".urlencode($methodName)."&VERSION=".urlencode($API_version)."&PWD=".urlencode($PAYPAL_API_PASSWORD)."&USER=".urlencode($PAYPAL_API_USER)."&SIGNATURE=".urlencode($PAYPAL_API_SIGNATURE).$nvpStr;
$nvpreq .= "&LOCALECODE=".strtoupper($langs->getDefaultLang(1)); $nvpreq .= "&LOCALECODE=".strtoupper($langs->getDefaultLang(1));
//$nvpreq.="&BRANDNAME=".urlencode(); // Override merchant name //$nvpreq.="&BRANDNAME=".urlencode(); // Override merchant name
//$nvpreq.="&NOTIFYURL=".urlencode(); // For Instant Payment Notification url //$nvpreq.="&NOTIFYURL=".urlencode(); // For Instant Payment Notification url
dol_syslog("Paypal API hash_call nvpreq=".$nvpreq); dol_syslog("Paypal API hash_call nvpreq=".$nvpreq);
//setting the nvpreq as POST FIELD to curl //setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//getting response from server //getting response from server
$response = curl_exec($ch); $response = curl_exec($ch);
$nvpReqArray = deformatNVP($nvpreq); $nvpReqArray = deformatNVP($nvpreq);
$_SESSION['nvpReqArray'] = $nvpReqArray; $_SESSION['nvpReqArray'] = $nvpReqArray;
//convrting NVPResponse to an Associative Array //convrting NVPResponse to an Associative Array
dol_syslog("Paypal API hash_call Response nvpresp=".$response); dol_syslog("Paypal API hash_call Response nvpresp=".$response);
$nvpResArray = deformatNVP($response); $nvpResArray = deformatNVP($response);
if (curl_errno($ch)) { if (curl_errno($ch)) {
// moving to display page to display curl errors // moving to display page to display curl errors
$_SESSION['curl_error_no'] = curl_errno($ch); $_SESSION['curl_error_no'] = curl_errno($ch);
$_SESSION['curl_error_msg'] = curl_error($ch); $_SESSION['curl_error_msg'] = curl_error($ch);
//Execute the Error handling module to display errors. //Execute the Error handling module to display errors.
} else { } else {
//closing the curl //closing the curl
curl_close($ch); curl_close($ch);
} }
return $nvpResArray; return $nvpResArray;
} }
@ -681,24 +681,24 @@ function hash_call($methodName, $nvpStr)
*/ */
function deformatNVP($nvpstr) function deformatNVP($nvpstr)
{ {
$intial = 0; $intial = 0;
$nvpArray = array(); $nvpArray = array();
while (strlen($nvpstr)) while (strlen($nvpstr))
{ {
//postion of Key //postion of Key
$keypos = strpos($nvpstr, '='); $keypos = strpos($nvpstr, '=');
//position of value //position of value
$valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr); $valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr);
/*getting the Key and Value values and storing in a Associative Array*/ /*getting the Key and Value values and storing in a Associative Array*/
$keyval = substr($nvpstr, $intial, $keypos); $keyval = substr($nvpstr, $intial, $keypos);
$valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1); $valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1);
//decoding the respose //decoding the respose
$nvpArray[urldecode($keyval)] = urldecode($valval); $nvpArray[urldecode($keyval)] = urldecode($valval);
$nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr)); $nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
} }
return $nvpArray; return $nvpArray;
} }
/** /**

View File

@ -79,31 +79,31 @@ $htmlother = new FormOther($db);
$object = new Product($db); $object = new Product($db);
if (!$id && empty($ref)) { if (!$id && empty($ref)) {
llxHeader("", $langs->trans("ProductStatistics")); llxHeader("", $langs->trans("ProductStatistics"));
$type = GETPOST('type', 'int'); $type = GETPOST('type', 'int');
$helpurl = ''; $helpurl = '';
if ($type == '0') { if ($type == '0') {
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
//$title=$langs->trans("StatisticsOfProducts"); //$title=$langs->trans("StatisticsOfProducts");
$title = $langs->trans("Statistics"); $title = $langs->trans("Statistics");
} elseif ($type == '1') { } elseif ($type == '1') {
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
//$title=$langs->trans("StatisticsOfServices"); //$title=$langs->trans("StatisticsOfServices");
$title = $langs->trans("Statistics"); $title = $langs->trans("Statistics");
} else { } else {
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
//$title=$langs->trans("StatisticsOfProductsOrServices"); //$title=$langs->trans("StatisticsOfProductsOrServices");
$title = $langs->trans("Statistics"); $title = $langs->trans("Statistics");
} }
$picto = 'product'; $picto = 'product';
if ($type == 1) $picto = 'service'; if ($type == 1) $picto = 'service';
print load_fiche_titre($title, $mesg, $picto); print load_fiche_titre($title, $mesg, $picto);
} else { } else {
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
$title = $langs->trans('ProductServiceCard'); $title = $langs->trans('ProductServiceCard');
$helpurl = ''; $helpurl = '';
@ -176,12 +176,12 @@ if ($result || empty($id)) {
// Tag // Tag
if ($conf->categorie->enabled) { if ($conf->categorie->enabled) {
print '<tr><td class="titlefield">'.$langs->trans("Categories").'</td><td>'; print '<tr><td class="titlefield">'.$langs->trans("Categories").'</td><td>';
//$moreforfilter.='<div class="divsearchfield">'; //$moreforfilter.='<div class="divsearchfield">';
$moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1); $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1);
//$moreforfilter.='</div>'; //$moreforfilter.='</div>';
print $moreforfilter; print $moreforfilter;
print '</td></tr>'; print '</td></tr>';
} }
} }
@ -189,7 +189,7 @@ if ($result || empty($id)) {
print '<tr><td class="titlefield">'.$langs->trans("Year").'</td><td>'; print '<tr><td class="titlefield">'.$langs->trans("Year").'</td><td>';
$arrayyears = array(); $arrayyears = array();
for ($year = $currentyear - 10; $year < $currentyear + 10; $year++) { for ($year = $currentyear - 10; $year < $currentyear + 10; $year++) {
$arrayyears[$year] = $year; $arrayyears[$year] = $year;
} }
if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year;
if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear;
@ -299,16 +299,16 @@ if ($result || empty($id)) {
if (dol_is_file($dir.'/'.$graphfiles[$key]['file'])) { if (dol_is_file($dir.'/'.$graphfiles[$key]['file'])) {
// TODO Load cachefile $graphfiles[$key]['file'] // TODO Load cachefile $graphfiles[$key]['file']
} else { } else {
$morefilters = ''; $morefilters = '';
if ($search_categ > 0) { if ($search_categ > 0) {
$categ = new Categorie($db); $categ = new Categorie($db);
$categ->fetch($search_categ); $categ->fetch($search_categ);
$listofprodids = $categ->getObjectsInCateg('product', 1); $listofprodids = $categ->getObjectsInCateg('product', 1);
$morefilters = ' AND d.fk_product IN ('.((is_array($listofprodids) && count($listofprodids)) ? join(',', $listofprodids) : '0').')'; $morefilters = ' AND d.fk_product IN ('.((is_array($listofprodids) && count($listofprodids)) ? join(',', $listofprodids) : '0').')';
} }
if ($search_categ == -2) { if ($search_categ == -2) {
$morefilters = ' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)'; $morefilters = ' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)';
} }
if ($key == 'propal') $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); if ($key == 'propal') $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
if ($key == 'orders') $graph_data = $object->get_nb_order($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); if ($key == 'orders') $graph_data = $object->get_nb_order($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
@ -371,10 +371,10 @@ if ($result || empty($id)) {
// Date generation // Date generation
if ($graphfiles[$key]['output'] && !$px->isGraphKo()) { if ($graphfiles[$key]['output'] && !$px->isGraphKo()) {
if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated = $langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour")); if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated = $langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour"));
else $dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour")); else $dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour"));
} else { } else {
$dategenerated = ($mesg ? '<font class="error">'.$mesg.'</font>' : $langs->trans("ChartNotGenerated")); $dategenerated = ($mesg ? '<font class="error">'.$mesg.'</font>' : $langs->trans("ChartNotGenerated"));
} }
$linktoregenerate = '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).((string) $type != '' ? '&type='.$type : '').'&action=recalcul&mode='.$mode.'&search_year='.$search_year.'&search_categ='.$search_categ.'">'.img_picto($langs->trans("ReCalculate").' ('.$dategenerated.')', 'refresh').'</a>'; $linktoregenerate = '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).((string) $type != '' ? '&type='.$type : '').'&action=recalcul&mode='.$mode.'&search_year='.$search_year.'&search_categ='.$search_categ.'">'.img_picto($langs->trans("ReCalculate").' ('.$dategenerated.')', 'refresh').'</a>';

View File

@ -41,14 +41,14 @@ class MouvementStock extends CommonObject
public $table_element = 'stock_mouvement'; public $table_element = 'stock_mouvement';
/** /**
* @var int ID product * @var int ID product
*/ */
public $product_id; public $product_id;
/** /**
* @var int ID warehouse * @var int ID warehouse
*/ */
public $warehouse_id; public $warehouse_id;
public $qty; public $qty;
@ -65,18 +65,18 @@ class MouvementStock extends CommonObject
public $price; public $price;
/** /**
* @var int ID user author * @var int ID user author
*/ */
public $fk_user_author; public $fk_user_author;
/** /**
* @var string stock movements label * @var string stock movements label
*/ */
public $label; public $label;
/** /**
* @var int ID * @var int ID
*/ */
public $fk_origin; public $fk_origin;
public $origintype; public $origintype;
@ -113,11 +113,11 @@ class MouvementStock extends CommonObject
/** /**
* Constructor * Constructor
* *
* @param DoliDB $db Database handler * @param DoliDB $db Database handler
*/ */
public function __construct($db) public function __construct($db)
{ {
$this->db = $db; $this->db = $db;
@ -147,10 +147,10 @@ class MouvementStock extends CommonObject
* @param int $id_product_batch Id product_batch (when skip_batch is false and we already know which record of product_batch to use) * @param int $id_product_batch Id product_batch (when skip_batch is false and we already know which record of product_batch to use)
* @return int <0 if KO, 0 if fk_product is null or product id does not exists, >0 if OK * @return int <0 if KO, 0 if fk_product is null or product id does not exists, >0 if OK
*/ */
public function _create($user, $fk_product, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $skip_batch = false, $id_product_batch = 0) public function _create($user, $fk_product, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $skip_batch = false, $id_product_batch = 0)
{ {
// phpcs:disable // phpcs:disable
global $conf, $langs; global $conf, $langs;
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
@ -227,114 +227,114 @@ class MouvementStock extends CommonObject
// If not found, we add record // If not found, we add record
$sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".MAIN_DB_PREFIX."product_lot as pb"; $sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".MAIN_DB_PREFIX."product_lot as pb";
$sql .= " WHERE pb.fk_product = ".$fk_product." AND pb.batch = '".$this->db->escape($batch)."'"; $sql .= " WHERE pb.fk_product = ".$fk_product." AND pb.batch = '".$this->db->escape($batch)."'";
dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG); dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql)
{
$num = $this->db->num_rows($resql);
$i = 0;
if ($num > 0)
{
while ($i < $num)
{
$obj = $this->db->fetch_object($resql);
if ($obj->eatby)
{
if ($eatby)
{
$tmparray = dol_getdate($eatby, true);
$eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) // We test date without hours and with hours for backward compatibility
{
// If found and eatby/sellby defined into table and provided and differs, return error
$langs->load("stocks");
$this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatbywithouthour, 'dayhour'));
dol_syslog("ThisSerialAlreadyExistWithDifferentDate batch=".$batch.", eatby found into product_lot = ".$obj->eatby." = ".dol_print_date($this->db->jdate($obj->eatby), 'dayhourrfc')." so eatbywithouthour = ".$eatbywithouthour." = ".dol_print_date($eatbywithouthour)." - eatby provided = ".$eatby." = ".dol_print_date($eatby, 'dayhourrfc'), LOG_ERR);
$this->db->rollback();
return -3;
}
} else {
$eatby = $obj->eatby; // If found and eatby/sellby defined into table and not provided, we take value from table
}
} else {
if ($eatby) // If found and eatby/sellby not defined into table and provided, we update table
{
$productlot = new Productlot($this->db);
$result = $productlot->fetch($obj->rowid);
$productlot->eatby = $eatby;
$result = $productlot->update($user);
if ($result <= 0)
{
$this->error = $productlot->error;
$this->errors = $productlot->errors;
$this->db->rollback();
return -5;
}
}
}
if ($obj->sellby)
{
if ($sellby)
{
$tmparray = dol_getdate($sellby, true);
$sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) // We test date without hours and with hours for backward compatibility
{
// If found and eatby/sellby defined into table and provided and differs, return error
$this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby));
dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR);
$this->db->rollback();
return -3;
}
} else {
$sellby = $obj->sellby; // If found and eatby/sellby defined into table and not provided, we take value from table
}
}
else
{
if ($sellby) // If found and eatby/sellby not defined into table and provided, we update table
{
$productlot = new Productlot($this->db);
$result = $productlot->fetch($obj->rowid);
$productlot->sellby = $sellby;
$result = $productlot->update($user);
if ($result <= 0)
{
$this->error = $productlot->error;
$this->errors = $productlot->errors;
$this->db->rollback();
return -5;
}
}
}
$i++;
}
}
else // If not found, we add record
{
$productlot = new Productlot($this->db);
$productlot->entity = $conf->entity;
$productlot->fk_product = $fk_product;
$productlot->batch = $batch;
// If we are here = first time we manage this batch, so we used dates provided by users to create lot
$productlot->eatby = $eatby;
$productlot->sellby = $sellby;
$result = $productlot->create($user);
if ($result <= 0)
{
$this->error = $productlot->error;
$this->errors = $productlot->errors;
$this->db->rollback();
return -4;
}
}
}
else
{ {
dol_print_error($this->db); $num = $this->db->num_rows($resql);
$this->db->rollback(); $i = 0;
return -1; if ($num > 0)
{
while ($i < $num)
{
$obj = $this->db->fetch_object($resql);
if ($obj->eatby)
{
if ($eatby)
{
$tmparray = dol_getdate($eatby, true);
$eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) // We test date without hours and with hours for backward compatibility
{
// If found and eatby/sellby defined into table and provided and differs, return error
$langs->load("stocks");
$this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatbywithouthour, 'dayhour'));
dol_syslog("ThisSerialAlreadyExistWithDifferentDate batch=".$batch.", eatby found into product_lot = ".$obj->eatby." = ".dol_print_date($this->db->jdate($obj->eatby), 'dayhourrfc')." so eatbywithouthour = ".$eatbywithouthour." = ".dol_print_date($eatbywithouthour)." - eatby provided = ".$eatby." = ".dol_print_date($eatby, 'dayhourrfc'), LOG_ERR);
$this->db->rollback();
return -3;
}
} else {
$eatby = $obj->eatby; // If found and eatby/sellby defined into table and not provided, we take value from table
}
} else {
if ($eatby) // If found and eatby/sellby not defined into table and provided, we update table
{
$productlot = new Productlot($this->db);
$result = $productlot->fetch($obj->rowid);
$productlot->eatby = $eatby;
$result = $productlot->update($user);
if ($result <= 0)
{
$this->error = $productlot->error;
$this->errors = $productlot->errors;
$this->db->rollback();
return -5;
}
}
}
if ($obj->sellby)
{
if ($sellby)
{
$tmparray = dol_getdate($sellby, true);
$sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) // We test date without hours and with hours for backward compatibility
{
// If found and eatby/sellby defined into table and provided and differs, return error
$this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby));
dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR);
$this->db->rollback();
return -3;
}
} else {
$sellby = $obj->sellby; // If found and eatby/sellby defined into table and not provided, we take value from table
}
}
else
{
if ($sellby) // If found and eatby/sellby not defined into table and provided, we update table
{
$productlot = new Productlot($this->db);
$result = $productlot->fetch($obj->rowid);
$productlot->sellby = $sellby;
$result = $productlot->update($user);
if ($result <= 0)
{
$this->error = $productlot->error;
$this->errors = $productlot->errors;
$this->db->rollback();
return -5;
}
}
}
$i++;
}
}
else // If not found, we add record
{
$productlot = new Productlot($this->db);
$productlot->entity = $conf->entity;
$productlot->fk_product = $fk_product;
$productlot->batch = $batch;
// If we are here = first time we manage this batch, so we used dates provided by users to create lot
$productlot->eatby = $eatby;
$productlot->sellby = $sellby;
$result = $productlot->create($user);
if ($result <= 0)
{
$this->error = $productlot->error;
$this->errors = $productlot->errors;
$this->db->rollback();
return -4;
}
}
}
else
{
dol_print_error($this->db);
$this->db->rollback();
return -1;
} }
} }
@ -346,41 +346,41 @@ class MouvementStock extends CommonObject
// Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2. // Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2.
if ($movestock && $qty < 0 && empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER)) if ($movestock && $qty < 0 && empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER))
{ {
if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch)
{ {
$foundforbatch = 0; $foundforbatch = 0;
$qtyisnotenough = 0; $qtyisnotenough = 0;
foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch)
{ {
if ($batch != $batchcursor) continue; if ($batch != $batchcursor) continue;
$foundforbatch = 1; $foundforbatch = 1;
if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty; if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty;
break; break;
} }
if (!$foundforbatch || $qtyisnotenough) if (!$foundforbatch || $qtyisnotenough)
{ {
$langs->load("stocks"); $langs->load("stocks");
include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$tmpwarehouse = new Entrepot($this->db); $tmpwarehouse = new Entrepot($this->db);
$tmpwarehouse->fetch($entrepot_id); $tmpwarehouse->fetch($entrepot_id);
$this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref); $this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
$this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref); $this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
$this->db->rollback(); $this->db->rollback();
return -8; return -8;
} }
} }
else else
{ {
if (empty($product->stock_warehouse[$entrepot_id]->real) || $product->stock_warehouse[$entrepot_id]->real < abs($qty)) if (empty($product->stock_warehouse[$entrepot_id]->real) || $product->stock_warehouse[$entrepot_id]->real < abs($qty))
{ {
$langs->load("stocks"); $langs->load("stocks");
$this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref; $this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
$this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref; $this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
$this->db->rollback(); $this->db->rollback();
return -8; return -8;
} }
} }
} }
if ($movestock && $entrepot_id > 0) // Change stock for current product, change for subproduct is done after if ($movestock && $entrepot_id > 0) // Change stock for current product, change for subproduct is done after
@ -533,10 +533,10 @@ class MouvementStock extends CommonObject
{ {
if ($id_product_batch > 0) if ($id_product_batch > 0)
{ {
$result = $this->createBatch($id_product_batch, $qty); $result = $this->createBatch($id_product_batch, $qty);
} else { } else {
$param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch); $param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch);
$result = $this->createBatch($param_batch, $qty); $result = $this->createBatch($param_batch, $qty);
} }
if ($result < 0) $error++; if ($result < 0) $error++;
} }
@ -548,7 +548,7 @@ class MouvementStock extends CommonObject
// $sql = "UPDATE ".MAIN_DB_PREFIX."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty; // $sql = "UPDATE ".MAIN_DB_PREFIX."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty;
// $sql.= " WHERE rowid = ".$fk_product; // $sql.= " WHERE rowid = ".$fk_product;
// Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql // Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
$sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$newpmp.","; $sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$newpmp.",";
$sql .= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; $sql .= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)";
$sql .= " WHERE rowid = ".$fk_product; $sql .= " WHERE rowid = ".$fk_product;
@ -562,11 +562,11 @@ class MouvementStock extends CommonObject
} }
} }
// If stock is now 0, we can remove entry into llx_product_stock, but only if there is no child lines into llx_product_batch (detail of batch, because we can imagine // If stock is now 0, we can remove entry into llx_product_stock, but only if there is no child lines into llx_product_batch (detail of batch, because we can imagine
// having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot. // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".MAIN_DB_PREFIX."product_batch as pb)"; $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".MAIN_DB_PREFIX."product_batch as pb)";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
// We do not test error, it can fails if there is child in batch details // We do not test error, it can fails if there is child in batch details
} }
// Add movement for sub products (recursive call) // Add movement for sub products (recursive call)
@ -577,10 +577,10 @@ class MouvementStock extends CommonObject
if ($movestock && !$error) if ($movestock && !$error)
{ {
// Call trigger // Call trigger
$result = $this->call_trigger('STOCK_MOVEMENT', $user); $result = $this->call_trigger('STOCK_MOVEMENT', $user);
if ($result < 0) $error++; if ($result < 0) $error++;
// End call triggers // End call triggers
} }
if (!$error) if (!$error)
@ -607,80 +607,80 @@ class MouvementStock extends CommonObject
*/ */
public function fetch($id) public function fetch($id)
{ {
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$sql = 'SELECT'; $sql = 'SELECT';
$sql .= ' t.rowid,'; $sql .= ' t.rowid,';
$sql .= " t.tms,"; $sql .= " t.tms,";
$sql .= " t.datem,"; $sql .= " t.datem,";
$sql .= " t.fk_product,"; $sql .= " t.fk_product,";
$sql .= " t.fk_entrepot,"; $sql .= " t.fk_entrepot,";
$sql .= " t.value,"; $sql .= " t.value,";
$sql .= " t.price,"; $sql .= " t.price,";
$sql .= " t.type_mouvement,"; $sql .= " t.type_mouvement,";
$sql .= " t.fk_user_author,"; $sql .= " t.fk_user_author,";
$sql .= " t.label,"; $sql .= " t.label,";
$sql .= " t.fk_origin,"; $sql .= " t.fk_origin,";
$sql .= " t.origintype,"; $sql .= " t.origintype,";
$sql .= " t.inventorycode,"; $sql .= " t.inventorycode,";
$sql .= " t.batch,"; $sql .= " t.batch,";
$sql .= " t.eatby,"; $sql .= " t.eatby,";
$sql .= " t.sellby,"; $sql .= " t.sellby,";
$sql .= " t.fk_projet as fk_project"; $sql .= " t.fk_projet as fk_project";
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE 1 = 1'; $sql .= ' WHERE 1 = 1';
//if (null !== $ref) { //if (null !== $ref) {
//$sql .= ' AND t.ref = ' . '\'' . $ref . '\''; //$sql .= ' AND t.ref = ' . '\'' . $ref . '\'';
//} else { //} else {
$sql .= ' AND t.rowid = '.$id; $sql .= ' AND t.rowid = '.$id;
//} //}
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$numrows = $this->db->num_rows($resql); $numrows = $this->db->num_rows($resql);
if ($numrows) { if ($numrows) {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
$this->product_id = $obj->fk_product; $this->product_id = $obj->fk_product;
$this->warehouse_id = $obj->fk_entrepot; $this->warehouse_id = $obj->fk_entrepot;
$this->qty = $obj->value; $this->qty = $obj->value;
$this->type = $obj->type_mouvement; $this->type = $obj->type_mouvement;
$this->tms = $this->db->jdate($obj->tms); $this->tms = $this->db->jdate($obj->tms);
$this->datem = $this->db->jdate($obj->datem); $this->datem = $this->db->jdate($obj->datem);
$this->price = $obj->price; $this->price = $obj->price;
$this->fk_user_author = $obj->fk_user_author; $this->fk_user_author = $obj->fk_user_author;
$this->label = $obj->label; $this->label = $obj->label;
$this->fk_origin = $obj->fk_origin; $this->fk_origin = $obj->fk_origin;
$this->origintype = $obj->origintype; $this->origintype = $obj->origintype;
$this->inventorycode = $obj->inventorycode; $this->inventorycode = $obj->inventorycode;
$this->batch = $obj->batch; $this->batch = $obj->batch;
$this->eatby = $this->db->jdate($obj->eatby); $this->eatby = $this->db->jdate($obj->eatby);
$this->sellby = $this->db->jdate($obj->sellby); $this->sellby = $this->db->jdate($obj->sellby);
$this->fk_project = $obj->fk_project; $this->fk_project = $obj->fk_project;
} }
// Retrieve all extrafield // Retrieve all extrafield
// fetch optionals attributes and labels // fetch optionals attributes and labels
$this->fetch_optionals(); $this->fetch_optionals();
// $this->fetch_lines(); // $this->fetch_lines();
$this->db->free($resql); $this->db->free($resql);
if ($numrows) { if ($numrows) {
return 1; return 1;
} else { } else {
return 0; return 0;
} }
} else { } else {
$this->errors[] = 'Error '.$this->db->lasterror(); $this->errors[] = 'Error '.$this->db->lasterror();
dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR); dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
return -1; return -1;
} }
} }
@ -774,7 +774,7 @@ class MouvementStock extends CommonObject
*/ */
public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '') public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '')
{ {
global $conf; global $conf;
$skip_batch = empty($conf->productbatch->enabled); $skip_batch = empty($conf->productbatch->enabled);
@ -800,11 +800,11 @@ class MouvementStock extends CommonObject
*/ */
public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode = '') public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode = '')
{ {
global $conf; global $conf;
$skip_batch = empty($conf->productbatch->enabled); $skip_batch = empty($conf->productbatch->enabled);
return $this->_create($user, $fk_product, $entrepot_id, $qty, 3, $price, $label, $inventorycode, $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch); return $this->_create($user, $fk_product, $entrepot_id, $qty, 3, $price, $label, $inventorycode, $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch);
} }
@ -869,7 +869,7 @@ class MouvementStock extends CommonObject
*/ */
private function createBatch($dluo, $qty) private function createBatch($dluo, $qty)
{ {
global $user; global $user;
$pdluo = new Productbatch($this->db); $pdluo = new Productbatch($this->db);
@ -932,7 +932,7 @@ class MouvementStock extends CommonObject
return $result; return $result;
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/** /**
* Return Url link of origin object * Return Url link of origin object
* *
@ -942,8 +942,8 @@ class MouvementStock extends CommonObject
*/ */
public function get_origin($fk_origin, $origintype) public function get_origin($fk_origin, $origintype)
{ {
// phpcs:enable // phpcs:enable
$origin = ''; $origin = '';
switch ($origintype) { switch ($origintype) {
case 'commande': case 'commande':
@ -982,10 +982,10 @@ class MouvementStock extends CommonObject
default: default:
if ($origintype) if ($origintype)
{ {
// Separate originetype with "@" : left part is class name, right part is module name // Separate originetype with "@" : left part is class name, right part is module name
$origintype_array = explode('@', $origintype); $origintype_array = explode('@', $origintype);
$classname = ucfirst($origintype_array[0]); $classname = ucfirst($origintype_array[0]);
$modulename = empty($origintype_array[1]) ? $classname : $origintype_array[1]; $modulename = empty($origintype_array[1]) ? $classname : $origintype_array[1];
$result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php'); $result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php');
if ($result) if ($result)
{ {
@ -1034,21 +1034,21 @@ class MouvementStock extends CommonObject
/** /**
* Initialise an instance with random values. * Initialise an instance with random values.
* Used to build previews or test instances. * Used to build previews or test instances.
* id must be 0 if object instance is a specimen. * id must be 0 if object instance is a specimen.
* *
* @return void * @return void
*/ */
public function initAsSpecimen() public function initAsSpecimen()
{ {
global $user, $langs, $conf, $mysoc; global $user, $langs, $conf, $mysoc;
// Initialize parameters // Initialize parameters
$this->id = 0; $this->id = 0;
// There is no specific properties. All data into insert are provided as method parameter. // There is no specific properties. All data into insert are provided as method parameter.
} }
/** /**
* Return a link (with optionaly the picto) * Return a link (with optionaly the picto)
@ -1099,7 +1099,7 @@ class MouvementStock extends CommonObject
return $this->LibStatut($mode); return $this->LibStatut($mode);
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/** /**
* Renvoi le libelle d'un status donne * Renvoi le libelle d'un status donne
* *
@ -1108,7 +1108,7 @@ class MouvementStock extends CommonObject
*/ */
public function LibStatut($mode = 0) public function LibStatut($mode = 0)
{ {
// phpcs:enable // phpcs:enable
global $langs; global $langs;
if ($mode == 0 || $mode == 1) { if ($mode == 0 || $mode == 1) {

View File

@ -70,8 +70,8 @@ $langs->loadLangs(array("main", "members", "companies", "install", "other"));
if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1); if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1);
if (empty($conf->global->MEMBER_ENABLE_PUBLIC)) { if (empty($conf->global->MEMBER_ENABLE_PUBLIC)) {
print $langs->trans("Auto subscription form for public visitors has not been enabled"); print $langs->trans("Auto subscription form for public visitors has not been enabled");
exit; exit;
} }
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -97,39 +97,39 @@ $user->loadDefaultValues();
*/ */
function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '') function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '')
{ {
global $user, $conf, $langs, $mysoc; global $user, $conf, $langs, $mysoc;
top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers
print '<body id="mainbody" class="publicnewmemberform">'; print '<body id="mainbody" class="publicnewmemberform">';
// Define urllogo // Define urllogo
$urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png'; $urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png';
if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) {
$urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small); $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small);
} elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) { } elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) {
$urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo); $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo);
} elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) { } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) {
$urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg'; $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg';
} }
print '<div class="center">'; print '<div class="center">';
// Output html code for logo // Output html code for logo
if ($urllogo) { if ($urllogo) {
print '<div class="backgreypublicpayment">'; print '<div class="backgreypublicpayment">';
print '<div class="logopublicpayment">'; print '<div class="logopublicpayment">';
print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
print '>'; print '>';
print '</div>'; print '</div>';
if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { if (empty($conf->global->MAIN_HIDE_POWERED_BY)) {
print '<div class="poweredbypublicpayment opacitymedium right"><a href="https://www.dolibarr.org" target="dolibarr">'.$langs->trans("PoweredBy").'<br><img src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>'; print '<div class="poweredbypublicpayment opacitymedium right"><a href="https://www.dolibarr.org" target="dolibarr">'.$langs->trans("PoweredBy").'<br><img src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>';
} }
print '</div>'; print '</div>';
} }
print '</div>'; print '</div>';
print '<div class="divmainbodylarge">'; print '<div class="divmainbodylarge">';
} }
/** /**
@ -139,12 +139,12 @@ function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $
*/ */
function llxFooterVierge() function llxFooterVierge()
{ {
print '</div>'; print '</div>';
printCommonFooter('public'); printCommonFooter('public');
print "</body>\n"; print "</body>\n";
print "</html>\n"; print "</html>\n";
} }
@ -156,7 +156,7 @@ $parameters = array();
// Note that $action and $object may have been modified by some hooks // Note that $action and $object may have been modified by some hooks
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
if ($reshook < 0) { if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
} }
// Action called when page is submitted // Action called when page is submitted
@ -166,164 +166,164 @@ if (empty($reshook) && $action == 'add') {
$db->begin(); $db->begin();
// test if login already exists // test if login already exists
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
if (!GETPOST('login')) { if (!GETPOST('login')) {
$error++; $error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"))."<br>\n"; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"))."<br>\n";
} }
$sql = "SELECT login FROM ".MAIN_DB_PREFIX."adherent WHERE login='".$db->escape(GETPOST('login'))."'"; $sql = "SELECT login FROM ".MAIN_DB_PREFIX."adherent WHERE login='".$db->escape(GETPOST('login'))."'";
$result = $db->query($sql); $result = $db->query($sql);
if ($result) { if ($result) {
$num = $db->num_rows($result); $num = $db->num_rows($result);
} }
if ($num != 0) { if ($num != 0) {
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
$errmsg .= $langs->trans("ErrorLoginAlreadyExists")."<br>\n"; $errmsg .= $langs->trans("ErrorLoginAlreadyExists")."<br>\n";
} }
if (!isset($_POST["pass1"]) || !isset($_POST["pass2"]) || $_POST["pass1"] == '' || $_POST["pass2"] == '' || $_POST["pass1"] != $_POST["pass2"]) { if (!isset($_POST["pass1"]) || !isset($_POST["pass2"]) || $_POST["pass1"] == '' || $_POST["pass2"] == '' || $_POST["pass1"] != $_POST["pass2"]) {
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
$errmsg .= $langs->trans("ErrorPasswordsMustMatch")."<br>\n"; $errmsg .= $langs->trans("ErrorPasswordsMustMatch")."<br>\n";
} }
if (!GETPOST("email")) { if (!GETPOST("email")) {
$error++; $error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."<br>\n"; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."<br>\n";
} }
} }
if (GETPOST('type') <= 0) { if (GETPOST('type') <= 0) {
$error++; $error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."<br>\n"; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."<br>\n";
} }
if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) { if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) {
$error++; $error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."<br>\n"; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."<br>\n";
} }
if (empty($_POST["lastname"])) { if (empty($_POST["lastname"])) {
$error++; $error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."<br>\n"; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."<br>\n";
} }
if (empty($_POST["firstname"])) { if (empty($_POST["firstname"])) {
$error++; $error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."<br>\n"; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."<br>\n";
} }
if (GETPOST("email") && !isValidEmail(GETPOST("email"))) { if (GETPOST("email") && !isValidEmail(GETPOST("email"))) {
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
$errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."<br>\n"; $errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."<br>\n";
} }
$birthday = dol_mktime($_POST["birthhour"], $_POST["birthmin"], $_POST["birthsec"], $_POST["birthmonth"], $_POST["birthday"], $_POST["birthyear"]); $birthday = dol_mktime($_POST["birthhour"], $_POST["birthmin"], $_POST["birthsec"], $_POST["birthmonth"], $_POST["birthday"], $_POST["birthyear"]);
if ($_POST["birthmonth"] && empty($birthday)) { if ($_POST["birthmonth"] && empty($birthday)) {
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
$errmsg .= $langs->trans("ErrorBadDateFormat")."<br>\n"; $errmsg .= $langs->trans("ErrorBadDateFormat")."<br>\n";
} }
if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) { if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) {
if (GETPOST("morphy") == 'mor' && GETPOST('budget') <= 0) { if (GETPOST("morphy") == 'mor' && GETPOST('budget') <= 0) {
$error++; $error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TurnoverOrBudget"))."<br>\n"; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TurnoverOrBudget"))."<br>\n";
} }
} }
if (isset($public)) $public = 1; if (isset($public)) $public = 1;
else $public = 0; else $public = 0;
if (!$error) { if (!$error) {
// email a peu pres correct et le login n'existe pas // email a peu pres correct et le login n'existe pas
$adh = new Adherent($db); $adh = new Adherent($db);
$adh->statut = -1; $adh->statut = -1;
$adh->public = $public; $adh->public = $public;
$adh->firstname = $_POST["firstname"]; $adh->firstname = $_POST["firstname"];
$adh->lastname = $_POST["lastname"]; $adh->lastname = $_POST["lastname"];
$adh->gender = $_POST["gender"]; $adh->gender = $_POST["gender"];
$adh->civility_id = $_POST["civility_id"]; $adh->civility_id = $_POST["civility_id"];
$adh->societe = $_POST["societe"]; $adh->societe = $_POST["societe"];
$adh->address = $_POST["address"]; $adh->address = $_POST["address"];
$adh->zip = $_POST["zipcode"]; $adh->zip = $_POST["zipcode"];
$adh->town = $_POST["town"]; $adh->town = $_POST["town"];
$adh->email = $_POST["email"]; $adh->email = $_POST["email"];
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
$adh->login = $_POST["login"]; $adh->login = $_POST["login"];
$adh->pass = $_POST["pass1"]; $adh->pass = $_POST["pass1"];
} }
$adh->photo = $_POST["photo"]; $adh->photo = $_POST["photo"];
$adh->country_id = $_POST["country_id"]; $adh->country_id = $_POST["country_id"];
$adh->state_id = $_POST["state_id"]; $adh->state_id = $_POST["state_id"];
$adh->typeid = $_POST["type"]; $adh->typeid = $_POST["type"];
$adh->note_private = $_POST["note_private"]; $adh->note_private = $_POST["note_private"];
$adh->morphy = $_POST["morphy"]; $adh->morphy = $_POST["morphy"];
$adh->birth = $birthday; $adh->birth = $birthday;
// Fill array 'array_options' with data from add form // Fill array 'array_options' with data from add form
$extrafields->fetch_name_optionals_label($adh->table_element); $extrafields->fetch_name_optionals_label($adh->table_element);
$ret = $extrafields->setOptionalsFromPost(null, $adh); $ret = $extrafields->setOptionalsFromPost(null, $adh);
if ($ret < 0) $error++; if ($ret < 0) $error++;
$result = $adh->create($user); $result = $adh->create($user);
if ($result > 0) { if ($result > 0) {
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
$object = $adh; $object = $adh;
$adht = new AdherentType($db); $adht = new AdherentType($db);
$adht->fetch($object->typeid); $adht->fetch($object->typeid);
if ($object->email) { if ($object->email) {
$subject = ''; $subject = '';
$msg = ''; $msg = '';
// Send subscription email // Send subscription email
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db); $formmail = new FormMail($db);
// Set output language // Set output language
$outputlangs = new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang); $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
// Load traductions files required by page // Load traductions files required by page
$outputlangs->loadLangs(array("main", "members")); $outputlangs->loadLangs(array("main", "members"));
// Get email content from template // Get email content from template
$arraydefaultmessage = null; $arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_AUTOREGISTER; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_AUTOREGISTER;
if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic; $subject = $arraydefaultmessage->topic;
$msg = $arraydefaultmessage->content; $msg = $arraydefaultmessage->content;
} }
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
complete_substitutions_array($substitutionarray, $outputlangs, $object); complete_substitutions_array($substitutionarray, $outputlangs, $object);
$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs); $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnValid()), $substitutionarray, $outputlangs); $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnValid()), $substitutionarray, $outputlangs);
if ($subjecttosend && $texttosend) { if ($subjecttosend && $texttosend) {
$moreinheader = 'X-Dolibarr-Info: send_an_email by public/members/new.php'."\r\n"; $moreinheader = 'X-Dolibarr-Info: send_an_email by public/members/new.php'."\r\n";
$result = $object->send_an_email($texttosend, $subjecttosend, array(), array(), array(), "", "", 0, -1, '', $moreinheader); $result = $object->send_an_email($texttosend, $subjecttosend, array(), array(), array(), "", "", 0, -1, '', $moreinheader);
} }
/*if ($result < 0) { /*if ($result < 0) {
$error++; $error++;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
}*/ }*/
} }
// Send email to the foundation to say a new member subscribed with autosubscribe form // Send email to the foundation to say a new member subscribed with autosubscribe form
if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL) && !empty($conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL_SUBJECT) && if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL) && !empty($conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL_SUBJECT) &&
!empty($conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL)) { !empty($conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL)) {
// Define link to login card // Define link to login card
$appli = constant('DOL_APPLICATION_TITLE'); $appli = constant('DOL_APPLICATION_TITLE');
if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
$appli = $conf->global->MAIN_APPLICATION_TITLE; $appli = $conf->global->MAIN_APPLICATION_TITLE;
if (preg_match('/\d\.\d/', $appli)) { if (preg_match('/\d\.\d/', $appli)) {
if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
} else $appli .= " ".DOL_VERSION; } else $appli .= " ".DOL_VERSION;
} else { } else {
$appli .= " ".DOL_VERSION; $appli .= " ".DOL_VERSION;
} }
$to = $adh->makeSubstitution($conf->global->MAIN_INFO_SOCIETE_MAIL); $to = $adh->makeSubstitution($conf->global->MAIN_INFO_SOCIETE_MAIL);
$from = $conf->global->ADHERENT_MAIL_FROM; $from = $conf->global->ADHERENT_MAIL_FROM;
$mailfile = new CMailFile( $mailfile = new CMailFile(
'['.$appli.'] '.$conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL_SUBJECT, '['.$appli.'] '.$conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL_SUBJECT,
$to, $to,
@ -338,103 +338,103 @@ if (empty($reshook) && $action == 'add') {
-1 -1
); );
if (!$mailfile->sendfile()) { if (!$mailfile->sendfile()) {
dol_syslog($langs->trans("ErrorFailedToSendMail", $from, $to), LOG_ERR); dol_syslog($langs->trans("ErrorFailedToSendMail", $from, $to), LOG_ERR);
} }
} }
if (!empty($backtopage)) { if (!empty($backtopage)) {
$urlback = $backtopage; $urlback = $backtopage;
} elseif (!empty($conf->global->MEMBER_URL_REDIRECT_SUBSCRIPTION)) { } elseif (!empty($conf->global->MEMBER_URL_REDIRECT_SUBSCRIPTION)) {
$urlback = $conf->global->MEMBER_URL_REDIRECT_SUBSCRIPTION; $urlback = $conf->global->MEMBER_URL_REDIRECT_SUBSCRIPTION;
// TODO Make replacement of __AMOUNT__, etc... // TODO Make replacement of __AMOUNT__, etc...
} else { } else {
$urlback = $_SERVER["PHP_SELF"]."?action=added"; $urlback = $_SERVER["PHP_SELF"]."?action=added";
} }
if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) && $conf->global->MEMBER_NEWFORM_PAYONLINE != '-1') { if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) && $conf->global->MEMBER_NEWFORM_PAYONLINE != '-1') {
if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'all') { if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'all') {
$urlback = DOL_MAIN_URL_ROOT.'/public/payment/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); $urlback = DOL_MAIN_URL_ROOT.'/public/payment/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref);
if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha'));
if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else { } else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN); $urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
} }
} }
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paybox') { } elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paybox') {
$urlback = DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); $urlback = DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref);
if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha'));
if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else { } else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN); $urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
} }
} }
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paypal') { } elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paypal') {
$urlback = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); $urlback = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref);
if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha'));
if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else { } else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN); $urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
} }
} }
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'stripe') { } elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'stripe') {
$urlback = DOL_MAIN_URL_ROOT.'/public/stripe/newpayment.php?from=membernewform&source=membersubscription&ref='.$adh->ref; $urlback = DOL_MAIN_URL_ROOT.'/public/stripe/newpayment.php?from=membernewform&source=membersubscription&ref='.$adh->ref;
if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha'));
if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else { } else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN); $urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
} }
} }
} else { } else {
dol_print_error('', "Autosubscribe form is setup to ask an online payment for a not managed online payment"); dol_print_error('', "Autosubscribe form is setup to ask an online payment for a not managed online payment");
exit; exit;
} }
} }
if (!empty($entity)) $urlback .= '&entity='.$entity; if (!empty($entity)) $urlback .= '&entity='.$entity;
dol_syslog("member ".$adh->ref." was created, we redirect to ".$urlback); dol_syslog("member ".$adh->ref." was created, we redirect to ".$urlback);
} else { } else {
$error++; $error++;
$errmsg .= join('<br>', $adh->errors); $errmsg .= join('<br>', $adh->errors);
} }
} }
if (!$error) { if (!$error) {
$db->commit(); $db->commit();
Header("Location: ".$urlback); Header("Location: ".$urlback);
exit; exit;
} else { } else {
$db->rollback(); $db->rollback();
} }
} }
// Action called after a submitted was send and member created successfully // Action called after a submitted was send and member created successfully
// If MEMBER_URL_REDIRECT_SUBSCRIPTION is set to url we never go here because a redirect was done to this url. // If MEMBER_URL_REDIRECT_SUBSCRIPTION is set to url we never go here because a redirect was done to this url.
// backtopage parameter with an url was set on member submit page, we never go here because a redirect was done to this url. // backtopage parameter with an url was set on member submit page, we never go here because a redirect was done to this url.
if (empty($reshook) && $action == 'added') { if (empty($reshook) && $action == 'added') {
llxHeaderVierge($langs->trans("NewMemberForm")); llxHeaderVierge($langs->trans("NewMemberForm"));
// Si on a pas ete redirige // Si on a pas ete redirige
print '<br>'; print '<br>';
print '<div class="center">'; print '<div class="center">';
print $langs->trans("NewMemberbyWeb"); print $langs->trans("NewMemberbyWeb");
print '</div>'; print '</div>';
llxFooterVierge(); llxFooterVierge();
exit; exit;
} }
@ -460,9 +460,9 @@ print '<div id="divsubscribe">';
print '<div class="center subscriptionformhelptext justify">'; print '<div class="center subscriptionformhelptext justify">';
if (!empty($conf->global->MEMBER_NEWFORM_TEXT)) { if (!empty($conf->global->MEMBER_NEWFORM_TEXT)) {
print $langs->trans($conf->global->MEMBER_NEWFORM_TEXT)."<br>\n"; print $langs->trans($conf->global->MEMBER_NEWFORM_TEXT)."<br>\n";
} else { } else {
print $langs->trans("NewSubscriptionDesc", $conf->global->MAIN_INFO_SOCIETE_MAIL)."<br>\n"; print $langs->trans("NewSubscriptionDesc", $conf->global->MAIN_INFO_SOCIETE_MAIL)."<br>\n";
} }
print '</div>'; print '</div>';
@ -510,31 +510,31 @@ print '<table class="border" summary="form to subscribe" id="tablesubscribe">'."
// Type // Type
if (empty($conf->global->MEMBER_NEWFORM_FORCETYPE)) { if (empty($conf->global->MEMBER_NEWFORM_FORCETYPE)) {
$listoftype = $adht->liste_array(); $listoftype = $adht->liste_array();
$tmp = array_keys($listoftype); $tmp = array_keys($listoftype);
$defaulttype = ''; $defaulttype = '';
$isempty = 1; $isempty = 1;
if (count($listoftype) == 1) { if (count($listoftype) == 1) {
$defaulttype = $tmp[0]; $defaulttype = $tmp[0];
$isempty = 0; $isempty = 0;
} }
print '<tr><td class="titlefield">'.$langs->trans("Type").' <FONT COLOR="red">*</FONT></td><td>'; print '<tr><td class="titlefield">'.$langs->trans("Type").' <FONT COLOR="red">*</FONT></td><td>';
print $form->selectarray("type", $adht->liste_array(), GETPOST('type') ?GETPOST('type') : $defaulttype, $isempty); print $form->selectarray("type", $adht->liste_array(), GETPOST('type') ?GETPOST('type') : $defaulttype, $isempty);
print '</td></tr>'."\n"; print '</td></tr>'."\n";
} else { } else {
$adht->fetch($conf->global->MEMBER_NEWFORM_FORCETYPE); $adht->fetch($conf->global->MEMBER_NEWFORM_FORCETYPE);
print '<input type="hidden" id="type" name="type" value="'.$conf->global->MEMBER_NEWFORM_FORCETYPE.'">'; print '<input type="hidden" id="type" name="type" value="'.$conf->global->MEMBER_NEWFORM_FORCETYPE.'">';
} }
// Moral/Physic attribute // Moral/Physic attribute
$morphys["phy"] = $langs->trans("Physical"); $morphys["phy"] = $langs->trans("Physical");
$morphys["mor"] = $langs->trans("Moral"); $morphys["mor"] = $langs->trans("Moral");
if (empty($conf->global->MEMBER_NEWFORM_FORCEMORPHY)) { if (empty($conf->global->MEMBER_NEWFORM_FORCEMORPHY)) {
print '<tr class="morphy"><td class="titlefield">'.$langs->trans('MemberNature').' <FONT COLOR="red">*</FONT></td><td>'."\n"; print '<tr class="morphy"><td class="titlefield">'.$langs->trans('MemberNature').' <FONT COLOR="red">*</FONT></td><td>'."\n";
print $form->selectarray("morphy", $morphys, GETPOST('morphy'), 1); print $form->selectarray("morphy", $morphys, GETPOST('morphy'), 1);
print '</td></tr>'."\n"; print '</td></tr>'."\n";
} else { } else {
print $morphys[$conf->global->MEMBER_NEWFORM_FORCEMORPHY]; print $morphys[$conf->global->MEMBER_NEWFORM_FORCEMORPHY];
print '<input type="hidden" id="morphy" name="morphy" value="'.$conf->global->MEMBER_NEWFORM_FORCEMORPHY.'">'; print '<input type="hidden" id="morphy" name="morphy" value="'.$conf->global->MEMBER_NEWFORM_FORCEMORPHY.'">';
} }
// Civility // Civility
print '<tr><td class="titlefield">'.$langs->trans('UserTitle').'</td><td>'; print '<tr><td class="titlefield">'.$langs->trans('UserTitle').'</td><td>';
@ -564,34 +564,34 @@ print '</td></tr>';
print '<tr><td>'.$langs->trans('Country').'</td><td>'; print '<tr><td>'.$langs->trans('Country').'</td><td>';
$country_id = GETPOST('country_id'); $country_id = GETPOST('country_id');
if (!$country_id && !empty($conf->global->MEMBER_NEWFORM_FORCECOUNTRYCODE)) { if (!$country_id && !empty($conf->global->MEMBER_NEWFORM_FORCECOUNTRYCODE)) {
$country_id = getCountry($conf->global->MEMBER_NEWFORM_FORCECOUNTRYCODE, 2, $db, $langs); $country_id = getCountry($conf->global->MEMBER_NEWFORM_FORCECOUNTRYCODE, 2, $db, $langs);
} }
if (!$country_id && !empty($conf->geoipmaxmind->enabled)) { if (!$country_id && !empty($conf->geoipmaxmind->enabled)) {
$country_code = dol_user_country(); $country_code = dol_user_country();
//print $country_code; //print $country_code;
if ($country_code) { if ($country_code) {
$new_country_id = getCountry($country_code, 3, $db, $langs); $new_country_id = getCountry($country_code, 3, $db, $langs);
//print 'xxx'.$country_code.' - '.$new_country_id; //print 'xxx'.$country_code.' - '.$new_country_id;
if ($new_country_id) $country_id = $new_country_id; if ($new_country_id) $country_id = $new_country_id;
} }
} }
$country_code = getCountry($country_id, 2, $db, $langs); $country_code = getCountry($country_id, 2, $db, $langs);
print $form->select_country($country_id, 'country_id'); print $form->select_country($country_id, 'country_id');
print '</td></tr>'; print '</td></tr>';
// State // State
if (empty($conf->global->SOCIETE_DISABLE_STATE)) { if (empty($conf->global->SOCIETE_DISABLE_STATE)) {
print '<tr><td>'.$langs->trans('State').'</td><td>'; print '<tr><td>'.$langs->trans('State').'</td><td>';
if ($country_code) print $formcompany->select_state(GETPOST("state_id"), $country_code); if ($country_code) print $formcompany->select_state(GETPOST("state_id"), $country_code);
else print ''; else print '';
print '</td></tr>'; print '</td></tr>';
} }
// EMail // EMail
print '<tr><td>'.$langs->trans("Email").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="email" maxlength="255" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('email')).'"></td></tr>'."\n"; print '<tr><td>'.$langs->trans("Email").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="email" maxlength="255" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('email')).'"></td></tr>'."\n";
// Login // Login
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
print '<tr><td>'.$langs->trans("Login").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="login" maxlength="50" class="minwidth100"value="'.dol_escape_htmltag(GETPOST('login')).'"></td></tr>'."\n"; print '<tr><td>'.$langs->trans("Login").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="login" maxlength="50" class="minwidth100"value="'.dol_escape_htmltag(GETPOST('login')).'"></td></tr>'."\n";
print '<tr><td>'.$langs->trans("Password").' <FONT COLOR="red">*</FONT></td><td><input type="password" maxlength="128" name="pass1" class="minwidth100" value="'.GETPOST("pass1").'"></td></tr>'."\n"; print '<tr><td>'.$langs->trans("Password").' <FONT COLOR="red">*</FONT></td><td><input type="password" maxlength="128" name="pass1" class="minwidth100" value="'.GETPOST("pass1").'"></td></tr>'."\n";
print '<tr><td>'.$langs->trans("PasswordAgain").' <FONT COLOR="red">*</FONT></td><td><input type="password" maxlength="128" name="pass2" class="minwidth100" value="'.GETPOST("pass2").'"></td></tr>'."\n"; print '<tr><td>'.$langs->trans("PasswordAgain").' <FONT COLOR="red">*</FONT></td><td><input type="password" maxlength="128" name="pass2" class="minwidth100" value="'.GETPOST("pass2").'"></td></tr>'."\n";
} }
// Birthday // Birthday
print '<tr id="trbirth" class="trbirth"><td>'.$langs->trans("DateToBirth").'</td><td>'; print '<tr id="trbirth" class="trbirth"><td>'.$langs->trans("DateToBirth").'</td><td>';
@ -612,12 +612,12 @@ print '</tr>'."\n";
// Add specific fields used by Dolibarr foundation for example // Add specific fields used by Dolibarr foundation for example
if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) { if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) {
$arraybudget = array('50'=>'<= 100 000', '100'=>'<= 200 000', '200'=>'<= 500 000', '300'=>'<= 1 500 000', '600'=>'<= 3 000 000', '1000'=>'<= 5 000 000', '2000'=>'5 000 000+'); $arraybudget = array('50'=>'<= 100 000', '100'=>'<= 200 000', '200'=>'<= 500 000', '300'=>'<= 1 500 000', '600'=>'<= 3 000 000', '1000'=>'<= 5 000 000', '2000'=>'5 000 000+');
print '<tr id="trbudget" class="trcompany"><td>'.$langs->trans("TurnoverOrBudget").' <FONT COLOR="red">*</FONT></td><td>'; print '<tr id="trbudget" class="trcompany"><td>'.$langs->trans("TurnoverOrBudget").' <FONT COLOR="red">*</FONT></td><td>';
print $form->selectarray('budget', $arraybudget, GETPOST('budget'), 1); print $form->selectarray('budget', $arraybudget, GETPOST('budget'), 1);
print ' € or $'; print ' € or $';
print '<script type="text/javascript"> print '<script type="text/javascript">
jQuery(document).ready(function () { jQuery(document).ready(function () {
initturnover(); initturnover();
jQuery("#morphy").click(function() { jQuery("#morphy").click(function() {
@ -651,28 +651,28 @@ if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) {
} }
}); });
</script>'; </script>';
print '</td></tr>'."\n"; print '</td></tr>'."\n";
} }
if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT) || !empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) { if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT) || !empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) {
// $conf->global->MEMBER_NEWFORM_SHOWAMOUNT is an amount // $conf->global->MEMBER_NEWFORM_SHOWAMOUNT is an amount
$amount = 0; $amount = 0;
if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) {
$amount = $conf->global->MEMBER_NEWFORM_AMOUNT; $amount = $conf->global->MEMBER_NEWFORM_AMOUNT;
} }
if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) { if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) {
$amount = GETPOST('amount') ?GETPOST('amount') : $conf->global->MEMBER_NEWFORM_AMOUNT; $amount = GETPOST('amount') ?GETPOST('amount') : $conf->global->MEMBER_NEWFORM_AMOUNT;
} }
// $conf->global->MEMBER_NEWFORM_PAYONLINE is 'paypal', 'paybox' or 'stripe' // $conf->global->MEMBER_NEWFORM_PAYONLINE is 'paypal', 'paybox' or 'stripe'
print '<tr><td>'.$langs->trans("Subscription").'</td><td class="nowrap">'; print '<tr><td>'.$langs->trans("Subscription").'</td><td class="nowrap">';
if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) {
print '<input type="text" name="amount" id="amount" class="flat amount" size="6" value="'.$amount.'">'; print '<input type="text" name="amount" id="amount" class="flat amount" size="6" value="'.$amount.'">';
} else { } else {
print '<input type="text" name="amount" id="amounthidden" class="flat amount" disabled size="6" value="'.$amount.'">'; print '<input type="text" name="amount" id="amounthidden" class="flat amount" disabled size="6" value="'.$amount.'">';
print '<input type="hidden" name="amount" id="amount" class="flat amount" size="6" value="'.$amount.'">'; print '<input type="hidden" name="amount" id="amount" class="flat amount" size="6" value="'.$amount.'">';
} }
print ' '.$langs->trans("Currency".$conf->currency); print ' '.$langs->trans("Currency".$conf->currency);
print '</td></tr>'; print '</td></tr>';
} }
print "</table>\n"; print "</table>\n";
@ -682,7 +682,7 @@ print dol_get_fiche_end();
print '<div class="center">'; print '<div class="center">';
print '<input type="submit" value="'.$langs->trans("Submit").'" id="submitsave" class="button">'; print '<input type="submit" value="'.$langs->trans("Submit").'" id="submitsave" class="button">';
if (!empty($backtopage)) { if (!empty($backtopage)) {
print ' &nbsp; &nbsp; <input type="submit" value="'.$langs->trans("Cancel").'" id="submitcancel" class="button">'; print ' &nbsp; &nbsp; <input type="submit" value="'.$langs->trans("Cancel").'" id="submitcancel" class="button">';
} }
print '</div>'; print '</div>';

View File

@ -64,11 +64,11 @@ if (empty($source)) $source = 'proposal';
if (!$action) if (!$action)
{ {
if ($source && !$ref) if ($source && !$ref)
{ {
print $langs->trans('ErrorBadParameters')." - ref missing"; print $langs->trans('ErrorBadParameters')." - ref missing";
exit; exit;
} }
} }
@ -83,18 +83,18 @@ $SECUREKEY = GETPOST("securekey"); // Secure key
if (!empty($source)) if (!empty($source))
{ {
$urlok .= 'source='.urlencode($source).'&'; $urlok .= 'source='.urlencode($source).'&';
$urlko .= 'source='.urlencode($source).'&'; $urlko .= 'source='.urlencode($source).'&';
} }
if (!empty($REF)) if (!empty($REF))
{ {
$urlok .= 'ref='.urlencode($REF).'&'; $urlok .= 'ref='.urlencode($REF).'&';
$urlko .= 'ref='.urlencode($REF).'&'; $urlko .= 'ref='.urlencode($REF).'&';
} }
if (!empty($SECUREKEY)) if (!empty($SECUREKEY))
{ {
$urlok .= 'securekey='.urlencode($SECUREKEY).'&'; $urlok .= 'securekey='.urlencode($SECUREKEY).'&';
$urlko .= 'securekey='.urlencode($SECUREKEY).'&'; $urlko .= 'securekey='.urlencode($SECUREKEY).'&';
} }
if (!empty($entity)) if (!empty($entity))
{ {
@ -114,7 +114,7 @@ $creditor = $mysoc->name;
if ($action == 'dosign') if ($action == 'dosign')
{ {
// TODO // TODO
} }
@ -134,12 +134,12 @@ llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'on
// Check link validity for param 'source' // Check link validity for param 'source'
if (!empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) if (!empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', '')))
{ {
$langs->load("errors"); $langs->load("errors");
dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref));
// End of page // End of page
llxFooter(); llxFooter();
$db->close(); $db->close();
exit; exit;
} }
print '<span id="dolpaymentspan"></span>'."\n"; print '<span id="dolpaymentspan"></span>'."\n";
@ -194,16 +194,16 @@ if ($urllogo)
$text = ''; $text = '';
if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT)) if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT))
{ {
$langs->load("members"); $langs->load("members");
$reg = array(); $reg = array();
if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."<br>\n"; if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."<br>\n";
else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n"; else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n";
$text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n"; $text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
} }
if (empty($text)) if (empty($text))
{ {
$text .= '<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'</strong></td></tr>'."\n"; $text .= '<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'</strong></td></tr>'."\n";
$text .= '<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'<br><br></td></tr>'."\n"; $text .= '<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'<br><br></td></tr>'."\n";
} }
print $text; print $text;
@ -237,9 +237,9 @@ if ($source == 'proposal')
// Creditor // Creditor
print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor"); print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor");
print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>'; print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>';
print '<input type="hidden" name="creditor" value="'.$creditor.'">'; print '<input type="hidden" name="creditor" value="'.$creditor.'">';
print '</td></tr>'."\n"; print '</td></tr>'."\n";
// Debitor // Debitor
@ -266,13 +266,13 @@ print '</table>'."\n";
print "\n"; print "\n";
if ($action != 'dosign') { if ($action != 'dosign') {
if ($found && !$error) { if ($found && !$error) {
// We are in a management option and no error // We are in a management option and no error
} else { } else {
dol_print_error_email('ERRORNEWONLINESIGN'); dol_print_error_email('ERRORNEWONLINESIGN');
} }
} else { } else {
// Print // Print
} }
print '</td></tr>'."\n"; print '</td></tr>'."\n";

View File

@ -417,42 +417,42 @@ if ($action == 'charge' && !empty($conf->stripe->enabled))
dol_syslog("POST vatnumber = ".$vatnumber, LOG_DEBUG, 0, '_stripe'); dol_syslog("POST vatnumber = ".$vatnumber, LOG_DEBUG, 0, '_stripe');
$error = 0; $error = 0;
$errormessage = ''; $errormessage = '';
// When using the Charge API architecture // When using the Charge API architecture
if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{ {
try { try {
$metadata = array( $metadata = array(
'dol_version' => DOL_VERSION, 'dol_version' => DOL_VERSION,
'dol_entity' => $conf->entity, 'dol_entity' => $conf->entity,
'dol_company' => $mysoc->name, // Usefull when using multicompany 'dol_company' => $mysoc->name, // Usefull when using multicompany
'dol_tax_num' => $vatnumber, 'dol_tax_num' => $vatnumber,
'ipaddress'=> getUserRemoteIP() 'ipaddress'=> getUserRemoteIP()
); );
if (!empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id; if (!empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id;
if ($thirdparty_id > 0) if ($thirdparty_id > 0)
{ {
dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe'); dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe');
$service = 'StripeTest'; $service = 'StripeTest';
$servicestatus = 0; $servicestatus = 0;
if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int'))
{ {
$service = 'StripeLive'; $service = 'StripeLive';
$servicestatus = 1; $servicestatus = 1;
} }
$thirdparty = new Societe($db); $thirdparty = new Societe($db);
$thirdparty->fetch($thirdparty_id); $thirdparty->fetch($thirdparty_id);
// Create Stripe customer // Create Stripe customer
include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
$stripe = new Stripe($db); $stripe = new Stripe($db);
$stripeacc = $stripe->getStripeAccount($service); $stripeacc = $stripe->getStripeAccount($service);
$customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1); $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
if (empty($customer)) if (empty($customer))
{ {
$error++; $error++;
@ -461,51 +461,51 @@ if ($action == 'charge' && !empty($conf->stripe->enabled))
$action = ''; $action = '';
} }
// Create Stripe card from Token // Create Stripe card from Token
if (!$error) if (!$error)
{ {
if ($savesource) { if ($savesource) {
$card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata)); $card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata));
} else { } else {
$card = $stripeToken; $card = $stripeToken;
} }
if (empty($card)) if (empty($card))
{ {
$error++; $error++;
dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe'); dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to create card record', null, 'errors'); setEventMessages('Failed to create card record', null, 'errors');
$action = ''; $action = '';
} else { } else {
if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG;
if (!empty($dol_id)) $metadata["dol_id"] = $dol_id; if (!empty($dol_id)) $metadata["dol_id"] = $dol_id;
if (!empty($dol_type)) $metadata["dol_type"] = $dol_type; if (!empty($dol_type)) $metadata["dol_type"] = $dol_type;
dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe'); dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe');
$charge = \Stripe\Charge::create(array( $charge = \Stripe\Charge::create(array(
'amount' => price2num($amountstripe, 'MU'), 'amount' => price2num($amountstripe, 'MU'),
'currency' => $currency, 'currency' => $currency,
'capture' => true, // Charge immediatly 'capture' => true, // Charge immediatly
'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref,
'metadata' => $metadata, 'metadata' => $metadata,
'customer' => $customer->id, 'customer' => $customer->id,
'source' => $card, 'source' => $card,
'statement_descriptor_suffix' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) 'statement_descriptor_suffix' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc"));
// Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
if (empty($charge)) if (empty($charge))
{ {
$error++; $error++;
dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to charge card', null, 'errors'); setEventMessages('Failed to charge card', null, 'errors');
$action = ''; $action = '';
} }
} }
} }
} else { } else {
$vatcleaned = $vatnumber ? $vatnumber : null; $vatcleaned = $vatnumber ? $vatnumber : null;
/*$taxinfo = array('type'=>'vat'); /*$taxinfo = array('type'=>'vat');
if ($vatcleaned) if ($vatcleaned)
{ {
$taxinfo["tax_id"] = $vatcleaned; $taxinfo["tax_id"] = $vatcleaned;
@ -514,18 +514,18 @@ if ($action == 'charge' && !empty($conf->stripe->enabled))
if (empty($vatcleaned)) $taxinfo=null; if (empty($vatcleaned)) $taxinfo=null;
*/ */
dol_syslog("Create anonymous customer card profile", LOG_DEBUG, 0, '_stripe'); dol_syslog("Create anonymous customer card profile", LOG_DEBUG, 0, '_stripe');
$customer = \Stripe\Customer::create(array( $customer = \Stripe\Customer::create(array(
'email' => $email, 'email' => $email,
'description' => ($email ? 'Anonymous customer for '.$email : 'Anonymous customer'), 'description' => ($email ? 'Anonymous customer for '.$email : 'Anonymous customer'),
'metadata' => $metadata, 'metadata' => $metadata,
'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?)
)); ));
// Return $customer = array('id'=>'cus_XXXX', ...) // Return $customer = array('id'=>'cus_XXXX', ...)
// Create the VAT record in Stripe // Create the VAT record in Stripe
/* We don't know country of customer, so we can't create tax /* We don't know country of customer, so we can't create tax
if (! empty($conf->global->STRIPE_SAVE_TAX_IDS)) // We setup to save Tax info on Stripe side. Warning: This may result in error when saving customer if (! empty($conf->global->STRIPE_SAVE_TAX_IDS)) // We setup to save Tax info on Stripe side. Warning: This may result in error when saving customer
{ {
if (! empty($vatcleaned)) if (! empty($vatcleaned))
@ -539,145 +539,145 @@ if ($action == 'charge' && !empty($conf->stripe->enabled))
} }
}*/ }*/
if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG;
if (!empty($dol_id)) $metadata["dol_id"] = $dol_id; if (!empty($dol_id)) $metadata["dol_id"] = $dol_id;
if (!empty($dol_type)) $metadata["dol_type"] = $dol_type; if (!empty($dol_type)) $metadata["dol_type"] = $dol_type;
// The customer was just created with a source, so we can make a charge // The customer was just created with a source, so we can make a charge
// with no card defined, the source just used for customer creation will be used. // with no card defined, the source just used for customer creation will be used.
dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe');
$charge = \Stripe\Charge::create(array( $charge = \Stripe\Charge::create(array(
'customer' => $customer->id, 'customer' => $customer->id,
'amount' => price2num($amountstripe, 'MU'), 'amount' => price2num($amountstripe, 'MU'),
'currency' => $currency, 'currency' => $currency,
'capture' => true, // Charge immediatly 'capture' => true, // Charge immediatly
'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref,
'metadata' => $metadata, 'metadata' => $metadata,
'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc"));
// Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
if (empty($charge)) if (empty($charge))
{ {
$error++; $error++;
dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to charge card', null, 'errors'); setEventMessages('Failed to charge card', null, 'errors');
$action = ''; $action = '';
} }
} }
} catch (\Stripe\Error\Card $e) { } catch (\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught // Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody(); $body = $e->getJsonBody();
$err = $body['error']; $err = $body['error'];
print('Status is:'.$e->getHttpStatus()."\n"); print('Status is:'.$e->getHttpStatus()."\n");
print('Type is:'.$err['type']."\n"); print('Type is:'.$err['type']."\n");
print('Code is:'.$err['code']."\n"); print('Code is:'.$err['code']."\n");
// param is '' in this case // param is '' in this case
print('Param is:'.$err['param']."\n"); print('Param is:'.$err['param']."\n");
print('Message is:'.$err['message']."\n"); print('Message is:'.$err['message']."\n");
$error++; $error++;
$errormessage = "ErrorCard ".$e->getMessage()." err=".var_export($err, true); $errormessage = "ErrorCard ".$e->getMessage()." err=".var_export($err, true);
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} catch (\Stripe\Error\RateLimit $e) { } catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly // Too many requests made to the API too quickly
$error++; $error++;
$errormessage = "ErrorRateLimit ".$e->getMessage(); $errormessage = "ErrorRateLimit ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} catch (\Stripe\Error\InvalidRequest $e) { } catch (\Stripe\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API // Invalid parameters were supplied to Stripe's API
$error++; $error++;
$errormessage = "ErrorInvalidRequest ".$e->getMessage(); $errormessage = "ErrorInvalidRequest ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} catch (\Stripe\Error\Authentication $e) { } catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed // Authentication with Stripe's API failed
// (maybe you changed API keys recently) // (maybe you changed API keys recently)
$error++; $error++;
$errormessage = "ErrorAuthentication ".$e->getMessage(); $errormessage = "ErrorAuthentication ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} catch (\Stripe\Error\ApiConnection $e) { } catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed // Network communication with Stripe failed
$error++; $error++;
$errormessage = "ErrorApiConnection ".$e->getMessage(); $errormessage = "ErrorApiConnection ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} catch (\Stripe\Error\Base $e) { } catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send // Display a very generic error to the user, and maybe send
// yourself an email // yourself an email
$error++; $error++;
$errormessage = "ErrorBase ".$e->getMessage(); $errormessage = "ErrorBase ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} catch (Exception $e) { } catch (Exception $e) {
// Something else happened, completely unrelated to Stripe // Something else happened, completely unrelated to Stripe
$error++; $error++;
$errormessage = "ErrorException ".$e->getMessage(); $errormessage = "ErrorException ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} }
} }
// When using the PaymentIntent API architecture // When using the PaymentIntent API architecture
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{ {
$service = 'StripeTest'; $service = 'StripeTest';
$servicestatus = 0; $servicestatus = 0;
if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int'))
{ {
$service = 'StripeLive'; $service = 'StripeLive';
$servicestatus = 1; $servicestatus = 1;
} }
include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
$stripe = new Stripe($db); $stripe = new Stripe($db);
$stripeacc = $stripe->getStripeAccount($service); $stripeacc = $stripe->getStripeAccount($service);
// We go here if $conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION is set. // We go here if $conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION is set.
// In such a case, payment is always ok when we call the "charge" action. // In such a case, payment is always ok when we call the "charge" action.
$paymentintent_id = GETPOST("paymentintent_id", "alpha"); $paymentintent_id = GETPOST("paymentintent_id", "alpha");
// Force to use the correct API key // Force to use the correct API key
global $stripearrayofkeysbyenv; global $stripearrayofkeysbyenv;
\Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']); \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
try { try {
if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
$paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id); $paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id);
} else { } else {
$paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id, array("stripe_account" => $stripeacc)); $paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id, array("stripe_account" => $stripeacc));
} }
} catch (Exception $e) } catch (Exception $e)
{ {
$error++; $error++;
$errormessage = "CantRetrievePaymentIntent ".$e->getMessage(); $errormessage = "CantRetrievePaymentIntent ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors'); setEventMessages($e->getMessage(), null, 'errors');
$action = ''; $action = '';
} }
if ($paymentintent->status != 'succeeded') if ($paymentintent->status != 'succeeded')
{ {
$error++; $error++;
$errormessage = "StatusOfRetrievedIntent is not succeeded: ".$paymentintent->status; $errormessage = "StatusOfRetrievedIntent is not succeeded: ".$paymentintent->status;
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($paymentintent->status, null, 'errors'); setEventMessages($paymentintent->status, null, 'errors');
$action = ''; $action = '';
} else { } else {
// TODO We can alse record the payment mode into llx_societe_rib with stripe $paymentintent->payment_method // TODO We can alse record the payment mode into llx_societe_rib with stripe $paymentintent->payment_method
// Note that with other old Stripe architecture (using Charge API), the payment mode was not recorded, so it is not mandatory to do it here. // Note that with other old Stripe architecture (using Charge API), the payment mode was not recorded, so it is not mandatory to do it here.
//dol_syslog("Create payment_method for ".$paymentintent->payment_method, LOG_DEBUG, 0, '_stripe'); //dol_syslog("Create payment_method for ".$paymentintent->payment_method, LOG_DEBUG, 0, '_stripe');
} }
} }
$remoteip = getUserRemoteIP(); $remoteip = getUserRemoteIP();
@ -727,8 +727,8 @@ if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_r
$langs->load("errors"); $langs->load("errors");
dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref));
// End of page // End of page
llxFooter(); llxFooter();
$db->close(); $db->close();
exit; exit;
} }
@ -1394,9 +1394,9 @@ if ($source == 'membersubscription')
print '</td></tr>'."\n"; print '</td></tr>'."\n";
if ($object->datefin > 0) { if ($object->datefin > 0) {
print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("DateEndSubscription"); print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("DateEndSubscription");
print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.dol_print_date($member->datefin, 'day'); print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.dol_print_date($member->datefin, 'day');
print '</td></tr>'."\n"; print '</td></tr>'."\n";
} }
if ($member->last_subscription_date || $member->last_subscription_amount) if ($member->last_subscription_date || $member->last_subscription_amount)
@ -1667,13 +1667,13 @@ if ($action != 'dopayment')
{ {
print '<br><br><span class="amountpaymentcomplete">'.$langs->trans("DonationPaid").'</span>'; print '<br><br><span class="amountpaymentcomplete">'.$langs->trans("DonationPaid").'</span>';
} else { } else {
// Membership can be paid and we still allow to make renewal // Membership can be paid and we still allow to make renewal
if ($source == 'membersubscription' && $object->datefin > dol_now()) if ($source == 'membersubscription' && $object->datefin > dol_now())
{ {
$langs->load("members"); $langs->load("members");
print '<br><span class="amountpaymentcomplete">'.$langs->trans("MembershipPaid", dol_print_date($object->datefin, 'day')).'</span><br>'; print '<br><span class="amountpaymentcomplete">'.$langs->trans("MembershipPaid", dol_print_date($object->datefin, 'day')).'</span><br>';
print '<div class="opacitymedium margintoponly">'.$langs->trans("PaymentWillBeRecordedForNextPeriod").'</div>'; print '<div class="opacitymedium margintoponly">'.$langs->trans("PaymentWillBeRecordedForNextPeriod").'</div>';
} }
// Buttons for all payments registration methods // Buttons for all payments registration methods
@ -1862,48 +1862,48 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
//if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) || ! empty($paymentintent)) //if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) || ! empty($paymentintent))
//{ //{
print ' print '
<table id="dolpaymenttable" summary="Payment form" class="center"> <table id="dolpaymenttable" summary="Payment form" class="center">
<tbody><tr><td class="textpublicpayment">'; <tbody><tr><td class="textpublicpayment">';
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{ {
print '<div id="payment-request-button"><!-- A Stripe Element will be inserted here. --></div>'; print '<div id="payment-request-button"><!-- A Stripe Element will be inserted here. --></div>';
} }
print '<div class="form-row left">'; print '<div class="form-row left">';
print '<label for="card-element">'.$langs->trans("CreditOrDebitCard").'</label>'; print '<label for="card-element">'.$langs->trans("CreditOrDebitCard").'</label>';
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{ {
print '<br><input id="cardholder-name" class="marginbottomonly" name="cardholder-name" value="" type="text" placeholder="'.$langs->trans("CardOwner").'" autocomplete="off" autofocus required>'; print '<br><input id="cardholder-name" class="marginbottomonly" name="cardholder-name" value="" type="text" placeholder="'.$langs->trans("CardOwner").'" autocomplete="off" autofocus required>';
} }
print '<div id="card-element"> print '<div id="card-element">
<!-- a Stripe Element will be inserted here. --> <!-- a Stripe Element will be inserted here. -->
</div>'; </div>';
print '<!-- Used to display form errors --> print '<!-- Used to display form errors -->
<div id="card-errors" role="alert"></div> <div id="card-errors" role="alert"></div>
</div>'; </div>';
print '<br>'; print '<br>';
print '<button class="button buttonpayment" style="text-align: center; padding-left: 0; padding-right: 0;" id="buttontopay" data-secret="'.(is_object($paymentintent) ? $paymentintent->client_secret : '').'">'.$langs->trans("ValidatePayment").'</button>'; print '<button class="button buttonpayment" style="text-align: center; padding-left: 0; padding-right: 0;" id="buttontopay" data-secret="'.(is_object($paymentintent) ? $paymentintent->client_secret : '').'">'.$langs->trans("ValidatePayment").'</button>';
print '<img id="hourglasstopay" class="hidden" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/working.gif">'; print '<img id="hourglasstopay" class="hidden" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/working.gif">';
print '</td></tr></tbody>'; print '</td></tr></tbody>';
print '</table>'; print '</table>';
//} //}
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{ {
if (empty($paymentintent)) if (empty($paymentintent))
{ {
print '<center>'.$langs->trans("Error").'</center>'; print '<center>'.$langs->trans("Error").'</center>';
} else { } else {
print '<input type="hidden" name="paymentintent_id" value="'.$paymentintent->id.'">'; print '<input type="hidden" name="paymentintent_id" value="'.$paymentintent->id.'">';
//$_SESSION["paymentintent_id"] = $paymentintent->id; //$_SESSION["paymentintent_id"] = $paymentintent->id;
} }
} }
print '</form>'."\n"; print '</form>'."\n";
@ -1916,71 +1916,71 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
print info_admin($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Stripe")), 0, 0, 'error'); print info_admin($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Stripe")), 0, 0, 'error');
} else { } else {
print '<!-- JS Code for Stripe components -->'; print '<!-- JS Code for Stripe components -->';
print '<script src="https://js.stripe.com/v3/"></script>'."\n"; print '<script src="https://js.stripe.com/v3/"></script>'."\n";
print '<!-- urllogofull = '.$urllogofull.' -->'."\n"; print '<!-- urllogofull = '.$urllogofull.' -->'."\n";
// Code to ask the credit card. This use the default "API version". No way to force API version when using JS code. // Code to ask the credit card. This use the default "API version". No way to force API version when using JS code.
print '<script type="text/javascript" language="javascript">'."\n"; print '<script type="text/javascript" language="javascript">'."\n";
if (!empty($conf->global->STRIPE_USE_NEW_CHECKOUT)) if (!empty($conf->global->STRIPE_USE_NEW_CHECKOUT))
{ {
$amountstripe = $amount; $amountstripe = $amount;
// Correct the amount according to unit of currency // Correct the amount according to unit of currency
// See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support
$arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100; if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100;
$ipaddress = getUserRemoteIP(); $ipaddress = getUserRemoteIP();
$metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress); $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
if (is_object($object)) if (is_object($object))
{ {
$metadata['dol_type'] = $object->element; $metadata['dol_type'] = $object->element;
$metadata['dol_id'] = $object->id; $metadata['dol_id'] = $object->id;
$ref = $object->ref; $ref = $object->ref;
} }
try { try {
$arrayforpaymentintent = array( $arrayforpaymentintent = array(
'description'=>'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''), 'description'=>'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''),
"metadata" => $metadata "metadata" => $metadata
); );
if ($TAG) $arrayforpaymentintent["statement_descriptor"] = dol_trunc($TAG, 10, 'right', 'UTF-8', 1); // 22 chars that appears on bank receipt (company + description) if ($TAG) $arrayforpaymentintent["statement_descriptor"] = dol_trunc($TAG, 10, 'right', 'UTF-8', 1); // 22 chars that appears on bank receipt (company + description)
$arrayforcheckout = array( $arrayforcheckout = array(
'payment_method_types' => array('card'), 'payment_method_types' => array('card'),
'line_items' => array(array( 'line_items' => array(array(
'name' => $langs->transnoentitiesnoconv("Payment").' '.$TAG, // Label of product line 'name' => $langs->transnoentitiesnoconv("Payment").' '.$TAG, // Label of product line
'description' => 'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''), 'description' => 'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''),
'amount' => $amountstripe, 'amount' => $amountstripe,
'currency' => $currency, 'currency' => $currency,
//'images' => array($urllogofull), //'images' => array($urllogofull),
'quantity' => 1, 'quantity' => 1,
)), )),
'client_reference_id' => $FULLTAG, 'client_reference_id' => $FULLTAG,
'success_url' => $urlok, 'success_url' => $urlok,
'cancel_url' => $urlko, 'cancel_url' => $urlko,
'payment_intent_data' => $arrayforpaymentintent 'payment_intent_data' => $arrayforpaymentintent
); );
if ($stripecu) $arrayforcheckout['customer'] = $stripecu; if ($stripecu) $arrayforcheckout['customer'] = $stripecu;
elseif (GETPOST('email', 'alpha') && isValidEmail(GETPOST('email', 'alpha'))) $arrayforcheckout['customer_email'] = GETPOST('email', 'alpha'); elseif (GETPOST('email', 'alpha') && isValidEmail(GETPOST('email', 'alpha'))) $arrayforcheckout['customer_email'] = GETPOST('email', 'alpha');
$sessionstripe = \Stripe\Checkout\Session::create($arrayforcheckout); $sessionstripe = \Stripe\Checkout\Session::create($arrayforcheckout);
$remoteip = getUserRemoteIP(); $remoteip = getUserRemoteIP();
// Save some data for the paymentok // Save some data for the paymentok
$_SESSION["currencyCodeType"] = $currency; $_SESSION["currencyCodeType"] = $currency;
$_SESSION["paymentType"] = ''; $_SESSION["paymentType"] = '';
$_SESSION["FinalPaymentAmt"] = $amount; $_SESSION["FinalPaymentAmt"] = $amount;
$_SESSION['ipaddress'] = ($remoteip ? $remoteip : 'unknown'); // Payer ip $_SESSION['ipaddress'] = ($remoteip ? $remoteip : 'unknown'); // Payer ip
$_SESSION['payerID'] = is_object($stripecu) ? $stripecu->id : ''; $_SESSION['payerID'] = is_object($stripecu) ? $stripecu->id : '';
$_SESSION['TRANSACTIONID'] = $sessionstripe->id; $_SESSION['TRANSACTIONID'] = $sessionstripe->id;
} catch (Exception $e) } catch (Exception $e)
{ {
print $e->getMessage(); print $e->getMessage();
} }
?> ?>
// Code for payment with option STRIPE_USE_NEW_CHECKOUT set // Code for payment with option STRIPE_USE_NEW_CHECKOUT set
// Create a Stripe client. // Create a Stripe client.
@ -2024,9 +2024,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
<?php <?php
} elseif (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) } elseif (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{ {
?> ?>
// Code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION set // Code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION set
// Create a Stripe client. // Create a Stripe client.
@ -2129,9 +2129,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
}); });
<?php <?php
} else // Old method (not SCA ready) } else // Old method (not SCA ready)
{ {
?> ?>
// Old code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION off and STRIPE_USE_NEW_CHECKOUT off // Old code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION off and STRIPE_USE_NEW_CHECKOUT off
// Create a Stripe client. // Create a Stripe client.
@ -2181,9 +2181,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
form.addEventListener('submit', function(event) { form.addEventListener('submit', function(event) {
event.preventDefault(); event.preventDefault();
<?php <?php
if (empty($conf->global->STRIPE_USE_3DSECURE)) // Ask credit card directly, no 3DS test if (empty($conf->global->STRIPE_USE_3DSECURE)) // Ask credit card directly, no 3DS test
{ {
?> ?>
/* Use token */ /* Use token */
stripe.createToken(card).then(function(result) { stripe.createToken(card).then(function(result) {
if (result.error) { if (result.error) {
@ -2196,9 +2196,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
} }
}); });
<?php <?php
} else // Ask credit card with 3DS test } else // Ask credit card with 3DS test
{ {
?> ?>
/* Use 3DS source */ /* Use 3DS source */
stripe.createSource(card).then(function(result) { stripe.createSource(card).then(function(result) {
if (result.error) { if (result.error) {
@ -2211,8 +2211,8 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
} }
}); });
<?php <?php
} }
?> ?>
}); });
@ -2265,9 +2265,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
} }
<?php <?php
} }
print '</script>'; print '</script>';
} }
} }
// This hook is used to show the embedded form to make payments with external payment modules (ie Payzen, ...) // This hook is used to show the embedded form to make payments with external payment modules (ie Payzen, ...)

View File

@ -22,15 +22,15 @@
*/ */
if (!defined('NOCSRFCHECK')) { if (!defined('NOCSRFCHECK')) {
define('NOCSRFCHECK', '1'); define('NOCSRFCHECK', '1');
} }
// Do not check anti CSRF attack test // Do not check anti CSRF attack test
if (!defined('NOREQUIREMENU')) { if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1'); define('NOREQUIREMENU', '1');
} }
// If there is no need to load and show top and left menu // If there is no need to load and show top and left menu
if (!defined("NOLOGIN")) { if (!defined("NOLOGIN")) {
define("NOLOGIN", '1'); define("NOLOGIN", '1');
} }
if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1');

View File

@ -69,7 +69,7 @@ $parameters = array(
// Note that $action and $object may have been modified by some hooks // Note that $action and $object may have been modified by some hooks
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
if ($reshook < 0) { if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
} }
// Add file in email form // Add file in email form
if (empty($reshook) && GETPOST('addfile', 'alpha') && !GETPOST('add', 'alpha')) { if (empty($reshook) && GETPOST('addfile', 'alpha') && !GETPOST('add', 'alpha')) {

View File

@ -57,7 +57,7 @@ class RecruitmentJobPosition extends CommonObject
*/ */
public $isextrafieldmanaged = 1; public $isextrafieldmanaged = 1;
/** /**
* @var string String with name of icon for recruitmentjobposition. Must be the part after the 'object_' into object_recruitmentjobposition.png * @var string String with name of icon for recruitmentjobposition. Must be the part after the 'object_' into object_recruitmentjobposition.png
*/ */
public $picto = 'recruitmentjobposition'; public $picto = 'recruitmentjobposition';
@ -126,30 +126,30 @@ class RecruitmentJobPosition extends CommonObject
); );
public $rowid; public $rowid;
/** /**
* @var string ref * @var string ref
*/ */
public $ref; public $ref;
public $entity; public $entity;
/** /**
* @var string label * @var string label
*/ */
public $label; public $label;
public $qty; public $qty;
public $fk_soc; public $fk_soc;
public $fk_project; public $fk_project;
public $fk_user_recruiter; public $fk_user_recruiter;
/** /**
* @var string recruiter email * @var string recruiter email
*/ */
public $email_recruiter; public $email_recruiter;
/** /**
* @var string suggested remuneration * @var string suggested remuneration
*/ */
public $remuneration_suggested; public $remuneration_suggested;
public $fk_user_supervisor; public $fk_user_supervisor;
public $fk_establishment; public $fk_establishment;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -610,8 +610,8 @@ if (!empty($type))
if ($type == 'f') $label = 'NewSupplier'; if ($type == 'f') $label = 'NewSupplier';
} }
if ($contextpage = 'poslist' && $type == 't' && ( !empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { if ($contextpage = 'poslist' && $type == 't' && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
print get_htmloutput_mesg(img_warning('default') . ' ' . $langs->trans("BecarefullChangeThirdpartyBeforeAddProductToInvoice"), '', 'warning', 1); print get_htmloutput_mesg(img_warning('default').' '.$langs->trans("BecarefullChangeThirdpartyBeforeAddProductToInvoice"), '', 'warning', 1);
} }
// Show the new button only when this page is not opend from the Extended POS (pop-up window) // Show the new button only when this page is not opend from the Extended POS (pop-up window)
@ -1257,13 +1257,13 @@ while ($i < min($num, $limit))
{ {
// Prospect status // Prospect status
print '<td class="center nowrap"><div class="nowrap">'; print '<td class="center nowrap"><div class="nowrap">';
print '<div class="inline-block">' . $companystatic->LibProspCommStatut($obj->stcomm_id, 2, $prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto); print '<div class="inline-block">'.$companystatic->LibProspCommStatut($obj->stcomm_id, 2, $prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto);
print '</div> - <div class="inline-block">'; print '</div> - <div class="inline-block">';
foreach ($prospectstatic->cacheprospectstatus as $key => $val) foreach ($prospectstatic->cacheprospectstatus as $key => $val)
{ {
$titlealt = 'default'; $titlealt = 'default';
if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label']; if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label'];
if ($obj->stcomm_id != $val['id']) print '<a class="pictosubstatus" href="' . $_SERVER["PHP_SELF"] . '?stcommsocid=' . $obj->rowid . '&stcomm=' . $val['code'] . '&action=setstcomm&token='.newToken() . $param . ($page ? '&page=' . urlencode($page) : '') . '">' . img_action($titlealt, $val['code'], $val['picto']) . '</a>'; if ($obj->stcomm_id != $val['id']) print '<a class="pictosubstatus" href="'.$_SERVER["PHP_SELF"].'?stcommsocid='.$obj->rowid.'&stcomm='.$val['code'].'&action=setstcomm&token='.newToken().$param.($page ? '&page='.urlencode($page) : '').'">'.img_action($titlealt, $val['code'], $val['picto']).'</a>';
} }
print '</div></div></td>'; print '</div></div></td>';
if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['nbfield']++;

View File

@ -40,7 +40,7 @@ if (GETPOSTISSET('status')) {
if (GETPOST('smp-status')) { if (GETPOST('smp-status')) {
print '<html lang="en">'; print '<html lang="en">';
print '<head>'; print '<head>';
print '<meta charset="utf-8"> print '<meta charset="utf-8">
<title>The HTML5 Herald</title> <title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald"> <meta name="description" content="The HTML5 Herald">

View File

@ -39,11 +39,11 @@ dol_syslog("Call ActionComm webservices interfaces");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES))
{ {
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
print $langs->trans("ToActivateModule"); print $langs->trans("ToActivateModule");
exit; exit;
} }
// Create the soap Object // Create the soap Object
@ -57,36 +57,36 @@ $server->wsdl->schemaTargetNamespace = $ns;
// Define WSDL Authentication object // Define WSDL Authentication object
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'authentication', 'authentication',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
array( array(
'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'), 'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'),
'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'), 'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'),
'login' => array('name'=>'login', 'type'=>'xsd:string'), 'login' => array('name'=>'login', 'type'=>'xsd:string'),
'password' => array('name'=>'password', 'type'=>'xsd:string'), 'password' => array('name'=>'password', 'type'=>'xsd:string'),
'entity' => array('name'=>'entity', 'type'=>'xsd:string'), 'entity' => array('name'=>'entity', 'type'=>'xsd:string'),
) )
); );
// Define WSDL Return object // Define WSDL Return object
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'result', 'result',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
array( array(
'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'), 'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'),
'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'), 'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'),
) )
); );
$actioncomm_fields = array( $actioncomm_fields = array(
'id' => array('name'=>'id', 'type'=>'xsd:string'), 'id' => array('name'=>'id', 'type'=>'xsd:string'),
'ref' => array('name'=>'ref', 'type'=>'xsd:string'), 'ref' => array('name'=>'ref', 'type'=>'xsd:string'),
'ref_ext' => array('name'=>'ref_ext', 'type'=>'xsd:string'), 'ref_ext' => array('name'=>'ref_ext', 'type'=>'xsd:string'),
'type_id' => array('name'=>'type_id', 'type'=>'xsd:string'), 'type_id' => array('name'=>'type_id', 'type'=>'xsd:string'),
@ -137,11 +137,11 @@ if (is_array($extrafield_array)) $actioncomm_fields = array_merge($actioncomm_fi
// Define other specific objects // Define other specific objects
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'actioncomm', 'actioncomm',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
$actioncomm_fields $actioncomm_fields
); );
@ -165,12 +165,12 @@ $server->wsdl->addComplexType(
'sequence', 'sequence',
'', '',
array( array(
'actioncommtype' => array( 'actioncommtype' => array(
'name' => 'actioncommtype', 'name' => 'actioncommtype',
'type' => 'tns:actioncommtype', 'type' => 'tns:actioncommtype',
'minOccurs' => '0', 'minOccurs' => '0',
'maxOccurs' => 'unbounded' 'maxOccurs' => 'unbounded'
) )
) )
); );
@ -199,16 +199,16 @@ $server->register(
// Register WSDL // Register WSDL
$server->register( $server->register(
'getActionComm', 'getActionComm',
// Entry values // Entry values
array('authentication'=>'tns:authentication', 'id'=>'xsd:string'), array('authentication'=>'tns:authentication', 'id'=>'xsd:string'),
// Exit values // Exit values
array('result'=>'tns:result', 'actioncomm'=>'tns:actioncomm'), array('result'=>'tns:result', 'actioncomm'=>'tns:actioncomm'),
$ns, $ns,
$ns.'#getActionComm', $ns.'#getActionComm',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to get actioncomm' 'WS to get actioncomm'
); );
// Register WSDL // Register WSDL
@ -251,100 +251,100 @@ $server->register(
*/ */
function getActionComm($authentication, $id) function getActionComm($authentication, $id)
{ {
global $db, $conf, $langs; global $db, $conf, $langs;
dol_syslog("Function: getActionComm login=".$authentication['login']." id=".$id); dol_syslog("Function: getActionComm login=".$authentication['login']." id=".$id);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) $conf->entity = $authentication['entity'];
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
$errorcode = ''; $errorlabel = ''; $errorcode = ''; $errorlabel = '';
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if ($error || (!$id)) if ($error || (!$id))
{ {
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error)
{ {
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->agenda->allactions->read) if ($fuser->rights->agenda->allactions->read)
{ {
$actioncomm = new ActionComm($db); $actioncomm = new ActionComm($db);
$result = $actioncomm->fetch($id); $result = $actioncomm->fetch($id);
if ($result > 0) if ($result > 0)
{ {
$actioncomm_result_fields = array( $actioncomm_result_fields = array(
'id' => $actioncomm->id, 'id' => $actioncomm->id,
'ref'=> $actioncomm->ref, 'ref'=> $actioncomm->ref,
'ref_ext'=> $actioncomm->ref_ext, 'ref_ext'=> $actioncomm->ref_ext,
'type_id'=> $actioncomm->type_id, 'type_id'=> $actioncomm->type_id,
'type_code'=> $actioncomm->type_code, 'type_code'=> $actioncomm->type_code,
'type'=> $actioncomm->type, 'type'=> $actioncomm->type,
'label'=> $actioncomm->label, 'label'=> $actioncomm->label,
'datep'=> dol_print_date($actioncomm->datep, 'dayhourrfc'), 'datep'=> dol_print_date($actioncomm->datep, 'dayhourrfc'),
'datef'=> dol_print_date($actioncomm->datef, 'dayhourrfc'), 'datef'=> dol_print_date($actioncomm->datef, 'dayhourrfc'),
'datec'=> dol_print_date($actioncomm->datec, 'dayhourrfc'), 'datec'=> dol_print_date($actioncomm->datec, 'dayhourrfc'),
'datem'=> dol_print_date($actioncomm->datem, 'dayhourrfc'), 'datem'=> dol_print_date($actioncomm->datem, 'dayhourrfc'),
'note'=> $actioncomm->note_private, 'note'=> $actioncomm->note_private,
'percentage'=> $actioncomm->percentage, 'percentage'=> $actioncomm->percentage,
'author'=> $actioncomm->authorid, 'author'=> $actioncomm->authorid,
'usermod'=> $actioncomm->usermodid, 'usermod'=> $actioncomm->usermodid,
'userownerid'=> $actioncomm->userownerid, 'userownerid'=> $actioncomm->userownerid,
'priority'=> $actioncomm->priority, 'priority'=> $actioncomm->priority,
'fulldayevent'=> $actioncomm->fulldayevent, 'fulldayevent'=> $actioncomm->fulldayevent,
'location'=> $actioncomm->location, 'location'=> $actioncomm->location,
'socid'=> $actioncomm->socid, 'socid'=> $actioncomm->socid,
'contactid'=> $actioncomm->contact_id, 'contactid'=> $actioncomm->contact_id,
'projectid'=> $actioncomm->fk_project, 'projectid'=> $actioncomm->fk_project,
'fk_element'=> $actioncomm->fk_element, 'fk_element'=> $actioncomm->fk_element,
'elementtype'=> $actioncomm->elementtype 'elementtype'=> $actioncomm->elementtype
); );
$elementtype = 'actioncomm'; $elementtype = 'actioncomm';
// Retrieve all extrafield for actioncomm // Retrieve all extrafield for actioncomm
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
//Get extrafield values //Get extrafield values
$actioncomm->fetch_optionals(); $actioncomm->fetch_optionals();
if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label']))
{ {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{ {
$actioncomm_result_fields = array_merge($actioncomm_result_fields, array('options_'.$key => $actioncomm->array_options['options_'.$key])); $actioncomm_result_fields = array_merge($actioncomm_result_fields, array('options_'.$key => $actioncomm->array_options['options_'.$key]));
} }
} }
// Create // Create
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'actioncomm'=>$actioncomm_result_fields); 'actioncomm'=>$actioncomm_result_fields);
} }
else { else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} }
else { else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error)
{ {
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
return $objectresp; return $objectresp;
} }
@ -384,8 +384,8 @@ function getListActionCommType($authentication)
} }
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'actioncommtypes'=>$resultarray); 'actioncommtypes'=>$resultarray);
} else { } else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;

View File

@ -35,11 +35,11 @@ dol_syslog("Call Contact webservices interfaces");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES))
{ {
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
print $langs->trans("ToActivateModule"); print $langs->trans("ToActivateModule");
exit; exit;
} }
// Create the soap Object // Create the soap Object
@ -53,31 +53,31 @@ $server->wsdl->schemaTargetNamespace = $ns;
// Define WSDL Authentication object // Define WSDL Authentication object
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'authentication', 'authentication',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
array( array(
'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'), 'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'),
'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'), 'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'),
'login' => array('name'=>'login', 'type'=>'xsd:string'), 'login' => array('name'=>'login', 'type'=>'xsd:string'),
'password' => array('name'=>'password', 'type'=>'xsd:string'), 'password' => array('name'=>'password', 'type'=>'xsd:string'),
'entity' => array('name'=>'entity', 'type'=>'xsd:string'), 'entity' => array('name'=>'entity', 'type'=>'xsd:string'),
) )
); );
// Define WSDL Return object // Define WSDL Return object
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'result', 'result',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
array( array(
'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'), 'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'),
'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'), 'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'),
) )
); );
$contact_fields = array( $contact_fields = array(
@ -142,11 +142,11 @@ if (is_array($extrafield_array)) $contact_fields = array_merge($contact_fields,
// Define other specific objects // Define other specific objects
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'contact', 'contact',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
$contact_fields $contact_fields
); );
@ -179,16 +179,16 @@ $styleuse = 'encoded'; // encoded/literal/literal wrapped
// Register WSDL // Register WSDL
$server->register( $server->register(
'getContact', 'getContact',
// Entry values // Entry values
array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref_ext'=>'xsd:string'), array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref_ext'=>'xsd:string'),
// Exit values // Exit values
array('result'=>'tns:result', 'contact'=>'tns:contact'), array('result'=>'tns:result', 'contact'=>'tns:contact'),
$ns, $ns,
$ns.'#getContact', $ns.'#getContact',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to get a contact' 'WS to get a contact'
); );
// Register WSDL // Register WSDL
@ -243,113 +243,113 @@ $server->register(
*/ */
function getContact($authentication, $id, $ref_ext) function getContact($authentication, $id, $ref_ext)
{ {
global $db, $conf, $langs; global $db, $conf, $langs;
dol_syslog("Function: getContact login=".$authentication['login']." id=".$id." ref_ext=".$ref_ext); dol_syslog("Function: getContact login=".$authentication['login']." id=".$id." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) $conf->entity = $authentication['entity'];
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
$errorcode = ''; $errorlabel = ''; $errorcode = ''; $errorlabel = '';
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && ($id && $ref_ext)) if (!$error && ($id && $ref_ext))
{ {
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error)
{ {
$fuser->getrights(); $fuser->getrights();
$contact = new Contact($db); $contact = new Contact($db);
$result = $contact->fetch($id, 0, $ref_ext); $result = $contact->fetch($id, 0, $ref_ext);
if ($result > 0) if ($result > 0)
{ {
// Only internal user who have contact read permission // Only internal user who have contact read permission
// Or for external user who have contact read permission, with restrict on societe_id // Or for external user who have contact read permission, with restrict on societe_id
if ( if (
$fuser->rights->societe->contact->lire && !$fuser->societe_id $fuser->rights->societe->contact->lire && !$fuser->societe_id
|| ($fuser->rights->societe->contact->lire && ($fuser->societe_id == $contact->socid)) || ($fuser->rights->societe->contact->lire && ($fuser->societe_id == $contact->socid))
) { ) {
$contact_result_fields = array( $contact_result_fields = array(
'id' => $contact->id, 'id' => $contact->id,
'ref_ext' => $contact->ref_ext, 'ref_ext' => $contact->ref_ext,
'lastname' => $contact->lastname, 'lastname' => $contact->lastname,
'firstname' => $contact->firstname, 'firstname' => $contact->firstname,
'address' => $contact->address, 'address' => $contact->address,
'zip' => $contact->zip, 'zip' => $contact->zip,
'town' => $contact->town, 'town' => $contact->town,
'state_id' => $contact->state_id, 'state_id' => $contact->state_id,
'state_code' => $contact->state_code, 'state_code' => $contact->state_code,
'state' => $contact->state, 'state' => $contact->state,
'country_id' => $contact->country_id, 'country_id' => $contact->country_id,
'country_code' => $contact->country_code, 'country_code' => $contact->country_code,
'country' => $contact->country, 'country' => $contact->country,
'socid' => $contact->socid, 'socid' => $contact->socid,
'status' => $contact->statut, 'status' => $contact->statut,
'phone_pro' => $contact->phone_pro, 'phone_pro' => $contact->phone_pro,
'fax' => $contact->fax, 'fax' => $contact->fax,
'phone_perso' => $contact->phone_perso, 'phone_perso' => $contact->phone_perso,
'phone_mobile' => $contact->phone_mobile, 'phone_mobile' => $contact->phone_mobile,
'code' => $contact->code, 'code' => $contact->code,
'email' => $contact->email, 'email' => $contact->email,
'birthday' => $contact->birthday, 'birthday' => $contact->birthday,
'default_lang' => $contact->default_lang, 'default_lang' => $contact->default_lang,
'note' => $contact->note, 'note' => $contact->note,
'ref_facturation' => $contact->ref_facturation, 'ref_facturation' => $contact->ref_facturation,
'ref_contrat' => $contact->ref_contrat, 'ref_contrat' => $contact->ref_contrat,
'ref_commande' => $contact->ref_commande, 'ref_commande' => $contact->ref_commande,
'ref_propal' => $contact->ref_propal, 'ref_propal' => $contact->ref_propal,
'user_id' => $contact->user_id, 'user_id' => $contact->user_id,
'user_login' => $contact->user_login, 'user_login' => $contact->user_login,
'civility_id' => $contact->civility_id, 'civility_id' => $contact->civility_id,
'poste' => $contact->poste 'poste' => $contact->poste
); );
$elementtype = 'socpeople'; $elementtype = 'socpeople';
//Retrieve all extrafield for thirdsparty //Retrieve all extrafield for thirdsparty
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
//Get extrafield values //Get extrafield values
$contact->fetch_optionals(); $contact->fetch_optionals();
if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label']))
{ {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{ {
$contact_result_fields = array_merge($contact_result_fields, array('options_'.$key => $contact->array_options['options_'.$key])); $contact_result_fields = array_merge($contact_result_fields, array('options_'.$key => $contact->array_options['options_'.$key]));
} }
} }
// Create // Create
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'contact'=>$contact_result_fields 'contact'=>$contact_result_fields
); );
} }
else { else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
else { else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref_ext='.$ref_ext;
} }
} }
if ($error) if ($error)
{ {
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
return $objectresp; return $objectresp;
} }
@ -623,11 +623,11 @@ function updateContact($authentication, $contact)
$error++; $errorcode = 'KO'; $errorlabel = "Contact id or ref_ext is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Contact id or ref_ext is mandatory.";
} }
// Check parameters // Check parameters
if (!$error && ($id && $ref_ext)) if (!$error && ($id && $ref_ext))
{ {
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be all provided. You must choose one of them."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be all provided. You must choose one of them.";
} }
if (!$error) if (!$error)
{ {

File diff suppressed because it is too large Load Diff

View File

@ -34,241 +34,241 @@ require_once DOL_DOCUMENT_ROOT.'/zapier/class/hook.class.php';
*/ */
class ZapierApi extends DolibarrApi class ZapierApi extends DolibarrApi
{ {
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( static $FIELDS = array(
'url', 'url',
); );
/** /**
* @var Hook $hook {@type Hook} * @var Hook $hook {@type Hook}
*/ */
public $hook; public $hook;
/** /**
* Constructor * Constructor
* *
* @url GET / * @url GET /
* *
*/ */
public function __construct() public function __construct()
{ {
global $db, $conf; global $db, $conf;
$this->db = $db; $this->db = $db;
$this->hook = new Hook($this->db); $this->hook = new Hook($this->db);
} }
/** /**
* Get properties of a hook object * Get properties of a hook object
* *
* Return an array with hook informations * Return an array with hook informations
* *
* @param int $id ID of hook * @param int $id ID of hook
* @return array|mixed data without useless information * @return array|mixed data without useless information
* *
* @url GET /hooks/{id} * @url GET /hooks/{id}
* @throws RestException * @throws RestException
*/ */
public function get($id) public function get($id)
{ {
if (!DolibarrApiAccess::$user->rights->zapier->read) { if (!DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401); throw new RestException(401);
} }
$result = $this->hook->fetch($id); $result = $this->hook->fetch($id);
if (!$result) { if (!$result) {
throw new RestException(404, 'Hook not found'); throw new RestException(404, 'Hook not found');
} }
if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) { if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
return $this->_cleanObjectDatas($this->hook); return $this->_cleanObjectDatas($this->hook);
} }
/** /**
* Get list of possibles choices for module * Get list of possibles choices for module
* *
* Return an array with hook informations * Return an array with hook informations
* @param integer $id ID * @param integer $id ID
* *
* @return array|mixed data * @return array|mixed data
* *
* @url GET /getmoduleschoices/ * @url GET /getmoduleschoices/
* @throws RestException * @throws RestException
*/ */
public function getModulesChoices($id) public function getModulesChoices($id)
{ {
if (!DolibarrApiAccess::$user->rights->zapier->read) { if (!DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401); throw new RestException(401);
} }
$arraychoices = array( $arraychoices = array(
'invoices' => 'Invoices', 'invoices' => 'Invoices',
'orders' => 'Orders', 'orders' => 'Orders',
'thirdparties' => 'Thirparties', 'thirdparties' => 'Thirparties',
'contacts' => 'Contacts', 'contacts' => 'Contacts',
); );
// $result = $this->hook->fetch($id); // $result = $this->hook->fetch($id);
// if (! $result ) { // if (! $result ) {
// throw new RestException(404, 'Hook not found'); // throw new RestException(404, 'Hook not found');
// } // }
// if (! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) { // if (! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
// throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); // throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
// } // }
return $arraychoices; return $arraychoices;
} }
/** /**
* List hooks * List hooks
* *
* Get a list of hooks * Get a list of hooks
* *
* @param string $sortfield Sort field * @param string $sortfield Sort field
* @param string $sortorder Sort order * @param string $sortorder Sort order
* @param int $limit Limit for list * @param int $limit Limit for list
* @param int $page Page number * @param int $page Page number
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
* @return array Array of order objects * @return array Array of order objects
* *
* @throws RestException * @throws RestException
* *
* @url GET /hooks/ * @url GET /hooks/
*/ */
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{ {
global $db, $conf; global $db, $conf;
$obj_ret = array(); $obj_ret = array();
$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : ''; $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
// Set to 1 if there is a field socid in table of object // Set to 1 if there is a field socid in table of object
$restrictonsocid = 0; $restrictonsocid = 0;
// If the internal user must only see his customers, force searching by him // If the internal user must only see his customers, force searching by him
$search_sale = 0; $search_sale = 0;
if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
$search_sale = DolibarrApiAccess::$user->id; $search_sale = DolibarrApiAccess::$user->id;
} }
$sql = "SELECT t.rowid"; $sql = "SELECT t.rowid";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
// We need these fields in order to filter by sale (including the case where the user can only see his prospects) // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql .= ", sc.fk_soc, sc.fk_user"; $sql .= ", sc.fk_soc, sc.fk_user";
} }
$sql .= " FROM ".MAIN_DB_PREFIX."hook_mytable as t"; $sql .= " FROM ".MAIN_DB_PREFIX."hook_mytable as t";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
$sql .= " WHERE 1 = 1"; $sql .= " WHERE 1 = 1";
// Example of use $mode // Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; //if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; //if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
$tmpobject = new Hook($this->db); $tmpobject = new Hook($this->db);
if ($tmpobject->ismultientitymanaged) { if ($tmpobject->ismultientitymanaged) {
$sql .= ' AND t.entity IN ('.getEntity('hook').')'; $sql .= ' AND t.entity IN ('.getEntity('hook').')';
} }
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= " AND t.fk_soc = sc.fk_soc"; $sql .= " AND t.fk_soc = sc.fk_soc";
} }
if ($restrictonsocid && $socid) { if ($restrictonsocid && $socid) {
$sql .= " AND t.fk_soc = ".$socid; $sql .= " AND t.fk_soc = ".$socid;
} }
if ($restrictonsocid && $search_sale > 0) { if ($restrictonsocid && $search_sale > 0) {
// Join for the needed table to filter by sale // Join for the needed table to filter by sale
$sql .= " AND t.rowid = sc.fk_soc"; $sql .= " AND t.rowid = sc.fk_soc";
} }
// Insert sale filter // Insert sale filter
if ($restrictonsocid && $search_sale > 0) { if ($restrictonsocid && $search_sale > 0) {
$sql .= " AND sc.fk_user = ".$search_sale; $sql .= " AND sc.fk_user = ".$search_sale;
} }
if ($sqlfilters) { if ($sqlfilters) {
if (!DolibarrApi::_checkFilters($sqlfilters)) { if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
} }
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) { if ($page < 0) {
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset); $sql .= $this->db->plimit($limit + 1, $offset);
} }
$result = $this->db->query($sql); $result = $this->db->query($sql);
$i = 0; $i = 0;
if ($result) { if ($result) {
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
while ($i < $num) { while ($i < $num) {
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$hook_static = new Hook($this->db); $hook_static = new Hook($this->db);
if ($hook_static->fetch($obj->rowid)) { if ($hook_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($hook_static); $obj_ret[] = $this->_cleanObjectDatas($hook_static);
} }
$i++; $i++;
} }
} else { } else {
throw new RestException(503, 'Error when retrieve hook list'); throw new RestException(503, 'Error when retrieve hook list');
} }
if (!count($obj_ret)) { if (!count($obj_ret)) {
throw new RestException(404, 'No hook found'); throw new RestException(404, 'No hook found');
} }
return $obj_ret; return $obj_ret;
} }
/** /**
* Create hook object * Create hook object
* *
* @param array $request_data Request datas * @param array $request_data Request datas
* @return int ID of hook * @return int ID of hook
* *
* @url POST /hook/ * @url POST /hook/
*/ */
public function post($request_data = null) public function post($request_data = null)
{ {
if (!DolibarrApiAccess::$user->rights->zapier->write) { if (!DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401); throw new RestException(401);
} }
// Check mandatory fields // Check mandatory fields
$fields = array( $fields = array(
'url', 'url',
); );
$result = $this->validate($request_data, $fields); $result = $this->validate($request_data, $fields);
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
$this->hook->$field = $value; $this->hook->$field = $value;
} }
$this->hook->fk_user = DolibarrApiAccess::$user->id; $this->hook->fk_user = DolibarrApiAccess::$user->id;
// on crée le hook dans la base // on crée le hook dans la base
if (!$this->hook->create(DolibarrApiAccess::$user)) { if (!$this->hook->create(DolibarrApiAccess::$user)) {
throw new RestException(500, "Error creating Hook", array_merge(array($this->hook->error), $this->hook->errors)); throw new RestException(500, "Error creating Hook", array_merge(array($this->hook->error), $this->hook->errors));
} }
return array( return array(
'id' => $this->hook->id, 'id' => $this->hook->id,
); );
} }
// /** // /**
// * Update hook // * Update hook
// * // *
// * @param int $id Id of hook to update // * @param int $id Id of hook to update
// * @param array $request_data Datas // * @param array $request_data Datas
// * @return int // * @return int
// * // *
// * @url PUT /hooks/{id} // * @url PUT /hooks/{id}
// */ // */
/*public function put($id, $request_data = null) /*public function put($id, $request_data = null)
{ {
if (! DolibarrApiAccess::$user->rights->zapier->write) { if (! DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401); throw new RestException(401);
@ -297,80 +297,80 @@ class ZapierApi extends DolibarrApi
} }
}*/ }*/
/** /**
* Delete hook * Delete hook
* *
* @param int $id Hook ID * @param int $id Hook ID
* @return array * @return array
* *
* @url DELETE /hook/{id} * @url DELETE /hook/{id}
*/ */
public function delete($id) public function delete($id)
{ {
if (!DolibarrApiAccess::$user->rights->zapier->delete) { if (!DolibarrApiAccess::$user->rights->zapier->delete) {
throw new RestException(401); throw new RestException(401);
} }
$result = $this->hook->fetch($id); $result = $this->hook->fetch($id);
if (!$result) { if (!$result) {
throw new RestException(404, 'Hook not found'); throw new RestException(404, 'Hook not found');
} }
if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) { if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
if (!$this->hook->delete(DolibarrApiAccess::$user)) { if (!$this->hook->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when deleting Hook : '.$this->hook->error); throw new RestException(500, 'Error when deleting Hook : '.$this->hook->error);
} }
return array( return array(
'success' => array( 'success' => array(
'code' => 200, 'code' => 200,
'message' => 'Hook deleted' 'message' => 'Hook deleted'
) )
); );
} }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/** /**
* Clean sensible object datas * Clean sensible object datas
* *
* @param object $object Object to clean * @param object $object Object to clean
* @return array Array of cleaned object properties * @return array Array of cleaned object properties
*/ */
public function _cleanObjectDatas($object) public function _cleanObjectDatas($object)
{ {
// phpcs:disable // phpcs:disable
$object = parent::_cleanObjectDatas($object); $object = parent::_cleanObjectDatas($object);
/*unset($object->note); /*unset($object->note);
unset($object->address); unset($object->address);
unset($object->barcode_type); unset($object->barcode_type);
unset($object->barcode_type_code); unset($object->barcode_type_code);
unset($object->barcode_type_label); unset($object->barcode_type_label);
unset($object->barcode_type_coder);*/ unset($object->barcode_type_coder);*/
return $object; return $object;
} }
/** /**
* Validate fields before create or update object * Validate fields before create or update object
* *
* @param array $data Array of data to validate * @param array $data Array of data to validate
* @param array $fields Array of fields needed * @param array $fields Array of fields needed
* @return array * @return array
* *
* @throws RestException * @throws RestException
*/ */
private function validate($data, $fields) private function validate($data, $fields)
{ {
$hook = array(); $hook = array();
foreach ($fields as $field) { foreach ($fields as $field) {
if (!isset($data[$field])) { if (!isset($data[$field])) {
throw new RestException(400, $field." field missing"); throw new RestException(400, $field." field missing");
} }
$hook[$field] = $data[$field]; $hook[$field] = $data[$field];
} }
return $hook; return $hook;
} }
} }

View File

@ -53,8 +53,8 @@ $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : (int) GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : (int) GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
// If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
@ -76,19 +76,19 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) { if (!$sortfield) {
// Set here default search field. By default 1st field in definition. // Set here default search field. By default 1st field in definition.
$sortfield = "t.".key($object->fields); $sortfield = "t.".key($object->fields);
} }
if (!$sortorder) { if (!$sortorder) {
$sortorder = "ASC"; $sortorder = "ASC";
} }
// Security check // Security check
$socid = 0; $socid = 0;
if ($user->socid > 0) { if ($user->socid > 0) {
// Protection if external user // Protection if external user
//$socid = $user->socid; //$socid = $user->socid;
accessforbidden(); accessforbidden();
} }
//$result = restrictedArea($user, 'zapier', $id, ''); //$result = restrictedArea($user, 'zapier', $id, '');
@ -96,27 +96,27 @@ if ($user->socid > 0) {
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha');
} }
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array(); $fieldstosearchall = array();
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
} }
// Definition of fields for list // Definition of fields for list
$arrayfields = array(); $arrayfields = array();
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
// If $val['visible']==0, then we never show the field // If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']);
} }
// Extra fields // Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) if (!empty($extrafields->attributes[$object->table_element]['list'][$key]))
$arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
} }
} }
$object->fields = dol_sort_array($object->fields, 'position'); $object->fields = dol_sort_array($object->fields, 'position');
$arrayfields = dol_sort_array($arrayfields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position');
@ -128,11 +128,11 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
*/ */
if (GETPOST('cancel', 'alpha')) { if (GETPOST('cancel', 'alpha')) {
$action = 'list'; $action = 'list';
$massaction = ''; $massaction = '';
} }
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = ''; $massaction = '';
} }
$parameters = array(); $parameters = array();
@ -140,30 +140,30 @@ $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook)) { if (empty($reshook)) {
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
// All tests are required to be compatible with all browsers // All tests are required to be compatible with all browsers
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
$search[$key] = ''; $search[$key] = '';
} }
$toselect = ''; $toselect = '';
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
// Mass actions // Mass actions
$objectclass = 'Hook'; $objectclass = 'Hook';
$objectlabel = 'Hook'; $objectlabel = 'Hook';
$permissiontoread = $user->rights->zapier->read; $permissiontoread = $user->rights->zapier->read;
$permissiontodelete = $user->rights->zapier->delete; $permissiontodelete = $user->rights->zapier->delete;
$uploaddir = $conf->zapier->dir_output; $uploaddir = $conf->zapier->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
} }
@ -185,13 +185,13 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Hooks"));
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$sql = 'SELECT '; $sql = 'SELECT ';
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
$sql .= 't.'.$key.', '; $sql .= 't.'.$key.', ';
} }
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
} }
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@ -201,21 +201,21 @@ $sql = preg_replace('/, $/', '', $sql);
$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
if ($object->ismultientitymanaged == 1) { if ($object->ismultientitymanaged == 1) {
$sql .= " WHERE t.entity IN (".getEntity($object->element).")"; $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
} else { } else {
$sql .= " WHERE 1 = 1"; $sql .= " WHERE 1 = 1";
} }
foreach ($search as $key => $val) { foreach ($search as $key => $val) {
if ($key == 'status' && $search[$key] == -1) { if ($key == 'status' && $search[$key] == -1) {
continue; continue;
} }
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if ($search[$key] != '') { if ($search[$key] != '') {
$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
} }
} }
if ($search_all) { if ($search_all) {
$sql .= natural_search(array_keys($fieldstosearchall), $search_all); $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
} }
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@ -245,35 +245,35 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) { if (($page * $limit) > $nbtotalofrecords) {
// if total of record found is smaller than page * limit, goto and load page 0 // if total of record found is smaller than page * limit, goto and load page 0
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) { if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) {
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) { if (!$resql) {
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) {
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".dol_buildpath('/zapierfordolibarr/hook_card.php', 1).'?id='.$id); header("Location: ".dol_buildpath('/zapierfordolibarr/hook_card.php', 1).'?id='.$id);
exit; exit;
} }
@ -303,13 +303,13 @@ $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
foreach ($search as $key => $val) { foreach ($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) { if (is_array($search[$key]) && count($search[$key])) {
foreach ($search[$key] as $skey) { foreach ($search[$key] as $skey) {
$param .= '&search_'.$key.'[]='.urlencode($skey); $param .= '&search_'.$key.'[]='.urlencode($skey);
} }
} else { } else {
$param .= '&search_'.$key.'='.urlencode($search[$key]); $param .= '&search_'.$key.'='.urlencode($search[$key]);
} }
} }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
// Add $param from extra fields // Add $param from extra fields
@ -317,8 +317,8 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
// List of mass actions available // List of mass actions available
$arrayofmassactions = array( $arrayofmassactions = array(
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
); );
if ($user->rights->zapier->delete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($user->rights->zapier->delete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
@ -337,9 +337,9 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
$newcardbutton = ''; $newcardbutton = '';
//if ($user->rights->zapier->creer) //if ($user->rights->zapier->creer)
//{ //{
$newcardbutton = '<a class="butActionNew" href="hook_card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']).'"><span class="valignmiddle text-plus-circle">'.$langs->trans('New').'</span>'; $newcardbutton = '<a class="butActionNew" href="hook_card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']).'"><span class="valignmiddle text-plus-circle">'.$langs->trans('New').'</span>';
$newcardbutton .= '<span class="fa fa-plus-circle valignmiddle"></span>'; $newcardbutton .= '<span class="fa fa-plus-circle valignmiddle"></span>';
$newcardbutton .= '</a>'; $newcardbutton .= '</a>';
//} //}
//else //else
//{ //{
@ -358,8 +358,8 @@ $trackid = 'xxxx'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) { if ($sall) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
$moreforfilter = ''; $moreforfilter = '';
@ -373,9 +373,9 @@ if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
else $moreforfilter = $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint;
if (!empty($moreforfilter)) { if (!empty($moreforfilter)) {
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
} }
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
@ -390,22 +390,22 @@ print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" :
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
$cssforfield = ''; $cssforfield = '';
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} }
if (in_array($val['type'], array('timestamp'))) { if (in_array($val['type'], array('timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} }
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) { if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'right';
} }
if ($key == 'status') { if ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} }
if (!empty($arrayfields['t.'.$key]['checked'])) { if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>';
} }
} }
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
@ -426,25 +426,25 @@ print '</tr>'."\n";
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
$cssforfield = ''; $cssforfield = '';
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right';
if ($key == 'status') { if ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} }
if (!empty($arrayfields['t.'.$key]['checked'])) { if (!empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
} }
} }
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
// Hook fields // Hook fields
$parameters = array( $parameters = array(
'arrayfields' => $arrayfields, 'arrayfields' => $arrayfields,
'param' => $param, 'param' => $param,
'sortfield' => $sortfield, 'sortfield' => $sortfield,
'sortorder' => $sortorder, 'sortorder' => $sortorder,
); );
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
@ -456,12 +456,12 @@ print '</tr>'."\n";
// Detect if we need a fetch on each output line // Detect if we need a fetch on each output line
$needToFetchEachLine = 0; $needToFetchEachLine = 0;
if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
if (preg_match('/\$object/', $val)) { if (preg_match('/\$object/', $val)) {
// There is at least one compute field that use $object // There is at least one compute field that use $object
$needToFetchEachLine++; $needToFetchEachLine++;
} }
} }
} }
@ -470,71 +470,71 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < min($num, $limit)) { while ($i < min($num, $limit)) {
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (empty($obj)) { if (empty($obj)) {
break; // Should not happen break; // Should not happen
} }
// Store properties in $object // Store properties in $object
$object->id = $obj->rowid; $object->id = $obj->rowid;
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
if (isset($obj->$key)) $object->$key = $obj->$key; if (isset($obj->$key)) $object->$key = $obj->$key;
} }
// Show here line of result // Show here line of result
print '<tr class="oddeven">'; print '<tr class="oddeven">';
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
$cssforfield = ''; $cssforfield = '';
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif ($key == 'status') { } elseif ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} }
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right';
if (!empty($arrayfields['t.'.$key]['checked'])) { if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td'; print '<td';
if ($cssforfield || $val['css']) print ' class="'; if ($cssforfield || $val['css']) print ' class="';
print $cssforfield; print $cssforfield;
if ($cssforfield && $val['css']) print ' '; if ($cssforfield && $val['css']) print ' ';
print $val['css']; print $val['css'];
if ($cssforfield || $val['css']) print '"'; if ($cssforfield || $val['css']) print '"';
print '>'; print '>';
if ($key == 'status') print $object->getLibStatut(5); if ($key == 'status') print $object->getLibStatut(5);
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), '');
else print $object->showOutputField($val, $key, $obj->$key, ''); else print $object->showOutputField($val, $key, $obj->$key, '');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['nbfield']++;
if (!empty($val['isameasure'])) { if (!empty($val['isameasure'])) {
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
$totalarray['val']['t.'.$key] += $obj->$key; $totalarray['val']['t.'.$key] += $obj->$key;
} }
} }
} }
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
// Fields from hook // Fields from hook
$parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) { if ($massactionbutton || $massaction) {
// If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['nbfield']++;
print '</tr>'; print '</tr>';
$i++; $i++;
} }
// Show total line // Show total line
@ -543,21 +543,21 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) { if ($num == 0) {
$colspan = 1; $colspan = 1;
foreach ($arrayfields as $key => $val) { foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) { if (!empty($val['checked'])) {
$colspan++; $colspan++;
} }
} }
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }
$db->free($resql); $db->free($resql);
$parameters = array( $parameters = array(
'arrayfields' => $arrayfields, 'arrayfields' => $arrayfields,
'sql' => $sql, 'sql' => $sql,
); );
$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
@ -568,23 +568,23 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0; $hidegeneratedfilelistifempty = 0;
} }
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);
// Show list of available documents // Show list of available documents
$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
$urlsource .= str_replace('&amp;', '&', $param); $urlsource .= str_replace('&amp;', '&', $param);
$filedir = $diroutputmassaction; $filedir = $diroutputmassaction;
$genallowed = $user->rights->zapier->read; $genallowed = $user->rights->zapier->read;
$delallowed = $user->rights->zapier->create; $delallowed = $user->rights->zapier->create;
print $formfile->showdocuments('massfilesarea_zapier', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); print $formfile->showdocuments('massfilesarea_zapier', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
} }
// End of page // End of page