Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop

This commit is contained in:
Laurent Destailleur 2020-10-27 19:57:52 +01:00
commit 6e0ae82048
33 changed files with 6112 additions and 6112 deletions

View File

@ -76,26 +76,26 @@ $defaultdelay = 1;
$defaultdelayunit = 'y';
if ($rowid) {
// Load member
$result = $object->fetch($rowid);
// Load member
$result = $object->fetch($rowid);
// Define variables to know what current user can do on users
$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
if ($object->user_id) {
// $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)
|| (($user->id != $object->user_id) && $user->rights->user->user->creer));
$caneditpassworduser = ((($user->id == $object->user_id) && $user->rights->user->self->password)
|| (($user->id != $object->user_id) && $user->rights->user->user->password));
}
// Define variables to know what current user can do on users
$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
if ($object->user_id) {
// $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)
|| (($user->id != $object->user_id) && $user->rights->user->user->creer));
$caneditpassworduser = ((($user->id == $object->user_id) && $user->rights->user->self->password)
|| (($user->id != $object->user_id) && $user->rights->user->user->password));
}
}
// Define variables to know what current user can do on members
$canaddmember = $user->rights->adherent->creer;
// Define variables to know what current user can do on properties of a member
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
@ -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)) {
$error = 0;
if (empty($user->rights->user->user->creer)) { // If can edit only itself user, we can link to itself only
$error = 0;
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) {
$error++;
setEventMessages($langs->trans("ErrorUserPermissionAllowsToLinksToItselfOnly"), null, 'errors');
$error++;
setEventMessages($langs->trans("ErrorUserPermissionAllowsToLinksToItselfOnly"), null, 'errors');
}
}
}
if (!$error) {
if ($_POST["userid"] != $object->user_id) { // If link differs from currently in database
if (!$error) {
if ($_POST["userid"] != $object->user_id) { // If link differs from currently in database
$result = $object->setUserId($_POST["userid"]);
if ($result < 0) dol_print_error('', $object->error);
$_POST['action'] = '';
$action = '';
}
}
if ($result < 0) dol_print_error('', $object->error);
$_POST['action'] = '';
$action = '';
}
}
}
if ($action == 'setsocid') {
$error = 0;
if (!$error) {
if (GETPOST('socid', 'int') != $object->fk_soc) { // If link differs from currently in database
$error = 0;
if (!$error) {
if (GETPOST('socid', 'int') != $object->fk_soc) { // If link differs from currently in database
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
$sql .= " WHERE fk_soc = '".GETPOST('socid', 'int')."'";
$resql = $db->query($sql);
if ($resql) {
$obj = $db->fetch_object($resql);
if ($obj && $obj->rowid > 0) {
$othermember = new Adherent($db);
$othermember->fetch($obj->rowid);
$thirdparty = new Societe($db);
$thirdparty->fetch(GETPOST('socid', 'int'));
$error++;
setEventMessages($langs->trans("ErrorMemberIsAlreadyLinkedToThisThirdParty", $othermember->getFullName($langs), $othermember->login, $thirdparty->name), null, 'errors');
}
}
$sql .= " WHERE fk_soc = '".GETPOST('socid', 'int')."'";
$resql = $db->query($sql);
if ($resql) {
$obj = $db->fetch_object($resql);
if ($obj && $obj->rowid > 0) {
$othermember = new Adherent($db);
$othermember->fetch($obj->rowid);
$thirdparty = new Societe($db);
$thirdparty->fetch(GETPOST('socid', 'int'));
$error++;
setEventMessages($langs->trans("ErrorMemberIsAlreadyLinkedToThisThirdParty", $othermember->getFullName($langs), $othermember->login, $thirdparty->name), null, 'errors');
}
}
if (!$error) {
$result = $object->setThirdPartyId(GETPOST('socid', 'int'));
if ($result < 0) dol_print_error('', $object->error);
$_POST['action'] = '';
$action = '';
}
}
}
if (!$error) {
$result = $object->setThirdPartyId(GETPOST('socid', 'int'));
if ($result < 0) dol_print_error('', $object->error);
$_POST['action'] = '';
$action = '';
}
}
}
}
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 = $adht->fetch($object->typeid);
$result = $object->fetch($rowid);
$result = $adht->fetch($object->typeid);
// Subscription informations
$datesubscription = 0;
$datesubend = 0;
$paymentdate = 0;
if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"]) {
$datesubscription = dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
}
if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"]) {
$datesubend = dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]);
}
if ($_POST["paymentyear"] && $_POST["paymentmonth"] && $_POST["paymentday"]) {
$paymentdate = dol_mktime(0, 0, 0, $_POST["paymentmonth"], $_POST["paymentday"], $_POST["paymentyear"]);
}
$amount = price2num(GETPOST("subscription", 'alpha')); // Amount of subscription
$label = $_POST["label"];
// Subscription informations
$datesubscription = 0;
$datesubend = 0;
$paymentdate = 0;
if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"]) {
$datesubscription = dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
}
if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"]) {
$datesubend = dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]);
}
if ($_POST["paymentyear"] && $_POST["paymentmonth"] && $_POST["paymentday"]) {
$paymentdate = dol_mktime(0, 0, 0, $_POST["paymentmonth"], $_POST["paymentday"], $_POST["paymentyear"]);
}
$amount = price2num(GETPOST("subscription", 'alpha')); // Amount of subscription
$label = $_POST["label"];
// Payment informations
$accountid = $_POST["accountid"];
$operation = $_POST["operation"]; // Payment mode
$num_chq = GETPOST("num_chq", "alphanohtml");
$emetteur_nom = $_POST["chqemetteur"];
$emetteur_banque = $_POST["chqbank"];
$option = $_POST["paymentsave"];
if (empty($option)) $option = 'none';
$sendalsoemail = GETPOST("sendmail", 'alpha');
// Payment informations
$accountid = $_POST["accountid"];
$operation = $_POST["operation"]; // Payment mode
$num_chq = GETPOST("num_chq", "alphanohtml");
$emetteur_nom = $_POST["chqemetteur"];
$emetteur_banque = $_POST["chqbank"];
$option = $_POST["paymentsave"];
if (empty($option)) $option = 'none';
$sendalsoemail = GETPOST("sendmail", 'alpha');
// Check parameters
if (!$datesubscription) {
$error++;
$langs->load("errors");
$errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateSubscription"));
setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription';
}
if (GETPOST('end') && !$datesubend) {
$error++;
$langs->load("errors");
$errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateEndSubscription"));
setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription';
}
if (!$datesubend) {
$datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd');
}
if (($option == 'bankviainvoice' || $option == 'bankdirect') && !$paymentdate) {
$error++;
$errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment"));
setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription';
}
// Check parameters
if (!$datesubscription) {
$error++;
$langs->load("errors");
$errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateSubscription"));
setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription';
}
if (GETPOST('end') && !$datesubend) {
$error++;
$langs->load("errors");
$errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateEndSubscription"));
setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription';
}
if (!$datesubend) {
$datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd');
}
if (($option == 'bankviainvoice' || $option == 'bankdirect') && !$paymentdate) {
$error++;
$errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment"));
setEventMessages($errmsg, null, 'errors');
$action = 'addsubscription';
}
// Check if a payment is mandatory or not
if (!$error && $adht->subscription) { // Member type need subscriptions
// Check if a payment is mandatory or not
if (!$error && $adht->subscription) { // Member type need subscriptions
if (!is_numeric($amount)) {
// If field is '' or not a numeric value
$errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount"));
setEventMessages($errmsg, null, 'errors');
$error++;
$action = 'addsubscription';
// If field is '' or not a numeric value
$errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount"));
setEventMessages($errmsg, null, 'errors');
$error++;
$action = 'addsubscription';
} else {
if (!empty($conf->banque->enabled) && $_POST["paymentsave"] != 'none') {
if ($_POST["subscription"]) {
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["accountid"] > 0)) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("FinancialAccount"));
} else {
if ($_POST["accountid"]) $errmsg = $langs->trans("ErrorDoNotProvideAccountsIfNullAmount");
}
if ($errmsg) {
$error++;
setEventMessages($errmsg, null, 'errors');
$error++;
$action = 'addsubscription';
}
}
}
}
if (!empty($conf->banque->enabled) && $_POST["paymentsave"] != 'none') {
if ($_POST["subscription"]) {
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["accountid"] > 0)) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("FinancialAccount"));
} else {
if ($_POST["accountid"]) $errmsg = $langs->trans("ErrorDoNotProvideAccountsIfNullAmount");
}
if ($errmsg) {
$error++;
setEventMessages($errmsg, null, 'errors');
$error++;
$action = 'addsubscription';
}
}
}
}
// Record the subscription then complementary actions
if (!$error && $action == 'subscription') {
$db->begin();
// Record the subscription then complementary actions
if (!$error && $action == 'subscription') {
$db->begin();
// Create subscription
$crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend);
if ($crowid <= 0) {
$error++;
$errmsg = $object->error;
setEventMessages($object->error, $object->errors, 'errors');
}
// Create subscription
$crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend);
if ($crowid <= 0) {
$error++;
$errmsg = $object->error;
setEventMessages($object->error, $object->errors, 'errors');
}
if (!$error) {
$result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque);
if (!$error) {
$result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque);
if ($result < 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
} else {
// If an invoice was created, it is into $object->invoice
}
}
}
if (!$error) {
$db->commit();
} else {
$db->rollback();
$action = 'addsubscription';
}
if (!$error) {
$db->commit();
} else {
$db->rollback();
$action = 'addsubscription';
}
if (!$error) {
setEventMessages("SubscriptionRecorded", null, 'mesgs');
}
if (!$error) {
setEventMessages("SubscriptionRecorded", null, 'mesgs');
}
// Send email
if (!$error) {
// Send confirmation Email
if ($object->email && $sendalsoemail) { // $object is 'Adherent'
// Send email
if (!$error) {
// Send confirmation Email
if ($object->email && $sendalsoemail) { // $object is 'Adherent'
$subject = '';
$msg = '';
$msg = '';
// Send subscription email
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
// Set output language
$outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
// Load traductions files required by page
$outputlangs->loadLangs(array("main", "members"));
// Send subscription email
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
// Set output language
$outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
// Load traductions files required by page
$outputlangs->loadLangs(array("main", "members"));
// Get email content from template
$arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
// Get email content from template
$arraydefaultmessage = null;
$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) {
$subject = $arraydefaultmessage->topic;
$msg = $arraydefaultmessage->content;
}
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic;
$msg = $arraydefaultmessage->content;
}
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
complete_substitutions_array($substitutionarray, $outputlangs, $object);
$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
complete_substitutions_array($substitutionarray, $outputlangs, $object);
$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
// Attach a file ?
$file = '';
$listofpaths = array();
$listofnames = array();
$listofmimes = array();
if (is_object($object->invoice)) {
$invoicediroutput = $conf->facture->dir_output;
$fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
$file = $fileparams['fullname'];
// Attach a file ?
$file = '';
$listofpaths = array();
$listofnames = array();
$listofmimes = array();
if (is_object($object->invoice)) {
$invoicediroutput = $conf->facture->dir_output;
$fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
$file = $fileparams['fullname'];
$listofpaths = array($file);
$listofnames = array(basename($file));
$listofmimes = array(dol_mimetype($file));
}
$listofpaths = array($file);
$listofnames = array(basename($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);
if ($result < 0) {
$errmsg = $object->error;
setEventMessages($object->error, $object->errors, 'errors');
} else {
setEventMessages($langs->trans("EmailSentToMember", $object->email), null, 'mesgs');
}
} else {
setEventMessages($langs->trans("NoEmailSentToMember"), null, 'mesgs');
}
}
$result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, '', $moreinheader);
if ($result < 0) {
$errmsg = $object->error;
setEventMessages($object->error, $object->errors, 'errors');
} else {
setEventMessages($langs->trans("EmailSentToMember", $object->email), null, 'mesgs');
}
} else {
setEventMessages($langs->trans("NoEmailSentToMember"), null, 'mesgs');
}
}
// Clean some POST vars
if (!$error) {
$_POST["subscription"] = '';
$_POST["accountid"] = '';
$_POST["operation"] = '';
$_POST["label"] = '';
$_POST["num_chq"] = '';
}
}
// Clean some POST vars
if (!$error) {
$_POST["subscription"] = '';
$_POST["accountid"] = '';
$_POST["operation"] = '';
$_POST["label"] = '';
$_POST["num_chq"] = '';
}
}
}
@ -393,32 +393,32 @@ if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
if ($rowid > 0) {
$res = $object->fetch($rowid);
if ($res < 0) { dol_print_error($db, $object->error); exit; }
$res = $object->fetch($rowid);
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;
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++;
if (!empty($conf->societe->enabled)) $rowspan++;
$rowspan = 10;
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++;
if (!empty($conf->societe->enabled)) $rowspan++;
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="rowid" value="'.$object->id.'">';
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">';
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="fichehalfleft">';
print '<div class="fichecenter">';
print '<div class="fichehalfleft">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent tableforfield">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent tableforfield">';
// Login
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
@ -443,20 +443,20 @@ if ($rowid > 0) {
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
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)) {
$langs->load("errors");
$htmltext = $langs->trans("WarningPasswordSetWithNoAccount");
print ' '.$form->textwithpicto('', $htmltext, 1, 'warning');
$langs->load("errors");
$htmltext = $langs->trans("WarningPasswordSetWithNoAccount");
print ' '.$form->textwithpicto('', $htmltext, 1, 'warning');
}
print '</td></tr>';
}
print '</table>';
print '</table>';
print '</div>';
print '<div class="fichehalfright"><div class="ficheaddleft">';
print '</div>';
print '<div class="fichehalfright"><div class="ficheaddleft">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield" width="100%">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield" width="100%">';
// Birthday
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>';
}
// Other attributes
$cols = 2;
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
// Other attributes
$cols = 2;
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
// Date end subscription
print '<tr><td>'.$langs->trans("SubscriptionEndDate").'</td><td class="valeur">';
if ($object->datefin) {
print dol_print_date($object->datefin, 'day');
if ($object->hasDelay()) {
print " ".img_warning($langs->trans("Late"));
}
print dol_print_date($object->datefin, 'day');
if ($object->hasDelay()) {
print " ".img_warning($langs->trans("Late"));
}
} else {
if (!$adht->subscription) {
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
} else {
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 (!$adht->subscription) {
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
} else {
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
}
}
print '</td></tr>';
@ -660,71 +660,71 @@ if ($rowid > 0) {
$accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
}
$accountstatic->ref = $objp->ref;
print $accountstatic->getNomUrl(1);
} else {
print '&nbsp;';
}
print '</td>';
}
print "</tr>";
$i++;
}
$accountstatic->ref = $objp->ref;
print $accountstatic->getNomUrl(1);
} else {
print '&nbsp;';
}
print '</td>';
}
print "</tr>";
$i++;
}
if (empty($num)) {
$colspan = 6;
if (!empty($conf->banque->enabled)) $colspan++;
print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
}
if (empty($num)) {
$colspan = 6;
if (!empty($conf->banque->enabled)) $colspan++;
print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
}
print "</table>";
} else {
dol_print_error($db);
}
}
print "</table>";
} else {
dol_print_error($db);
}
}
if (($action != 'addsubscription' && $action != 'create_thirdparty')) {
// Shon online payment link
$useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled));
if (($action != 'addsubscription' && $action != 'create_thirdparty')) {
// Shon online payment link
$useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled));
if ($useonlinepayment) {
print '<br>';
if ($useonlinepayment) {
print '<br>';
require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
print showOnlinePaymentUrl('membersubscription', $object->ref);
print '<br>';
}
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
print showOnlinePaymentUrl('membersubscription', $object->ref);
print '<br>';
}
}
/*
/*
* Add new subscription form
*/
if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->rights->adherent->cotisation->creer) {
print '<br>';
if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->rights->adherent->cotisation->creer) {
print '<br>';
print load_fiche_titre($langs->trans("NewCotisation"));
print load_fiche_titre($langs->trans("NewCotisation"));
// Define default choice for complementary actions
$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
$bankviainvoice = 0; // 1 means option by default is write to bank via invoice
if (GETPOST('paymentsave')) {
if (GETPOST('paymentsave') == 'bankdirect') $bankdirect = 1;
if (GETPOST('paymentsave') == 'invoiceonly') $invoiceonly = 1;
if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice = 1;
} 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;
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;
}
// Define default choice for complementary actions
$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
$bankviainvoice = 0; // 1 means option by default is write to bank via invoice
if (GETPOST('paymentsave')) {
if (GETPOST('paymentsave') == 'bankdirect') $bankdirect = 1;
if (GETPOST('paymentsave') == 'invoiceonly') $invoiceonly = 1;
if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice = 1;
} 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;
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;
}
print "\n\n<!-- Form add subscription -->\n";
print "\n\n<!-- Form add subscription -->\n";
if ($conf->use_javascript_ajax) {
//var_dump($bankdirect.'-'.$bankviainvoice.'-'.$invoiceonly.'-'.empty($conf->global->ADHERENT_BANK_USE));
print "\n".'<script type="text/javascript" language="javascript">';
print '$(document).ready(function () {
if ($conf->use_javascript_ajax) {
//var_dump($bankdirect.'-'.$bankviainvoice.'-'.$invoiceonly.'-'.empty($conf->global->ADHERENT_BANK_USE));
print "\n".'<script type="text/javascript" language="javascript">';
print '$(document).ready(function () {
$(".bankswitchclass, .bankswitchclass2").'.(($bankdirect || $bankviainvoice) ? 'show()' : 'hide()').';
$("#none, #invoiceonly").click(function() {
$(".bankswitchclass").hide();
@ -750,10 +750,10 @@ if ($rowid > 0) {
}
});
';
if (GETPOST('paymentsave')) print '$("#'.GETPOST('paymentsave').'").prop("checked",true);';
print '});';
print '</script>'."\n";
}
if (GETPOST('paymentsave')) print '$("#'.GETPOST('paymentsave').'").prop("checked",true);';
print '});';
print '</script>'."\n";
}
// Confirm create third party
@ -778,16 +778,16 @@ if ($rowid > 0) {
if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED)) {
$tmpcompany = new Societe($db);
$tmpcompany->name = $companyname;
$tmpcompany->get_codeclient($tmpcompany, 0);
$tmpcompany->get_codeclient($tmpcompany, 0);
$customercode = $tmpcompany->code_client;
$formquestion[] = array(
'label' => $langs->trans("CustomerCode"),
'type' => 'text',
'name' => 'customercode',
'value' => $customercode,
'morecss' => 'minwidth300',
'moreattr' => 'maxlength="128"',
);
'label' => $langs->trans("CustomerCode"),
'type' => 'text',
'name' => 'customercode',
'value' => $customercode,
'morecss' => 'minwidth300',
'moreattr' => 'maxlength="128"',
);
}
// @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 '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="subscription">';
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="thirdpartylabel" id="thirdpartylabel" value="'.dol_escape_htmltag($object->company).'">';
print '<form name="subscription" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="subscription">';
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="thirdpartylabel" id="thirdpartylabel" value="'.dol_escape_htmltag($object->company).'">';
print dol_get_fiche_head('');
print "<table class=\"border\" width=\"100%\">\n";
print '<tbody>';
print '<tbody>';
$today = dol_now();
$datefrom = 0;
$dateto = 0;
$paymentdate = -1;
$datefrom = 0;
$dateto = 0;
$paymentdate = -1;
// Date payment
if (GETPOST('paymentyear') && GETPOST('paymentmonth') && GETPOST('paymentday')) {
$paymentdate = dol_mktime(0, 0, 0, GETPOST('paymentmonth'), GETPOST('paymentday'), GETPOST('paymentyear'));
}
// Date payment
if (GETPOST('paymentyear') && GETPOST('paymentmonth') && GETPOST('paymentday')) {
$paymentdate = dol_mktime(0, 0, 0, GETPOST('paymentmonth'), GETPOST('paymentday'), GETPOST('paymentyear'));
}
print '<tr>';
// Date start subscription
print '<td class="fieldrequired">'.$langs->trans("DateSubscription").'</td><td>';
if (GETPOST('reday')) {
$datefrom = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
}
if (!$datefrom) {
$datefrom = $object->datevalid;
if ($object->datefin > 0) {
$datefrom = dol_time_plus_duree($object->datefin, 1, 'd');
}
}
print $form->selectDate($datefrom, '', '', '', '', "subscription", 1, 1);
print "</td></tr>";
print '<tr>';
// Date start subscription
print '<td class="fieldrequired">'.$langs->trans("DateSubscription").'</td><td>';
if (GETPOST('reday')) {
$datefrom = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
}
if (!$datefrom) {
$datefrom = $object->datevalid;
if ($object->datefin > 0) {
$datefrom = dol_time_plus_duree($object->datefin, 1, 'd');
}
}
print $form->selectDate($datefrom, '', '', '', '', "subscription", 1, 1);
print "</td></tr>";
// Date end subscription
if (GETPOST('endday')) {
$dateto = dol_mktime(0, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
}
if (!$dateto) {
$dateto = -1; // By default, no date is suggested
}
print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td>';
print $form->selectDate($dateto, 'end', '', '', '', "subscription", 1, 0);
print "</td></tr>";
// Date end subscription
if (GETPOST('endday')) {
$dateto = dol_mktime(0, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
}
if (!$dateto) {
$dateto = -1; // By default, no date is suggested
}
print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td>';
print $form->selectDate($dateto, 'end', '', '', '', "subscription", 1, 0);
print "</td></tr>";
if ($adht->subscription) {
// 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>';
if ($adht->subscription) {
// 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>';
// Label
print '<tr><td>'.$langs->trans("Label").'</td>';
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");
print '"></td></tr>';
// Label
print '<tr><td>'.$langs->trans("Label").'</td>';
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");
print '"></td></tr>';
// Complementary action
if ((!empty($conf->banque->enabled) || !empty($conf->facture->enabled)) && empty($conf->global->ADHERENT_SUBSCRIPTION_HIDECOMPLEMENTARYACTIONS)) {
$company = new Societe($db);
if ($object->fk_soc) {
$result = $company->fetch($object->fk_soc);
}
// Complementary action
if ((!empty($conf->banque->enabled) || !empty($conf->facture->enabled)) && empty($conf->global->ADHERENT_SUBSCRIPTION_HIDECOMPLEMENTARYACTIONS)) {
$company = new Societe($db);
if ($object->fk_soc) {
$result = $company->fetch($object->fk_soc);
}
// Title payments
//print '<tr><td colspan="2"><b>'.$langs->trans("Payment").'</b></td></tr>';
// Title payments
//print '<tr><td colspan="2"><b>'.$langs->trans("Payment").'</b></td></tr>';
// No more action
print '<tr><td class="tdtop fieldrequired">'.$langs->trans('MoreActions');
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>';
// Add entry into bank accoun
if (!empty($conf->banque->enabled)) {
print '<input type="radio" class="moreaction" id="bankdirect" name="paymentsave" value="bankdirect"'.(!empty($bankdirect) ? ' checked' : '');
print '> '.$langs->trans("MoreActionBankDirect").'<br>';
}
// Add invoice with no payments
if (!empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(!empty($invoiceonly) ? ' checked' : '');
//if (empty($object->fk_soc)) print ' disabled';
print '> '.$langs->trans("MoreActionInvoiceOnly");
if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
else {
print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty");
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>';
// No more action
print '<tr><td class="tdtop fieldrequired">'.$langs->trans('MoreActions');
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>';
// Add entry into bank accoun
if (!empty($conf->banque->enabled)) {
print '<input type="radio" class="moreaction" id="bankdirect" name="paymentsave" value="bankdirect"'.(!empty($bankdirect) ? ' checked' : '');
print '> '.$langs->trans("MoreActionBankDirect").'<br>';
}
// Add invoice with no payments
if (!empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(!empty($invoiceonly) ? ' checked' : '');
//if (empty($object->fk_soc)) print ' disabled';
print '> '.$langs->trans("MoreActionInvoiceOnly");
if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
else {
print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty");
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_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
$prodtmp = new Product($db);
$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 '<br>';
}
// Add invoice with payments
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' : '');
//if (empty($object->fk_soc)) print ' disabled';
print '> '.$langs->trans("MoreActionBankViaInvoice");
if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
else {
print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty");
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>';
print '<br>';
}
// Add invoice with payments
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' : '');
//if (empty($object->fk_soc)) print ' disabled';
print '> '.$langs->trans("MoreActionBankViaInvoice");
if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
else {
print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty");
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_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
$prodtmp = new Product($db);
$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);
}
$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_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);
@ -141,8 +141,8 @@ if (($action == 'update' && !GETPOST("cancel", 'alpha'))
// Create thumbs of logo (Note that PDF use original file and not thumbs)
if ($isimage > 0)
{
// 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...
// 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...
// Create small thumb, Used on logon for example
$imgThumbSmall = vignette($dirforimage.$original_file, $maxwidthsmall, $maxheightsmall, '_small', $quality);
@ -269,7 +269,7 @@ if ($action == 'addthumb' || $action == 'addthumbsquarred') // Regenerate thumb
$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...
// 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" : "");
if (!isOnlyOneLocalTax(2))
{
print '<br><label for="lt2">'.$langs->trans("LTRate").'</label>: ';
$formcompany->select_localtax(2, $conf->global->MAIN_INFO_VALUE_LOCALTAX2, "lt2");
print '<br><label for="lt2">'.$langs->trans("LTRate").'</label>: ';
$formcompany->select_localtax(2, $conf->global->MAIN_INFO_VALUE_LOCALTAX2, "lt2");
}
print '<br><label for="clt2">'.$langs->trans("CalcLocaltax").'</label>: ';
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'))) {
$sql .= " WHERE ".$rowidcol." = '".$db->escape($rowid)."'";
} else {
$sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
$sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
}
if (in_array('entity', $listfieldmodify)) $sql .= " AND entity = '".getEntity($tabname[$id])."'";

View File

@ -113,17 +113,17 @@ class Asset extends CommonObject
*/
public $entity;
/**
* @var string Asset label
*/
public $label;
/**
* @var string Asset label
*/
public $label;
public $amount;
/**
* @var int Thirdparty ID
*/
public $fk_soc;
public $fk_soc;
/**
* @var string description
@ -134,21 +134,21 @@ class Asset extends CommonObject
public $note_private;
/**
* @var integer|string date_creation
*/
* @var integer|string date_creation
*/
public $date_creation;
public $tms;
/**
* @var int ID
*/
* @var int ID
*/
public $fk_user_creat;
/**
* @var int ID
*/
* @var int ID
*/
public $fk_user_modif;
public $import_key;
@ -381,7 +381,7 @@ class Asset extends CommonObject
return $this->LibStatut($this->status, $mode);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return the status
*
@ -391,14 +391,14 @@ class Asset extends CommonObject
*/
public static function LibStatut($status, $mode = 0)
{
// phpcs:enable
// phpcs:enable
global $langs;
$langs->load("contracts");
$labelStatus = array();
$labelStatus = array();
$labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled');
$labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
$labelStatusShort = array();
$labelStatusShort = array();
$labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Disabled');
$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"))
{
$db->begin();
$db->begin();
$datev = dol_mktime(12, 0, 0, $_POST["datevmonth"], $_POST["datevday"], $_POST["datevyear"]);
$datep = dol_mktime(12, 0, 0, $_POST["datepmonth"], $_POST["datepday"], $_POST["datepyear"]);
$datev = dol_mktime(12, 0, 0, $_POST["datevmonth"], $_POST["datevday"], $_POST["datevyear"]);
$datep = dol_mktime(12, 0, 0, $_POST["datepmonth"], $_POST["datepday"], $_POST["datepyear"]);
$object->accountid = GETPOST("accountid");
$object->paymenttype = GETPOST("paiementtype");
$object->datev = $datev;
$object->datep = $datep;
$object->amount = price2num(GETPOST("amount"));
$object->accountid = GETPOST("accountid");
$object->paymenttype = GETPOST("paiementtype");
$object->datev = $datev;
$object->datep = $datep;
$object->amount = price2num(GETPOST("amount"));
$object->label = GETPOST("label");
$object->ltt = $lttype;
$ret = $object->addPayment($user);
if ($ret > 0)
{
$db->commit();
header("Location: list.php?localTaxType=".$lttype);
exit;
} else {
$db->rollback();
setEventMessages($object->error, $object->errors, 'errors');
$_GET["action"] = "create";
}
$ret = $object->addPayment($user);
if ($ret > 0)
{
$db->commit();
header("Location: list.php?localTaxType=".$lttype);
exit;
} else {
$db->rollback();
setEventMessages($object->error, $object->errors, 'errors');
$_GET["action"] = "create";
}
}
//delete payment of localtax
if ($action == 'delete')
{
$result = $object->fetch($id);
$result = $object->fetch($id);
if ($object->rappro == 0)
{
$db->begin();
$db->begin();
$ret = $object->delete($user);
if ($ret > 0)
{
$ret = $object->delete($user);
if ($ret > 0)
{
if ($object->fk_bank)
{
$accountline = new AccountLine($db);
@ -116,13 +116,13 @@ if ($action == 'delete')
$db->rollback();
setEventMessages($object->error, $object->errors, 'errors');
}
} else {
$db->rollback();
setEventMessages($object->error, $object->errors, 'errors');
}
} else {
$db->rollback();
setEventMessages($object->error, $object->errors, 'errors');
}
} else {
$mesg = 'Error try do delete a line linked to a conciliated bank transaction';
setEventMessages($mesg, null, 'errors');
$mesg = 'Error try do delete a line linked to a conciliated bank transaction';
setEventMessages($mesg, null, 'errors');
}
}
@ -149,25 +149,25 @@ llxHeader("", $title, $helpurl);
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 '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="localTaxType" value="'.$lttype.'">';
print '<input type="hidden" name="action" value="add">';
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="localTaxType" value="'.$lttype.'">';
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 '<td class="titlefieldcreate fieldrequired">'.$langs->trans("DatePayment").'</td><td>';
print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1);
print '</td></tr>';
print "<tr>";
print '<td class="titlefieldcreate fieldrequired">'.$langs->trans("DatePayment").'</td><td>';
print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1);
print '</td></tr>';
print '<tr><td class="fieldrequired">'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).'</td><td>';
print $form->selectDate($datev, "datev", '', '', '', 'add', 1, 1);
print '</td></tr>';
print '<tr><td class="fieldrequired">'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).'</td><td>';
print $form->selectDate($datev, "datev", '', '', '', 'add', 1, 1);
print '</td></tr>';
// 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>';

File diff suppressed because it is too large Load Diff

View File

@ -33,36 +33,36 @@ abstract class CommonInvoice extends CommonObject
{
use CommonIncoterm;
/**
* Standard invoice
*/
const TYPE_STANDARD = 0;
/**
* Standard invoice
*/
const TYPE_STANDARD = 0;
/**
* Replacement invoice
*/
const TYPE_REPLACEMENT = 1;
/**
* Replacement invoice
*/
const TYPE_REPLACEMENT = 1;
/**
* Credit note invoice
*/
const TYPE_CREDIT_NOTE = 2;
/**
* Credit note invoice
*/
const TYPE_CREDIT_NOTE = 2;
/**
* Deposit invoice
*/
const TYPE_DEPOSIT = 3;
/**
* Deposit invoice
*/
const TYPE_DEPOSIT = 3;
/**
* Proforma invoice.
* @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice !
*/
const TYPE_PROFORMA = 4;
/**
* Proforma invoice.
* @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice !
*/
const TYPE_PROFORMA = 4;
/**
* Situation invoice
*/
const TYPE_SITUATION = 5;
/**
* Situation invoice
*/
const TYPE_SITUATION = 5;
/**
* Draft status
@ -102,16 +102,16 @@ abstract class CommonInvoice extends CommonObject
*/
public function getRemainToPay($multicurrency = 0)
{
$alreadypaid = 0.0;
$alreadypaid += $this->getSommePaiement($multicurrency);
$alreadypaid += $this->getSumDepositsUsed($multicurrency);
$alreadypaid += $this->getSumCreditNotesUsed($multicurrency);
$alreadypaid = 0.0;
$alreadypaid += $this->getSommePaiement($multicurrency);
$alreadypaid += $this->getSumDepositsUsed($multicurrency);
$alreadypaid += $this->getSumCreditNotesUsed($multicurrency);
$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
$remaintopay = 0.0;
}
return $remaintopay;
$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
$remaintopay = 0.0;
}
return $remaintopay;
}
/**
@ -151,7 +151,7 @@ abstract class CommonInvoice extends CommonObject
/**
* 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
* @return float <0 if KO, Sum of deposits amount otherwise
@ -159,21 +159,21 @@ abstract class CommonInvoice extends CommonObject
public function getSumDepositsUsed($multicurrency = 0)
{
if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
{
// TODO
return 0.0;
}
{
// TODO
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);
$result = $discountstatic->getSumDepositsUsed($this, $multicurrency);
if ($result >= 0) {
return $result;
} else {
$this->error = $discountstatic->error;
return -1;
}
$discountstatic = new DiscountAbsolute($this->db);
$result = $discountstatic->getSumDepositsUsed($this, $multicurrency);
if ($result >= 0) {
return $result;
} else {
$this->error = $discountstatic->error;
return -1;
}
}
/**
@ -184,16 +184,16 @@ abstract class CommonInvoice extends CommonObject
*/
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);
$result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency);
if ($result >= 0) {
return $result;
} else {
$this->error = $discountstatic->error;
return -1;
}
$discountstatic = new DiscountAbsolute($this->db);
$result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency);
if ($result >= 0) {
return $result;
} else {
$this->error = $discountstatic->error;
return -1;
}
}
/**
@ -204,16 +204,16 @@ abstract class CommonInvoice extends CommonObject
*/
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);
$result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency);
if ($result >= 0) {
return $result;
} else {
$this->error = $discountstatic->error;
return -1;
}
$discountstatic = new DiscountAbsolute($this->db);
$result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency);
if ($result >= 0) {
return $result;
} else {
$this->error = $discountstatic->error;
return -1;
}
}
/**
@ -329,7 +329,7 @@ abstract class CommonInvoice extends CommonObject
$obj = $this->db->fetch_object($resql);
$tmp = array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
if (!empty($field3)) {
$tmp['ref_ext'] = $obj->ref_ext;
$tmp['ref_ext'] = $obj->ref_ext;
}
$retarray[]=$tmp;
$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
* Rule is:
@ -399,9 +399,9 @@ abstract class CommonInvoice extends CommonObject
*
* @return int <=0 if no, >0 if yes
*/
public function is_erasable()
{
// phpcs:enable
public function is_erasable()
{
// phpcs:enable
global $conf;
// 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
*/
public function getLibType()
public function getLibType()
{
global $langs;
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_CREDIT_NOTE) return $langs->trans("InvoiceAvoir");
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_SITUATION) return $langs->trans("InvoiceSituation");
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_CREDIT_NOTE) return $langs->trans("InvoiceAvoir");
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_SITUATION) return $langs->trans("InvoiceSituation");
return $langs->trans("Unknown");
}
@ -510,7 +510,7 @@ abstract class CommonInvoice extends CommonObject
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
*
@ -523,52 +523,52 @@ abstract class CommonInvoice extends CommonObject
*/
public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = 0)
{
// phpcs:enable
// phpcs:enable
global $langs;
$langs->load('bills');
$statusType = 'status0';
$prefix = 'Short';
if (!$paye) {
if ($status == 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft');
} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid');
$statusType = 'status5';
} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially');
$statusType = 'status9';
} elseif ($alreadypaid == 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid');
$statusType = 'status1';
} else {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted');
$statusType = 'status3';
}
if ($status == 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft');
} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid');
$statusType = 'status5';
} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially');
$statusType = 'status9';
} elseif ($alreadypaid == 0) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid');
$statusType = 'status1';
} else {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted');
$statusType = 'status3';
}
} else {
$statusType = 'status6';
$statusType = 'status6';
if ($type == self::TYPE_CREDIT_NOTE) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note
} elseif ($type == self::TYPE_DEPOSIT) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice
} else {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid');
}
if ($type == self::TYPE_CREDIT_NOTE) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note
} elseif ($type == self::TYPE_DEPOSIT) {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice
} else {
$labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid');
$labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid');
}
}
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
* 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.
* @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_id;
$cdr_nbjour = 0;
$cdr_type = 0;
$cdr_decalage = 0;
$cdr_type = 0;
$cdr_decalage = 0;
$sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
$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
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);
$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
if (!is_array($mesgs)) {
// If mesgs is a string
// If mesgs is a string
if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
} else {
// If mesgs is an array
// If mesgs is an array
foreach ($mesgs as $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'];
}
} else {
// Common usage
// Common usage
$liste[$obj->id] = $obj->label ? $obj->label : $obj->doc_template_name;
}
}

View File

@ -32,10 +32,10 @@
*/
function loan_prepare_head($object)
{
global $db, $langs, $conf;
global $db, $langs, $conf;
$tab = 0;
$head = array();
$tab = 0;
$head = array();
$head[$tab][0] = DOL_URL_ROOT.'/loan/card.php?id='.$object->id;
$head[$tab][1] = $langs->trans('Card');
@ -47,17 +47,17 @@ function loan_prepare_head($object)
$head[$tab][2] = 'FinancialCommitment';
$tab++;
// Show more tabs from modules
// 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); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $tab, 'loan');
// Show more tabs from modules
// 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); to remove a tab
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/class/link.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$upload_dir = $conf->loan->dir_output."/".dol_sanitizeFileName($object->ref);
$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][1] = $langs->trans("Documents");
if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
@ -73,14 +73,14 @@ function loan_prepare_head($object)
$tab++;
}
$head[$tab][0] = DOL_URL_ROOT.'/loan/info.php?id='.$object->id;
$head[$tab][1] = $langs->trans("Info");
$head[$tab][2] = 'info';
$tab++;
$head[$tab][0] = DOL_URL_ROOT.'/loan/info.php?id='.$object->id;
$head[$tab][1] = $langs->trans("Info");
$head[$tab][2] = 'info';
$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)
{
global $conf, $db;
require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php';
$object = new LoanSchedule($db);
$output = array();
global $conf, $db;
require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php';
$object = new LoanSchedule($db);
$output = array();
// If mensuality is 0 we don't pay interests and remaining capital not modified
if ($mens == 0) {
$int = 0;
$cap_rest = $capital;
} else {
$int = ($capital * ($rate / 12));
$int = round($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);
// If mensuality is 0 we don't pay interests and remaining capital not modified
if ($mens == 0) {
$int = 0;
$cap_rest = $capital;
} else {
$int = ($capital * ($rate / 12));
$int = round($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);
$echance++;
$capital = $cap_rest;
while ($echance <= $nbterm) {
$mens = round($object->calcMonthlyPayments($capital, $rate, $nbterm - $echance + 1), 2, PHP_ROUND_HALF_UP);
$echance++;
$capital = $cap_rest;
while ($echance <= $nbterm) {
$mens = round($object->calcMonthlyPayments($capital, $rate, $nbterm - $echance + 1), 2, PHP_ROUND_HALF_UP);
$int = ($capital * ($rate / 12));
$int = round($int, 2, PHP_ROUND_HALF_UP);
$cap_rest = round($capital - ($mens - $int), 2, PHP_ROUND_HALF_UP);
$int = ($capital * ($rate / 12));
$int = round($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,
);
$capital = $cap_rest;
$echance++;
}
$capital = $cap_rest;
$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
{
/**
* Dolibarr version of the loaded document
* @var string
*/
* Dolibarr version of the loaded document
* @var string
*/
public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr'
/**
* @var string Error code (or message)
*/
public $error = '';
* @var string Error code (or message)
*/
public $error = '';
/**
* @var string
@ -54,17 +54,17 @@ class mod_task_universal extends ModeleNumRefTask
public $name = 'Universal';
/**
* Returns the description of the numbering model
*
* @return string Texte descripif
*/
public function info()
{
global $conf, $langs, $db;
/**
* Returns the description of the numbering model
*
* @return string Texte descripif
*/
public function info()
{
global $conf, $langs, $db;
// Load translation files required by the page
$langs->loadLangs(array("projects", "admin"));
$langs->loadLangs(array("projects", "admin"));
$form = new Form($db);
@ -93,37 +93,37 @@ class mod_task_universal extends ModeleNumRefTask
$texte .= '</form>';
return $texte;
}
}
/**
* Return an example of numbering
*
* @return string Example
*/
public function getExample()
{
global $conf, $langs, $mysoc;
/**
* Return an example of numbering
*
* @return string Example
*/
public function getExample()
{
global $conf, $langs, $mysoc;
$old_code_client = $mysoc->code_client;
$mysoc->code_client = 'CCCCCCCCCC';
$numExample = $this->getNextValue($mysoc, '');
$old_code_client = $mysoc->code_client;
$mysoc->code_client = 'CCCCCCCCCC';
$numExample = $this->getNextValue($mysoc, '');
$mysoc->code_client = $old_code_client;
if (!$numExample) {
$numExample = $langs->trans('NotConfigured');
}
return $numExample;
}
}
/**
* Return next value
*
* @param Societe $objsoc Object third party
* @param Task $object Object task
* @return string Value if OK, 0 if KO
*/
public function getNextValue($objsoc, $object)
{
/**
* Return next value
*
* @param Societe $objsoc Object third party
* @param Task $object Object task
* @return string Value if OK, 0 if KO
*/
public function getNextValue($objsoc, $object)
{
global $db, $conf;
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
/**
* Return next reference not yet used as a reference
*
* @param Societe $objsoc Object third party
* @param Task $object Object task
* @return string Next not used reference
*/
public function project_get_num($objsoc = 0, $object = '')
{
// phpcs:enable
return $this->getNextValue($objsoc, $object);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return next reference not yet used as a reference
*
* @param Societe $objsoc Object third party
* @param Task $object Object task
* @return string Next not used reference
*/
public function project_get_num($objsoc = 0, $object = '')
{
// phpcs:enable
return $this->getNextValue($objsoc, $object);
}
}

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -42,15 +42,15 @@ function paypaladmin_prepare_head()
$object = new stdClass();
// Show more tabs from modules
// 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); to remove a tab
// Show more tabs from modules
// 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); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'paypaladmin');
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;
$langs->load("paypal");
$langs->load("paybox");
$servicename = 'PayPal';
$out = '<br><br>';
$out .= img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'<br>';
$url = getPaypalPaymentUrl(0, $type, $ref);
$out .= '<input type="text" id="paypalurl" class="quatrevingtpercent" value="'.$url.'">';
$out .= ajax_autoselect("paypalurl", 0);
return $out;
$langs->load("paybox");
$servicename = 'PayPal';
$out = '<br><br>';
$out .= img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'<br>';
$url = getPaypalPaymentUrl(0, $type, $ref);
$out .= '<input type="text" id="paypalurl" class="quatrevingtpercent" value="'.$url.'">';
$out .= ajax_autoselect("paypalurl", 0);
return $out;
}
@ -94,88 +94,88 @@ function getPaypalPaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
$ref = str_replace(' ', '', $ref);
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>' : '');
if (!empty($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);
}
}
if ($type == 'order')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=order&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'order_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
if ($type == 'invoice')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'invoice_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
if ($type == 'contractline')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'contractline_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
if ($type == 'membersubscription')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'member_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
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>' : '');
if (!empty($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);
}
}
if ($type == 'order')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=order&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'order_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
if ($type == 'invoice')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'invoice_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
if ($type == 'contractline')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'contractline_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
if ($type == 'membersubscription')
{
$out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode ? '<font color="#666666">' : '');
if ($mode == 1) $out .= 'member_ref';
if ($mode == 0) $out .= urlencode($ref);
$out .= ($mode ? '</font>' : '');
if (!empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
else {
$out .= '&securekey='.($mode ? '<font color="#666666">' : '');
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);
$out .= ($mode ? '</font>' : '');
}
}
}
// For multicompany
$out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities
// For multicompany
$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)
{
//declaring of global variables
global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
//declaring of global variables
global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
global $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum;
global $email, $desc;
global $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum;
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';
$landingPage = 'Billing';
// For payment with Paypal only
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly')
{
$solutionType = 'Mark';
$landingPage = 'Login';
}
// For payment with Credit card or Paypal
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral')
{
$solutionType = 'Sole';
$landingPage = 'Billing';
}
// For payment with Credit card
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly')
{
$solutionType = 'Sole';
$landingPage = 'Billing';
}
$solutionType = 'Sole';
$landingPage = 'Billing';
// For payment with Paypal only
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly')
{
$solutionType = 'Mark';
$landingPage = 'Login';
}
// For payment with Credit card or Paypal
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral')
{
$solutionType = 'Sole';
$landingPage = 'Billing';
}
// For payment with Credit card
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly')
{
$solutionType = 'Sole';
$landingPage = 'Billing';
}
dol_syslog("expresscheckout redirect with callSetExpressCheckout $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum");
$resArray = callSetExpressCheckout(
$paymentAmount,
$currencyCodeType,
$paymentType,
$returnURL,
$cancelURL,
$tag,
$solutionType,
$landingPage,
$shipToName,
$shipToStreet,
$shipToCity,
$shipToState,
$shipToCountryCode,
$shipToZip,
$shipToStreet2,
$phoneNum,
$email,
$desc
);
dol_syslog("expresscheckout redirect with callSetExpressCheckout $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum");
$resArray = callSetExpressCheckout(
$paymentAmount,
$currencyCodeType,
$paymentType,
$returnURL,
$cancelURL,
$tag,
$solutionType,
$landingPage,
$shipToName,
$shipToStreet,
$shipToCity,
$shipToState,
$shipToCountryCode,
$shipToZip,
$shipToStreet2,
$phoneNum,
$email,
$desc
);
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$token = $resArray["TOKEN"];
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$token = $resArray["TOKEN"];
// Redirect to paypal.com here
$payPalURL = $API_Url.$token;
header("Location: ".$payPalURL);
exit;
} else {
//Display a user friendly Error on the page using any of the following error information returned by PayPal
$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
// Redirect to paypal.com here
$payPalURL = $API_Url.$token;
header("Location: ".$payPalURL);
exit;
} else {
//Display a user friendly Error on the page using any of the following error information returned by PayPal
$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
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";
} else {
$mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."<br>\n";
$mesg .= $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
$mesg .= $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
$mesg .= $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
$mesg .= $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
}
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";
} else {
$mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."<br>\n";
$mesg .= $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
$mesg .= $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
$mesg .= $langs->trans('ErrorCode').": ".$ErrorCode."<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 = '')
{
//------------------------------------------------------------------------------------------------------------------------------------
// 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
global $conf, $langs, $mysoc;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
//declaring of global variables
global $conf, $langs, $mysoc;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
$nvpstr = '';
//$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call
$nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL);
$nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL);
if (!empty($conf->global->PAYPAL_ALLOW_NOTES))
{
$nvpstr = $nvpstr."&ALLOWNOTE=0";
}
if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS))
{
$nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted
} else {
$nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory)
}
$nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType);
$nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage);
if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER))
{
$nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number
}
$nvpstr = '';
//$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call
$nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL);
$nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL);
if (!empty($conf->global->PAYPAL_ALLOW_NOTES))
{
$nvpstr = $nvpstr."&ALLOWNOTE=0";
}
if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS))
{
$nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted
} else {
$nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory)
}
$nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType);
$nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage);
if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER))
{
$nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number
}
$paypalprefix = 'PAYMENTREQUEST_0_';
//$paypalprefix = '';
$paypalprefix = 'PAYMENTREQUEST_0_';
//$paypalprefix = '';
if (!empty($paypalprefix) && $paymentType == 'Sole') $paymentType = 'Sale';
$nvpstr = $nvpstr."&AMT=".urlencode($paymentAmount); // Total for all elements
$nvpstr = $nvpstr."&".$paypalprefix."INVNUM=".urlencode($tag);
$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."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."INVNUM=".urlencode($tag);
$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."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."L_PAYMENTREQUEST_0_QTY0=1";
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_AMT0=".urlencode($paymentAmount);
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NAME0=".urlencode($desc);
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NUMBER0=0";
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_QTY0=1";
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_AMT0=".urlencode($paymentAmount);
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NAME0=".urlencode($desc);
$nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NUMBER0=0";
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTONAME=".urlencode($shipToName); // SHIPTONAME deprecated by paypal -> PAYMENTREQUEST_n_SHIPTONAME
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET=".urlencode($shipToStreet); //
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET2=".urlencode($shipToStreet2);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCITY=".urlencode($shipToCity);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTATE=".urlencode($shipToState);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip);
$nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum);
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
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTONAME=".urlencode($shipToName); // SHIPTONAME deprecated by paypal -> PAYMENTREQUEST_n_SHIPTONAME
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET=".urlencode($shipToStreet); //
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET2=".urlencode($shipToStreet2);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCITY=".urlencode($shipToCity);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTATE=".urlencode($shipToState);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip);
$nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum);
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($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo)
{
global $dolibarr_main_url_root;
if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo)
{
global $dolibarr_main_url_root;
// Define $urlwithroot
$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=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
// Define $urlwithroot
$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=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
$urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo);
$nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo);
}
if (!empty($conf->global->PAYPAL_BRANDNAME))
{
$nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME
}
if (!empty($conf->global->PAYPAL_NOTETOBUYER))
{
$nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER
}
$urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo);
$nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo);
}
if (!empty($conf->global->PAYPAL_BRANDNAME))
{
$nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME
}
if (!empty($conf->global->PAYPAL_NOTETOBUYER))
{
$nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER
}
$_SESSION["FinalPaymentAmt"] = $paymentAmount;
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType; // 'Mark', 'Sole'
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType; // 'Mark', 'Sole'
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip
//'---------------------------------------------------------------------------------------------------------------
//' Make the API call to PayPal
//' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
//' If an error occured, show the resulting errors
//'---------------------------------------------------------------------------------------------------------------
$resArray = hash_call("SetExpressCheckout", $nvpstr);
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$token = urldecode($resArray["TOKEN"]);
$_SESSION['TOKEN'] = $token;
}
//'---------------------------------------------------------------------------------------------------------------
//' Make the API call to PayPal
//' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
//' If an error occured, show the resulting errors
//'---------------------------------------------------------------------------------------------------------------
$resArray = hash_call("SetExpressCheckout", $nvpstr);
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$token = urldecode($resArray["TOKEN"]);
$_SESSION['TOKEN'] = $token;
}
return $resArray;
return $resArray;
}
/**
@ -431,39 +431,39 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType,
*/
function getDetails($token)
{
//'--------------------------------------------------------------
//' At this point, the buyer has completed authorizing the payment
//' at PayPal. The function will call PayPal to obtain the details
//' of the authorization, incuding any shipping information of the
//' buyer. Remember, the authorization is not a completed transaction
//' at this state - the buyer still needs an additional step to finalize
//' the transaction
//'--------------------------------------------------------------
//'--------------------------------------------------------------
//' At this point, the buyer has completed authorizing the payment
//' at PayPal. The function will call PayPal to obtain the details
//' of the authorization, incuding any shipping information of the
//' buyer. Remember, the authorization is not a completed transaction
//' at this state - the buyer still needs an additional step to finalize
//' the transaction
//'--------------------------------------------------------------
//declaring of global variables
global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
//declaring of global variables
global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
//'---------------------------------------------------------------------------
//' Build a second API request to PayPal, using the token as the
//' ID to get the details on the payment authorization
//'---------------------------------------------------------------------------
$nvpstr = "&TOKEN=".$token;
//'---------------------------------------------------------------------------
//' Build a second API request to PayPal, using the token as the
//' ID to get the details on the payment authorization
//'---------------------------------------------------------------------------
$nvpstr = "&TOKEN=".$token;
//'---------------------------------------------------------------------------
//' Make the API call and store the results in an array.
//' If the call was a success, show the authorization details, and provide
//' an action to complete the payment.
//' If failed, show the error
//'---------------------------------------------------------------------------
$resArray = hash_call("GetExpressCheckoutDetails", $nvpstr);
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$_SESSION['payer_id'] = $resArray['PAYERID'];
}
return $resArray;
//'---------------------------------------------------------------------------
//' Make the API call and store the results in an array.
//' If the call was a success, show the authorization details, and provide
//' an action to complete the payment.
//' If failed, show the error
//'---------------------------------------------------------------------------
$resArray = hash_call("GetExpressCheckoutDetails", $nvpstr);
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$_SESSION['payer_id'] = $resArray['PAYERID'];
}
return $resArray;
}
@ -481,37 +481,37 @@ function getDetails($token)
*/
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
holds the name value pairs
*/
//declaring of global variables
global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
//declaring of global variables
global $conf, $langs;
global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
$nvpstr = '';
$nvpstr .= '&TOKEN='.urlencode($token);
$nvpstr .= '&PAYERID='.urlencode($payerID);
$nvpstr .= '&PAYMENTACTION='.urlencode($paymentType);
$nvpstr .= '&AMT='.urlencode($FinalPaymentAmt);
$nvpstr .= '&CURRENCYCODE='.urlencode($currencyCodeType);
$nvpstr .= '&IPADDRESS='.urlencode($ipaddress);
$nvpstr .= '&INVNUM='.urlencode($tag);
$nvpstr = '';
$nvpstr .= '&TOKEN='.urlencode($token);
$nvpstr .= '&PAYERID='.urlencode($payerID);
$nvpstr .= '&PAYMENTACTION='.urlencode($paymentType);
$nvpstr .= '&AMT='.urlencode($FinalPaymentAmt);
$nvpstr .= '&CURRENCYCODE='.urlencode($currencyCodeType);
$nvpstr .= '&IPADDRESS='.urlencode($ipaddress);
$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
*/
$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 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)
{
//declaring of global variables
global $conf, $langs;
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;
//declaring of global variables
global $conf, $langs;
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;
// TODO problem with triggers
$API_version = "98.0";
// TODO problem with triggers
$API_version = "98.0";
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_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
} else {
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$API_Url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$API_Url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
}
// 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;
// TODO END problem with triggers
dol_syslog("Paypal API endpoint ".$API_Endpoint);
dol_syslog("Paypal API endpoint ".$API_Endpoint);
//setting the curl parameters.
$ch = curl_init();
//setting the curl parameters.
$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 $nvpStr;
exit;*/
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// 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_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// 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));
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 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_TIMEOUT, empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_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_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 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)
{
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_PROXY, $PROXY_HOST.":".$PROXY_PORT);
if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
}
//if USE_PROXY constant set to true in Constants.php, then only proxy will be enabled.
if ($USE_PROXY)
{
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_PROXY, $PROXY_HOST.":".$PROXY_PORT);
if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
}
//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 .= "&LOCALECODE=".strtoupper($langs->getDefaultLang(1));
//$nvpreq.="&BRANDNAME=".urlencode(); // Override merchant name
//$nvpreq.="&NOTIFYURL=".urlencode(); // For Instant Payment Notification url
//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 .= "&LOCALECODE=".strtoupper($langs->getDefaultLang(1));
//$nvpreq.="&BRANDNAME=".urlencode(); // Override merchant name
//$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
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//getting response from server
$response = curl_exec($ch);
//getting response from server
$response = curl_exec($ch);
$nvpReqArray = deformatNVP($nvpreq);
$_SESSION['nvpReqArray'] = $nvpReqArray;
$nvpReqArray = deformatNVP($nvpreq);
$_SESSION['nvpReqArray'] = $nvpReqArray;
//convrting NVPResponse to an Associative Array
dol_syslog("Paypal API hash_call Response nvpresp=".$response);
$nvpResArray = deformatNVP($response);
//convrting NVPResponse to an Associative Array
dol_syslog("Paypal API hash_call Response nvpresp=".$response);
$nvpResArray = deformatNVP($response);
if (curl_errno($ch)) {
// moving to display page to display curl errors
$_SESSION['curl_error_no'] = curl_errno($ch);
$_SESSION['curl_error_msg'] = curl_error($ch);
if (curl_errno($ch)) {
// moving to display page to display curl errors
$_SESSION['curl_error_no'] = curl_errno($ch);
$_SESSION['curl_error_msg'] = curl_error($ch);
//Execute the Error handling module to display errors.
} else {
//closing the curl
curl_close($ch);
}
//Execute the Error handling module to display errors.
} else {
//closing the curl
curl_close($ch);
}
return $nvpResArray;
return $nvpResArray;
}
@ -681,24 +681,24 @@ function hash_call($methodName, $nvpStr)
*/
function deformatNVP($nvpstr)
{
$intial = 0;
$nvpArray = array();
$intial = 0;
$nvpArray = array();
while (strlen($nvpstr))
{
//postion of Key
$keypos = strpos($nvpstr, '=');
//position of value
$valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr);
while (strlen($nvpstr))
{
//postion of Key
$keypos = strpos($nvpstr, '=');
//position of value
$valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr);
/*getting the Key and Value values and storing in a Associative Array*/
$keyval = substr($nvpstr, $intial, $keypos);
$valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1);
//decoding the respose
$nvpArray[urldecode($keyval)] = urldecode($valval);
$nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
}
return $nvpArray;
/*getting the Key and Value values and storing in a Associative Array*/
$keyval = substr($nvpstr, $intial, $keypos);
$valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1);
//decoding the respose
$nvpArray[urldecode($keyval)] = urldecode($valval);
$nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
}
return $nvpArray;
}
/**

View File

@ -79,31 +79,31 @@ $htmlother = new FormOther($db);
$object = new Product($db);
if (!$id && empty($ref)) {
llxHeader("", $langs->trans("ProductStatistics"));
llxHeader("", $langs->trans("ProductStatistics"));
$type = GETPOST('type', 'int');
$type = GETPOST('type', 'int');
$helpurl = '';
if ($type == '0') {
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
//$title=$langs->trans("StatisticsOfProducts");
$title = $langs->trans("Statistics");
} elseif ($type == '1') {
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
//$title=$langs->trans("StatisticsOfServices");
$title = $langs->trans("Statistics");
} else {
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
//$title=$langs->trans("StatisticsOfProductsOrServices");
$title = $langs->trans("Statistics");
}
if ($type == '0') {
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
//$title=$langs->trans("StatisticsOfProducts");
$title = $langs->trans("Statistics");
} elseif ($type == '1') {
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
//$title=$langs->trans("StatisticsOfServices");
$title = $langs->trans("Statistics");
} else {
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
//$title=$langs->trans("StatisticsOfProductsOrServices");
$title = $langs->trans("Statistics");
}
$picto = 'product';
if ($type == 1) $picto = 'service';
$picto = 'product';
if ($type == 1) $picto = 'service';
print load_fiche_titre($title, $mesg, $picto);
print load_fiche_titre($title, $mesg, $picto);
} else {
$result = $object->fetch($id, $ref);
$result = $object->fetch($id, $ref);
$title = $langs->trans('ProductServiceCard');
$helpurl = '';
@ -176,12 +176,12 @@ if ($result || empty($id)) {
// Tag
if ($conf->categorie->enabled) {
print '<tr><td class="titlefield">'.$langs->trans("Categories").'</td><td>';
//$moreforfilter.='<div class="divsearchfield">';
$moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1);
//$moreforfilter.='</div>';
print $moreforfilter;
print '</td></tr>';
print '<tr><td class="titlefield">'.$langs->trans("Categories").'</td><td>';
//$moreforfilter.='<div class="divsearchfield">';
$moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1);
//$moreforfilter.='</div>';
print $moreforfilter;
print '</td></tr>';
}
}
@ -189,7 +189,7 @@ if ($result || empty($id)) {
print '<tr><td class="titlefield">'.$langs->trans("Year").'</td><td>';
$arrayyears = array();
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($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear;
@ -299,16 +299,16 @@ if ($result || empty($id)) {
if (dol_is_file($dir.'/'.$graphfiles[$key]['file'])) {
// TODO Load cachefile $graphfiles[$key]['file']
} else {
$morefilters = '';
if ($search_categ > 0) {
$categ = new Categorie($db);
$categ->fetch($search_categ);
$listofprodids = $categ->getObjectsInCateg('product', 1);
$morefilters = ' AND d.fk_product IN ('.((is_array($listofprodids) && count($listofprodids)) ? join(',', $listofprodids) : '0').')';
}
if ($search_categ == -2) {
$morefilters = ' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)';
}
$morefilters = '';
if ($search_categ > 0) {
$categ = new Categorie($db);
$categ->fetch($search_categ);
$listofprodids = $categ->getObjectsInCateg('product', 1);
$morefilters = ' AND d.fk_product IN ('.((is_array($listofprodids) && count($listofprodids)) ? join(',', $listofprodids) : '0').')';
}
if ($search_categ == -2) {
$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 == '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
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"));
else $dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "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 = ($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>';

View File

@ -41,14 +41,14 @@ class MouvementStock extends CommonObject
public $table_element = 'stock_mouvement';
/**
* @var int ID product
*/
/**
* @var int ID product
*/
public $product_id;
/**
* @var int ID warehouse
*/
/**
* @var int ID warehouse
*/
public $warehouse_id;
public $qty;
@ -65,18 +65,18 @@ class MouvementStock extends CommonObject
public $price;
/**
* @var int ID user author
*/
* @var int ID user author
*/
public $fk_user_author;
/**
* @var string stock movements label
*/
public $label;
* @var string stock movements label
*/
public $label;
/**
* @var int ID
*/
/**
* @var int ID
*/
public $fk_origin;
public $origintype;
@ -113,11 +113,11 @@ class MouvementStock extends CommonObject
/**
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
*/
public function __construct($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)
* @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
global $conf, $langs;
// phpcs:disable
global $conf, $langs;
require_once DOL_DOCUMENT_ROOT.'/product/class/product.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
$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)."'";
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);
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_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
dol_print_error($this->db);
$this->db->rollback();
return -1;
$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);
$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.
if ($movestock && $qty < 0 && empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER))
{
if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch)
{
$foundforbatch = 0;
$qtyisnotenough = 0;
foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch)
{
if ($batch != $batchcursor) continue;
$foundforbatch = 1;
if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty;
break;
}
if (!$foundforbatch || $qtyisnotenough)
{
$langs->load("stocks");
include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$tmpwarehouse = new Entrepot($this->db);
$tmpwarehouse->fetch($entrepot_id);
if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch)
{
$foundforbatch = 0;
$qtyisnotenough = 0;
foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch)
{
if ($batch != $batchcursor) continue;
$foundforbatch = 1;
if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty;
break;
}
if (!$foundforbatch || $qtyisnotenough)
{
$langs->load("stocks");
include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$tmpwarehouse = new Entrepot($this->db);
$tmpwarehouse->fetch($entrepot_id);
$this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
$this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
$this->db->rollback();
return -8;
}
}
else
{
if (empty($product->stock_warehouse[$entrepot_id]->real) || $product->stock_warehouse[$entrepot_id]->real < abs($qty))
{
$langs->load("stocks");
$this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
$this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
$this->db->rollback();
return -8;
}
}
$this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
$this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
$this->db->rollback();
return -8;
}
}
else
{
if (empty($product->stock_warehouse[$entrepot_id]->real) || $product->stock_warehouse[$entrepot_id]->real < abs($qty))
{
$langs->load("stocks");
$this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
$this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
$this->db->rollback();
return -8;
}
}
}
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)
{
$result = $this->createBatch($id_product_batch, $qty);
$result = $this->createBatch($id_product_batch, $qty);
} else {
$param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch);
$result = $this->createBatch($param_batch, $qty);
$param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch);
$result = $this->createBatch($param_batch, $qty);
}
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.= " 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 .= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)";
$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
// 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)";
$resql = $this->db->query($sql);
// We do not test error, it can fails if there is child in batch details
// 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.
$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);
// We do not test error, it can fails if there is child in batch details
}
// Add movement for sub products (recursive call)
@ -577,10 +577,10 @@ class MouvementStock extends CommonObject
if ($movestock && !$error)
{
// Call trigger
$result = $this->call_trigger('STOCK_MOVEMENT', $user);
if ($result < 0) $error++;
// End call triggers
// Call trigger
$result = $this->call_trigger('STOCK_MOVEMENT', $user);
if ($result < 0) $error++;
// End call triggers
}
if (!$error)
@ -607,80 +607,80 @@ class MouvementStock extends CommonObject
*/
public function fetch($id)
{
dol_syslog(__METHOD__, LOG_DEBUG);
dol_syslog(__METHOD__, LOG_DEBUG);
$sql = 'SELECT';
$sql .= ' t.rowid,';
$sql .= " t.tms,";
$sql .= " t.datem,";
$sql .= " t.fk_product,";
$sql .= " t.fk_entrepot,";
$sql .= " t.value,";
$sql .= " t.price,";
$sql .= " t.type_mouvement,";
$sql .= " t.fk_user_author,";
$sql .= " t.label,";
$sql .= " t.fk_origin,";
$sql .= " t.origintype,";
$sql .= " t.inventorycode,";
$sql .= " t.batch,";
$sql .= " t.eatby,";
$sql .= " t.sellby,";
$sql .= " t.fk_projet as fk_project";
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE 1 = 1';
//if (null !== $ref) {
//$sql .= ' AND t.ref = ' . '\'' . $ref . '\'';
//} else {
$sql .= ' AND t.rowid = '.$id;
//}
$sql = 'SELECT';
$sql .= ' t.rowid,';
$sql .= " t.tms,";
$sql .= " t.datem,";
$sql .= " t.fk_product,";
$sql .= " t.fk_entrepot,";
$sql .= " t.value,";
$sql .= " t.price,";
$sql .= " t.type_mouvement,";
$sql .= " t.fk_user_author,";
$sql .= " t.label,";
$sql .= " t.fk_origin,";
$sql .= " t.origintype,";
$sql .= " t.inventorycode,";
$sql .= " t.batch,";
$sql .= " t.eatby,";
$sql .= " t.sellby,";
$sql .= " t.fk_projet as fk_project";
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE 1 = 1';
//if (null !== $ref) {
//$sql .= ' AND t.ref = ' . '\'' . $ref . '\'';
//} else {
$sql .= ' AND t.rowid = '.$id;
//}
$resql = $this->db->query($sql);
if ($resql) {
$numrows = $this->db->num_rows($resql);
if ($numrows) {
$obj = $this->db->fetch_object($resql);
$resql = $this->db->query($sql);
if ($resql) {
$numrows = $this->db->num_rows($resql);
if ($numrows) {
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
$this->id = $obj->rowid;
$this->product_id = $obj->fk_product;
$this->warehouse_id = $obj->fk_entrepot;
$this->qty = $obj->value;
$this->type = $obj->type_mouvement;
$this->product_id = $obj->fk_product;
$this->warehouse_id = $obj->fk_entrepot;
$this->qty = $obj->value;
$this->type = $obj->type_mouvement;
$this->tms = $this->db->jdate($obj->tms);
$this->datem = $this->db->jdate($obj->datem);
$this->price = $obj->price;
$this->fk_user_author = $obj->fk_user_author;
$this->label = $obj->label;
$this->fk_origin = $obj->fk_origin;
$this->origintype = $obj->origintype;
$this->inventorycode = $obj->inventorycode;
$this->batch = $obj->batch;
$this->eatby = $this->db->jdate($obj->eatby);
$this->sellby = $this->db->jdate($obj->sellby);
$this->fk_project = $obj->fk_project;
}
$this->tms = $this->db->jdate($obj->tms);
$this->datem = $this->db->jdate($obj->datem);
$this->price = $obj->price;
$this->fk_user_author = $obj->fk_user_author;
$this->label = $obj->label;
$this->fk_origin = $obj->fk_origin;
$this->origintype = $obj->origintype;
$this->inventorycode = $obj->inventorycode;
$this->batch = $obj->batch;
$this->eatby = $this->db->jdate($obj->eatby);
$this->sellby = $this->db->jdate($obj->sellby);
$this->fk_project = $obj->fk_project;
}
// Retrieve all extrafield
// fetch optionals attributes and labels
$this->fetch_optionals();
// Retrieve all extrafield
// fetch optionals attributes and labels
$this->fetch_optionals();
// $this->fetch_lines();
// $this->fetch_lines();
$this->db->free($resql);
$this->db->free($resql);
if ($numrows) {
return 1;
} else {
return 0;
}
} else {
$this->errors[] = 'Error '.$this->db->lasterror();
dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
if ($numrows) {
return 1;
} else {
return 0;
}
} else {
$this->errors[] = 'Error '.$this->db->lasterror();
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 = '')
{
global $conf;
global $conf;
$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 = '')
{
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)
{
global $user;
global $user;
$pdluo = new Productbatch($this->db);
@ -932,7 +932,7 @@ class MouvementStock extends CommonObject
return $result;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return Url link of origin object
*
@ -942,8 +942,8 @@ class MouvementStock extends CommonObject
*/
public function get_origin($fk_origin, $origintype)
{
// phpcs:enable
$origin = '';
// phpcs:enable
$origin = '';
switch ($origintype) {
case 'commande':
@ -982,10 +982,10 @@ class MouvementStock extends CommonObject
default:
if ($origintype)
{
// Separate originetype with "@" : left part is class name, right part is module name
$origintype_array = explode('@', $origintype);
$classname = ucfirst($origintype_array[0]);
$modulename = empty($origintype_array[1]) ? $classname : $origintype_array[1];
// Separate originetype with "@" : left part is class name, right part is module name
$origintype_array = explode('@', $origintype);
$classname = ucfirst($origintype_array[0]);
$modulename = empty($origintype_array[1]) ? $classname : $origintype_array[1];
$result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php');
if ($result)
{
@ -1034,21 +1034,21 @@ class MouvementStock extends CommonObject
/**
* Initialise an instance with random values.
* Used to build previews or test instances.
* id must be 0 if object instance is a specimen.
*
* @return void
*/
public function initAsSpecimen()
{
global $user, $langs, $conf, $mysoc;
* Initialise an instance with random values.
* Used to build previews or test instances.
* id must be 0 if object instance is a specimen.
*
* @return void
*/
public function initAsSpecimen()
{
global $user, $langs, $conf, $mysoc;
// Initialize parameters
$this->id = 0;
// Initialize parameters
$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)
@ -1099,7 +1099,7 @@ class MouvementStock extends CommonObject
return $this->LibStatut($mode);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Renvoi le libelle d'un status donne
*
@ -1108,7 +1108,7 @@ class MouvementStock extends CommonObject
*/
public function LibStatut($mode = 0)
{
// phpcs:enable
// phpcs:enable
global $langs;
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->global->MEMBER_ENABLE_PUBLIC)) {
print $langs->trans("Auto subscription form for public visitors has not been enabled");
exit;
print $langs->trans("Auto subscription form for public visitors has not been enabled");
exit;
}
// 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 = '')
{
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
$urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png';
// Define urllogo
$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)) {
$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)) {
$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')) {
$urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg';
}
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);
} 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);
} elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) {
$urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg';
}
print '<div class="center">';
// Output html code for logo
if ($urllogo) {
print '<div class="backgreypublicpayment">';
print '<div class="logopublicpayment">';
print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
print '>';
print '</div>';
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>';
}
print '</div>';
// Output html code for logo
if ($urllogo) {
print '<div class="backgreypublicpayment">';
print '<div class="logopublicpayment">';
print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
print '>';
print '</div>';
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>';
}
print '</div>';
print '<div class="divmainbodylarge">';
print '<div class="divmainbodylarge">';
}
/**
@ -139,12 +139,12 @@ function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $
*/
function llxFooterVierge()
{
print '</div>';
print '</div>';
printCommonFooter('public');
printCommonFooter('public');
print "</body>\n";
print "</html>\n";
print "</body>\n";
print "</html>\n";
}
@ -156,7 +156,7 @@ $parameters = array();
// Note that $action and $object may have been modified by some hooks
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
// Action called when page is submitted
@ -166,164 +166,164 @@ if (empty($reshook) && $action == 'add') {
$db->begin();
// test if login already exists
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
if (!GETPOST('login')) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"))."<br>\n";
}
$sql = "SELECT login FROM ".MAIN_DB_PREFIX."adherent WHERE login='".$db->escape(GETPOST('login'))."'";
$result = $db->query($sql);
if ($result) {
$num = $db->num_rows($result);
}
if ($num != 0) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorLoginAlreadyExists")."<br>\n";
}
if (!isset($_POST["pass1"]) || !isset($_POST["pass2"]) || $_POST["pass1"] == '' || $_POST["pass2"] == '' || $_POST["pass1"] != $_POST["pass2"]) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorPasswordsMustMatch")."<br>\n";
}
if (!GETPOST("email")) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."<br>\n";
}
}
if (GETPOST('type') <= 0) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."<br>\n";
}
if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."<br>\n";
}
if (empty($_POST["lastname"])) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."<br>\n";
}
if (empty($_POST["firstname"])) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."<br>\n";
}
if (GETPOST("email") && !isValidEmail(GETPOST("email"))) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."<br>\n";
}
$birthday = dol_mktime($_POST["birthhour"], $_POST["birthmin"], $_POST["birthsec"], $_POST["birthmonth"], $_POST["birthday"], $_POST["birthyear"]);
if ($_POST["birthmonth"] && empty($birthday)) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorBadDateFormat")."<br>\n";
}
if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) {
if (GETPOST("morphy") == 'mor' && GETPOST('budget') <= 0) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TurnoverOrBudget"))."<br>\n";
}
}
// test if login already exists
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
if (!GETPOST('login')) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"))."<br>\n";
}
$sql = "SELECT login FROM ".MAIN_DB_PREFIX."adherent WHERE login='".$db->escape(GETPOST('login'))."'";
$result = $db->query($sql);
if ($result) {
$num = $db->num_rows($result);
}
if ($num != 0) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorLoginAlreadyExists")."<br>\n";
}
if (!isset($_POST["pass1"]) || !isset($_POST["pass2"]) || $_POST["pass1"] == '' || $_POST["pass2"] == '' || $_POST["pass1"] != $_POST["pass2"]) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorPasswordsMustMatch")."<br>\n";
}
if (!GETPOST("email")) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."<br>\n";
}
}
if (GETPOST('type') <= 0) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."<br>\n";
}
if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."<br>\n";
}
if (empty($_POST["lastname"])) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."<br>\n";
}
if (empty($_POST["firstname"])) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."<br>\n";
}
if (GETPOST("email") && !isValidEmail(GETPOST("email"))) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."<br>\n";
}
$birthday = dol_mktime($_POST["birthhour"], $_POST["birthmin"], $_POST["birthsec"], $_POST["birthmonth"], $_POST["birthday"], $_POST["birthyear"]);
if ($_POST["birthmonth"] && empty($birthday)) {
$error++;
$langs->load("errors");
$errmsg .= $langs->trans("ErrorBadDateFormat")."<br>\n";
}
if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) {
if (GETPOST("morphy") == 'mor' && GETPOST('budget') <= 0) {
$error++;
$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TurnoverOrBudget"))."<br>\n";
}
}
if (isset($public)) $public = 1;
else $public = 0;
if (isset($public)) $public = 1;
else $public = 0;
if (!$error) {
// email a peu pres correct et le login n'existe pas
$adh = new Adherent($db);
$adh->statut = -1;
$adh->public = $public;
$adh->firstname = $_POST["firstname"];
$adh->lastname = $_POST["lastname"];
$adh->gender = $_POST["gender"];
$adh->civility_id = $_POST["civility_id"];
$adh->societe = $_POST["societe"];
$adh->address = $_POST["address"];
$adh->zip = $_POST["zipcode"];
$adh->town = $_POST["town"];
$adh->email = $_POST["email"];
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
$adh->login = $_POST["login"];
$adh->pass = $_POST["pass1"];
}
$adh->photo = $_POST["photo"];
$adh->country_id = $_POST["country_id"];
$adh->state_id = $_POST["state_id"];
$adh->typeid = $_POST["type"];
$adh->note_private = $_POST["note_private"];
$adh->morphy = $_POST["morphy"];
$adh->birth = $birthday;
if (!$error) {
// email a peu pres correct et le login n'existe pas
$adh = new Adherent($db);
$adh->statut = -1;
$adh->public = $public;
$adh->firstname = $_POST["firstname"];
$adh->lastname = $_POST["lastname"];
$adh->gender = $_POST["gender"];
$adh->civility_id = $_POST["civility_id"];
$adh->societe = $_POST["societe"];
$adh->address = $_POST["address"];
$adh->zip = $_POST["zipcode"];
$adh->town = $_POST["town"];
$adh->email = $_POST["email"];
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
$adh->login = $_POST["login"];
$adh->pass = $_POST["pass1"];
}
$adh->photo = $_POST["photo"];
$adh->country_id = $_POST["country_id"];
$adh->state_id = $_POST["state_id"];
$adh->typeid = $_POST["type"];
$adh->note_private = $_POST["note_private"];
$adh->morphy = $_POST["morphy"];
$adh->birth = $birthday;
// Fill array 'array_options' with data from add form
$extrafields->fetch_name_optionals_label($adh->table_element);
$ret = $extrafields->setOptionalsFromPost(null, $adh);
// Fill array 'array_options' with data from add form
$extrafields->fetch_name_optionals_label($adh->table_element);
$ret = $extrafields->setOptionalsFromPost(null, $adh);
if ($ret < 0) $error++;
$result = $adh->create($user);
if ($result > 0) {
$result = $adh->create($user);
if ($result > 0) {
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
$object = $adh;
$object = $adh;
$adht = new AdherentType($db);
$adht->fetch($object->typeid);
$adht = new AdherentType($db);
$adht->fetch($object->typeid);
if ($object->email) {
$subject = '';
$msg = '';
if ($object->email) {
$subject = '';
$msg = '';
// Send subscription email
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
// Set output language
$outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
// Load traductions files required by page
$outputlangs->loadLangs(array("main", "members"));
// Get email content from template
$arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_AUTOREGISTER;
// Send subscription email
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
// Set output language
$outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
// Load traductions files required by page
$outputlangs->loadLangs(array("main", "members"));
// Get email content from template
$arraydefaultmessage = null;
$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) {
$subject = $arraydefaultmessage->topic;
$msg = $arraydefaultmessage->content;
}
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic;
$msg = $arraydefaultmessage->content;
}
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
complete_substitutions_array($substitutionarray, $outputlangs, $object);
$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnValid()), $substitutionarray, $outputlangs);
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
complete_substitutions_array($substitutionarray, $outputlangs, $object);
$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnValid()), $substitutionarray, $outputlangs);
if ($subjecttosend && $texttosend) {
$moreinheader = 'X-Dolibarr-Info: send_an_email by public/members/new.php'."\r\n";
if ($subjecttosend && $texttosend) {
$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);
}
/*if ($result < 0) {
$result = $object->send_an_email($texttosend, $subjecttosend, array(), array(), array(), "", "", 0, -1, '', $moreinheader);
}
/*if ($result < 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}*/
}
}
// 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) &&
!empty($conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL)) {
// Define link to login card
$appli = constant('DOL_APPLICATION_TITLE');
if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
$appli = $conf->global->MAIN_APPLICATION_TITLE;
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
} else $appli .= " ".DOL_VERSION;
} else {
// 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) &&
!empty($conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL)) {
// Define link to login card
$appli = constant('DOL_APPLICATION_TITLE');
if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
$appli = $conf->global->MAIN_APPLICATION_TITLE;
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
} else $appli .= " ".DOL_VERSION;
} else {
$appli .= " ".DOL_VERSION;
}
}
$to = $adh->makeSubstitution($conf->global->MAIN_INFO_SOCIETE_MAIL);
$from = $conf->global->ADHERENT_MAIL_FROM;
$to = $adh->makeSubstitution($conf->global->MAIN_INFO_SOCIETE_MAIL);
$from = $conf->global->ADHERENT_MAIL_FROM;
$mailfile = new CMailFile(
'['.$appli.'] '.$conf->global->ADHERENT_AUTOREGISTER_NOTIF_MAIL_SUBJECT,
$to,
@ -338,103 +338,103 @@ if (empty($reshook) && $action == 'add') {
-1
);
if (!$mailfile->sendfile()) {
dol_syslog($langs->trans("ErrorFailedToSendMail", $from, $to), LOG_ERR);
}
}
if (!$mailfile->sendfile()) {
dol_syslog($langs->trans("ErrorFailedToSendMail", $from, $to), LOG_ERR);
}
}
if (!empty($backtopage)) {
if (!empty($backtopage)) {
$urlback = $backtopage;
} elseif (!empty($conf->global->MEMBER_URL_REDIRECT_SUBSCRIPTION)) {
$urlback = $conf->global->MEMBER_URL_REDIRECT_SUBSCRIPTION;
// TODO Make replacement of __AMOUNT__, etc...
} else {
$urlback = $conf->global->MEMBER_URL_REDIRECT_SUBSCRIPTION;
// TODO Make replacement of __AMOUNT__, etc...
} else {
$urlback = $_SERVER["PHP_SELF"]."?action=added";
}
if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) && $conf->global->MEMBER_NEWFORM_PAYONLINE != '-1') {
if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'all') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paybox') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paypal') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'stripe') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} else {
dol_print_error('', "Autosubscribe form is setup to ask an online payment for a not managed online payment");
exit;
}
}
if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) && $conf->global->MEMBER_NEWFORM_PAYONLINE != '-1') {
if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'all') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paybox') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paypal') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'stripe') {
$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 (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email'));
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2));
} else {
$urlback .= '&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN);
}
}
} else {
dol_print_error('', "Autosubscribe form is setup to ask an online payment for a not managed online payment");
exit;
}
}
if (!empty($entity)) $urlback .= '&entity='.$entity;
dol_syslog("member ".$adh->ref." was created, we redirect to ".$urlback);
} else {
$error++;
$errmsg .= join('<br>', $adh->errors);
}
}
if (!empty($entity)) $urlback .= '&entity='.$entity;
dol_syslog("member ".$adh->ref." was created, we redirect to ".$urlback);
} else {
$error++;
$errmsg .= join('<br>', $adh->errors);
}
}
if (!$error) {
$db->commit();
if (!$error) {
$db->commit();
Header("Location: ".$urlback);
exit;
} else {
$db->rollback();
}
Header("Location: ".$urlback);
exit;
} else {
$db->rollback();
}
}
// 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.
// 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') {
llxHeaderVierge($langs->trans("NewMemberForm"));
llxHeaderVierge($langs->trans("NewMemberForm"));
// Si on a pas ete redirige
print '<br>';
print '<div class="center">';
print $langs->trans("NewMemberbyWeb");
print '</div>';
// Si on a pas ete redirige
print '<br>';
print '<div class="center">';
print $langs->trans("NewMemberbyWeb");
print '</div>';
llxFooterVierge();
exit;
llxFooterVierge();
exit;
}
@ -460,9 +460,9 @@ print '<div id="divsubscribe">';
print '<div class="center subscriptionformhelptext justify">';
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 {
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>';
@ -510,31 +510,31 @@ print '<table class="border" summary="form to subscribe" id="tablesubscribe">'."
// Type
if (empty($conf->global->MEMBER_NEWFORM_FORCETYPE)) {
$listoftype = $adht->liste_array();
$tmp = array_keys($listoftype);
$defaulttype = '';
$isempty = 1;
if (count($listoftype) == 1) {
$listoftype = $adht->liste_array();
$tmp = array_keys($listoftype);
$defaulttype = '';
$isempty = 1;
if (count($listoftype) == 1) {
$defaulttype = $tmp[0];
$isempty = 0;
}
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 '</td></tr>'."\n";
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 '</td></tr>'."\n";
} else {
$adht->fetch($conf->global->MEMBER_NEWFORM_FORCETYPE);
print '<input type="hidden" id="type" name="type" value="'.$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.'">';
}
// Moral/Physic attribute
$morphys["phy"] = $langs->trans("Physical");
$morphys["mor"] = $langs->trans("Moral");
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 $form->selectarray("morphy", $morphys, GETPOST('morphy'), 1);
print '</td></tr>'."\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 '</td></tr>'."\n";
} else {
print $morphys[$conf->global->MEMBER_NEWFORM_FORCEMORPHY];
print '<input type="hidden" id="morphy" name="morphy" value="'.$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.'">';
}
// Civility
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>';
$country_id = GETPOST('country_id');
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)) {
$country_code = dol_user_country();
//print $country_code;
if ($country_code) {
$new_country_id = getCountry($country_code, 3, $db, $langs);
//print 'xxx'.$country_code.' - '.$new_country_id;
if ($new_country_id) $country_id = $new_country_id;
}
$country_code = dol_user_country();
//print $country_code;
if ($country_code) {
$new_country_id = getCountry($country_code, 3, $db, $langs);
//print 'xxx'.$country_code.' - '.$new_country_id;
if ($new_country_id) $country_id = $new_country_id;
}
}
$country_code = getCountry($country_id, 2, $db, $langs);
print $form->select_country($country_id, 'country_id');
print '</td></tr>';
// State
if (empty($conf->global->SOCIETE_DISABLE_STATE)) {
print '<tr><td>'.$langs->trans('State').'</td><td>';
if ($country_code) print $formcompany->select_state(GETPOST("state_id"), $country_code);
else print '';
print '</td></tr>';
print '<tr><td>'.$langs->trans('State').'</td><td>';
if ($country_code) print $formcompany->select_state(GETPOST("state_id"), $country_code);
else print '';
print '</td></tr>';
}
// 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";
// Login
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("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("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("PasswordAgain").' <FONT COLOR="red">*</FONT></td><td><input type="password" maxlength="128" name="pass2" class="minwidth100" value="'.GETPOST("pass2").'"></td></tr>'."\n";
}
// Birthday
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
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+');
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 ' € or $';
$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 $form->selectarray('budget', $arraybudget, GETPOST('budget'), 1);
print ' € or $';
print '<script type="text/javascript">
print '<script type="text/javascript">
jQuery(document).ready(function () {
initturnover();
jQuery("#morphy").click(function() {
@ -651,28 +651,28 @@ if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) {
}
});
</script>';
print '</td></tr>'."\n";
print '</td></tr>'."\n";
}
if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT) || !empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) {
// $conf->global->MEMBER_NEWFORM_SHOWAMOUNT is an amount
$amount = 0;
if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) {
$amount = $conf->global->MEMBER_NEWFORM_AMOUNT;
}
// $conf->global->MEMBER_NEWFORM_SHOWAMOUNT is an amount
$amount = 0;
if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) {
$amount = $conf->global->MEMBER_NEWFORM_AMOUNT;
}
if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) {
$amount = GETPOST('amount') ?GETPOST('amount') : $conf->global->MEMBER_NEWFORM_AMOUNT;
}
// $conf->global->MEMBER_NEWFORM_PAYONLINE is 'paypal', 'paybox' or 'stripe'
print '<tr><td>'.$langs->trans("Subscription").'</td><td class="nowrap">';
if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) {
print '<input type="text" name="amount" id="amount" class="flat amount" size="6" value="'.$amount.'">';
} else {
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 ' '.$langs->trans("Currency".$conf->currency);
print '</td></tr>';
if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) {
$amount = GETPOST('amount') ?GETPOST('amount') : $conf->global->MEMBER_NEWFORM_AMOUNT;
}
// $conf->global->MEMBER_NEWFORM_PAYONLINE is 'paypal', 'paybox' or 'stripe'
print '<tr><td>'.$langs->trans("Subscription").'</td><td class="nowrap">';
if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) {
print '<input type="text" name="amount" id="amount" class="flat amount" size="6" value="'.$amount.'">';
} else {
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 ' '.$langs->trans("Currency".$conf->currency);
print '</td></tr>';
}
print "</table>\n";
@ -682,7 +682,7 @@ print dol_get_fiche_end();
print '<div class="center">';
print '<input type="submit" value="'.$langs->trans("Submit").'" id="submitsave" class="button">';
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>';

View File

@ -64,11 +64,11 @@ if (empty($source)) $source = 'proposal';
if (!$action)
{
if ($source && !$ref)
{
print $langs->trans('ErrorBadParameters')." - ref missing";
exit;
}
if ($source && !$ref)
{
print $langs->trans('ErrorBadParameters')." - ref missing";
exit;
}
}
@ -83,18 +83,18 @@ $SECUREKEY = GETPOST("securekey"); // Secure key
if (!empty($source))
{
$urlok .= 'source='.urlencode($source).'&';
$urlko .= 'source='.urlencode($source).'&';
$urlok .= 'source='.urlencode($source).'&';
$urlko .= 'source='.urlencode($source).'&';
}
if (!empty($REF))
{
$urlok .= 'ref='.urlencode($REF).'&';
$urlko .= 'ref='.urlencode($REF).'&';
$urlok .= 'ref='.urlencode($REF).'&';
$urlko .= 'ref='.urlencode($REF).'&';
}
if (!empty($SECUREKEY))
{
$urlok .= 'securekey='.urlencode($SECUREKEY).'&';
$urlko .= 'securekey='.urlencode($SECUREKEY).'&';
$urlok .= 'securekey='.urlencode($SECUREKEY).'&';
$urlko .= 'securekey='.urlencode($SECUREKEY).'&';
}
if (!empty($entity))
{
@ -114,7 +114,7 @@ $creditor = $mysoc->name;
if ($action == 'dosign')
{
// TODO
// TODO
}
@ -134,12 +134,12 @@ llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'on
// Check link validity for param 'source'
if (!empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', '')))
{
$langs->load("errors");
dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref));
// End of page
llxFooter();
$db->close();
exit;
$langs->load("errors");
dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref));
// End of page
llxFooter();
$db->close();
exit;
}
print '<span id="dolpaymentspan"></span>'."\n";
@ -194,16 +194,16 @@ if ($urllogo)
$text = '';
if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT))
{
$langs->load("members");
$reg = array();
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";
$text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
$langs->load("members");
$reg = array();
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";
$text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
}
if (empty($text))
{
$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"><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";
}
print $text;
@ -237,9 +237,9 @@ if ($source == 'proposal')
// 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 '<input type="hidden" name="creditor" value="'.$creditor.'">';
print '</td></tr>'."\n";
print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>';
print '<input type="hidden" name="creditor" value="'.$creditor.'">';
print '</td></tr>'."\n";
// Debitor
@ -266,13 +266,13 @@ print '</table>'."\n";
print "\n";
if ($action != 'dosign') {
if ($found && !$error) {
// We are in a management option and no error
} else {
dol_print_error_email('ERRORNEWONLINESIGN');
}
if ($found && !$error) {
// We are in a management option and no error
} else {
dol_print_error_email('ERRORNEWONLINESIGN');
}
} else {
// Print
// Print
}
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');
$error = 0;
$errormessage = '';
$errormessage = '';
// When using the Charge API architecture
if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{
try {
$metadata = array(
'dol_version' => DOL_VERSION,
'dol_entity' => $conf->entity,
'dol_company' => $mysoc->name, // Usefull when using multicompany
'dol_tax_num' => $vatnumber,
'ipaddress'=> getUserRemoteIP()
);
// When using the Charge API architecture
if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{
try {
$metadata = array(
'dol_version' => DOL_VERSION,
'dol_entity' => $conf->entity,
'dol_company' => $mysoc->name, // Usefull when using multicompany
'dol_tax_num' => $vatnumber,
'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)
{
dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe');
if ($thirdparty_id > 0)
{
dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe');
$service = 'StripeTest';
$servicestatus = 0;
if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int'))
{
$service = 'StripeLive';
$servicestatus = 1;
}
$service = 'StripeTest';
$servicestatus = 0;
if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int'))
{
$service = 'StripeLive';
$servicestatus = 1;
}
$thirdparty = new Societe($db);
$thirdparty->fetch($thirdparty_id);
$thirdparty = new Societe($db);
$thirdparty->fetch($thirdparty_id);
// Create Stripe customer
include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
$stripe = new Stripe($db);
$stripeacc = $stripe->getStripeAccount($service);
$customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
// Create Stripe customer
include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
$stripe = new Stripe($db);
$stripeacc = $stripe->getStripeAccount($service);
$customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
if (empty($customer))
{
$error++;
@ -461,51 +461,51 @@ if ($action == 'charge' && !empty($conf->stripe->enabled))
$action = '';
}
// Create Stripe card from Token
if (!$error)
{
if ($savesource) {
$card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata));
} else {
$card = $stripeToken;
}
// Create Stripe card from Token
if (!$error)
{
if ($savesource) {
$card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata));
} else {
$card = $stripeToken;
}
if (empty($card))
{
$error++;
dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to create card record', null, 'errors');
$action = '';
} else {
if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG;
if (!empty($dol_id)) $metadata["dol_id"] = $dol_id;
if (!empty($dol_type)) $metadata["dol_type"] = $dol_type;
if (empty($card))
{
$error++;
dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to create card record', null, 'errors');
$action = '';
} else {
if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG;
if (!empty($dol_id)) $metadata["dol_id"] = $dol_id;
if (!empty($dol_type)) $metadata["dol_type"] = $dol_type;
dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe');
$charge = \Stripe\Charge::create(array(
'amount' => price2num($amountstripe, 'MU'),
'currency' => $currency,
'capture' => true, // Charge immediatly
'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref,
'metadata' => $metadata,
'customer' => $customer->id,
'source' => $card,
'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"));
// Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
if (empty($charge))
{
$error++;
dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to charge card', null, 'errors');
$action = '';
}
}
}
} else {
$vatcleaned = $vatnumber ? $vatnumber : null;
dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe');
$charge = \Stripe\Charge::create(array(
'amount' => price2num($amountstripe, 'MU'),
'currency' => $currency,
'capture' => true, // Charge immediatly
'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref,
'metadata' => $metadata,
'customer' => $customer->id,
'source' => $card,
'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"));
// Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
if (empty($charge))
{
$error++;
dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to charge card', null, 'errors');
$action = '';
}
}
}
} else {
$vatcleaned = $vatnumber ? $vatnumber : null;
/*$taxinfo = array('type'=>'vat');
/*$taxinfo = array('type'=>'vat');
if ($vatcleaned)
{
$taxinfo["tax_id"] = $vatcleaned;
@ -514,18 +514,18 @@ if ($action == 'charge' && !empty($conf->stripe->enabled))
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(
'email' => $email,
'description' => ($email ? 'Anonymous customer for '.$email : 'Anonymous customer'),
'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 ?)
));
// Return $customer = array('id'=>'cus_XXXX', ...)
$customer = \Stripe\Customer::create(array(
'email' => $email,
'description' => ($email ? 'Anonymous customer for '.$email : 'Anonymous customer'),
'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 ?)
));
// Return $customer = array('id'=>'cus_XXXX', ...)
// Create the VAT record in Stripe
/* We don't know country of customer, so we can't create tax
// Create the VAT record in Stripe
/* 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($vatcleaned))
@ -539,145 +539,145 @@ if ($action == 'charge' && !empty($conf->stripe->enabled))
}
}*/
if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG;
if (!empty($dol_id)) $metadata["dol_id"] = $dol_id;
if (!empty($dol_type)) $metadata["dol_type"] = $dol_type;
if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG;
if (!empty($dol_id)) $metadata["dol_id"] = $dol_id;
if (!empty($dol_type)) $metadata["dol_type"] = $dol_type;
// 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.
dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe');
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => price2num($amountstripe, 'MU'),
'currency' => $currency,
'capture' => true, // Charge immediatly
'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref,
'metadata' => $metadata,
'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"));
// Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
if (empty($charge))
{
$error++;
dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to charge card', null, 'errors');
$action = '';
}
}
} catch (\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
// 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.
dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe');
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => price2num($amountstripe, 'MU'),
'currency' => $currency,
'capture' => true, // Charge immediatly
'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref,
'metadata' => $metadata,
'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"));
// Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
if (empty($charge))
{
$error++;
dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe');
setEventMessages('Failed to charge card', null, 'errors');
$action = '';
}
}
} catch (\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:'.$e->getHttpStatus()."\n");
print('Type is:'.$err['type']."\n");
print('Code is:'.$err['code']."\n");
// param is '' in this case
print('Param is:'.$err['param']."\n");
print('Message is:'.$err['message']."\n");
print('Status is:'.$e->getHttpStatus()."\n");
print('Type is:'.$err['type']."\n");
print('Code is:'.$err['code']."\n");
// param is '' in this case
print('Param is:'.$err['param']."\n");
print('Message is:'.$err['message']."\n");
$error++;
$errormessage = "ErrorCard ".$e->getMessage()." err=".var_export($err, true);
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
$error++;
$errormessage = "ErrorRateLimit ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
$error++;
$errormessage = "ErrorInvalidRequest ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
$error++;
$errormessage = "ErrorAuthentication ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
$error++;
$errormessage = "ErrorApiConnection ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error++;
$errormessage = "ErrorBase ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error++;
$errormessage = "ErrorException ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
}
}
$error++;
$errormessage = "ErrorCard ".$e->getMessage()." err=".var_export($err, true);
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
$error++;
$errormessage = "ErrorRateLimit ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
$error++;
$errormessage = "ErrorInvalidRequest ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
$error++;
$errormessage = "ErrorAuthentication ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
$error++;
$errormessage = "ErrorApiConnection ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error++;
$errormessage = "ErrorBase ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error++;
$errormessage = "ErrorException ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
}
}
// When using the PaymentIntent API architecture
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{
$service = 'StripeTest';
$servicestatus = 0;
if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int'))
{
$service = 'StripeLive';
$servicestatus = 1;
}
include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
$stripe = new Stripe($db);
$stripeacc = $stripe->getStripeAccount($service);
// When using the PaymentIntent API architecture
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{
$service = 'StripeTest';
$servicestatus = 0;
if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int'))
{
$service = 'StripeLive';
$servicestatus = 1;
}
include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
$stripe = new Stripe($db);
$stripeacc = $stripe->getStripeAccount($service);
// 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.
$paymentintent_id = GETPOST("paymentintent_id", "alpha");
// 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.
$paymentintent_id = GETPOST("paymentintent_id", "alpha");
// Force to use the correct API key
global $stripearrayofkeysbyenv;
\Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
// Force to use the correct API key
global $stripearrayofkeysbyenv;
\Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
try {
if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
$paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id);
} else {
$paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id, array("stripe_account" => $stripeacc));
}
} catch (Exception $e)
{
$error++;
$errormessage = "CantRetrievePaymentIntent ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
}
try {
if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
$paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id);
} else {
$paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id, array("stripe_account" => $stripeacc));
}
} catch (Exception $e)
{
$error++;
$errormessage = "CantRetrievePaymentIntent ".$e->getMessage();
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($e->getMessage(), null, 'errors');
$action = '';
}
if ($paymentintent->status != 'succeeded')
{
$error++;
$errormessage = "StatusOfRetrievedIntent is not succeeded: ".$paymentintent->status;
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($paymentintent->status, null, 'errors');
$action = '';
} else {
// 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.
//dol_syslog("Create payment_method for ".$paymentintent->payment_method, LOG_DEBUG, 0, '_stripe');
}
}
if ($paymentintent->status != 'succeeded')
{
$error++;
$errormessage = "StatusOfRetrievedIntent is not succeeded: ".$paymentintent->status;
dol_syslog($errormessage, LOG_WARNING, 0, '_stripe');
setEventMessages($paymentintent->status, null, 'errors');
$action = '';
} else {
// 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.
//dol_syslog("Create payment_method for ".$paymentintent->payment_method, LOG_DEBUG, 0, '_stripe');
}
}
$remoteip = getUserRemoteIP();
@ -727,8 +727,8 @@ if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_r
$langs->load("errors");
dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref));
// End of page
llxFooter();
$db->close();
llxFooter();
$db->close();
exit;
}
@ -1394,9 +1394,9 @@ if ($source == 'membersubscription')
print '</td></tr>'."\n";
if ($object->datefin > 0) {
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></tr>'."\n";
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></tr>'."\n";
}
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>';
} else {
// Membership can be paid and we still allow to make renewal
if ($source == 'membersubscription' && $object->datefin > dol_now())
{
$langs->load("members");
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>';
}
// Membership can be paid and we still allow to make renewal
if ($source == 'membersubscription' && $object->datefin > dol_now())
{
$langs->load("members");
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>';
}
// 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))
//{
print '
print '
<table id="dolpaymenttable" summary="Payment form" class="center">
<tbody><tr><td class="textpublicpayment">';
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{
print '<div id="payment-request-button"><!-- A Stripe Element will be inserted here. --></div>';
}
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 class="form-row left">';
print '<label for="card-element">'.$langs->trans("CreditOrDebitCard").'</label>';
print '<div class="form-row left">';
print '<label for="card-element">'.$langs->trans("CreditOrDebitCard").'</label>';
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>';
}
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 '<div id="card-element">
print '<div id="card-element">
<!-- a Stripe Element will be inserted here. -->
</div>';
print '<!-- Used to display form errors -->
print '<!-- Used to display form errors -->
<div id="card-errors" role="alert"></div>
</div>';
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 '<img id="hourglasstopay" class="hidden" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/working.gif">';
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 '<img id="hourglasstopay" class="hidden" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/working.gif">';
print '</td></tr></tbody>';
print '</table>';
print '</td></tr></tbody>';
print '</table>';
//}
if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION))
{
if (empty($paymentintent))
{
print '<center>'.$langs->trans("Error").'</center>';
} else {
print '<input type="hidden" name="paymentintent_id" value="'.$paymentintent->id.'">';
//$_SESSION["paymentintent_id"] = $paymentintent->id;
}
if (empty($paymentintent))
{
print '<center>'.$langs->trans("Error").'</center>';
} else {
print '<input type="hidden" name="paymentintent_id" value="'.$paymentintent->id.'">';
//$_SESSION["paymentintent_id"] = $paymentintent->id;
}
}
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');
} else {
print '<!-- JS Code for Stripe components -->';
print '<script src="https://js.stripe.com/v3/"></script>'."\n";
print '<!-- urllogofull = '.$urllogofull.' -->'."\n";
print '<script src="https://js.stripe.com/v3/"></script>'."\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.
print '<script type="text/javascript" language="javascript">'."\n";
// 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";
if (!empty($conf->global->STRIPE_USE_NEW_CHECKOUT))
{
$amountstripe = $amount;
if (!empty($conf->global->STRIPE_USE_NEW_CHECKOUT))
{
$amountstripe = $amount;
// Correct the amount according to unit of currency
// 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');
if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100;
// Correct the amount according to unit of currency
// 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');
if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100;
$ipaddress = getUserRemoteIP();
$metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
if (is_object($object))
{
$metadata['dol_type'] = $object->element;
$metadata['dol_id'] = $object->id;
$ipaddress = getUserRemoteIP();
$metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
if (is_object($object))
{
$metadata['dol_type'] = $object->element;
$metadata['dol_id'] = $object->id;
$ref = $object->ref;
}
$ref = $object->ref;
}
try {
$arrayforpaymentintent = array(
'description'=>'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''),
"metadata" => $metadata
);
if ($TAG) $arrayforpaymentintent["statement_descriptor"] = dol_trunc($TAG, 10, 'right', 'UTF-8', 1); // 22 chars that appears on bank receipt (company + description)
try {
$arrayforpaymentintent = array(
'description'=>'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''),
"metadata" => $metadata
);
if ($TAG) $arrayforpaymentintent["statement_descriptor"] = dol_trunc($TAG, 10, 'right', 'UTF-8', 1); // 22 chars that appears on bank receipt (company + description)
$arrayforcheckout = array(
'payment_method_types' => array('card'),
'line_items' => array(array(
'name' => $langs->transnoentitiesnoconv("Payment").' '.$TAG, // Label of product line
'description' => 'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''),
'amount' => $amountstripe,
'currency' => $currency,
//'images' => array($urllogofull),
'quantity' => 1,
)),
'client_reference_id' => $FULLTAG,
'success_url' => $urlok,
'cancel_url' => $urlko,
'payment_intent_data' => $arrayforpaymentintent
);
if ($stripecu) $arrayforcheckout['customer'] = $stripecu;
elseif (GETPOST('email', 'alpha') && isValidEmail(GETPOST('email', 'alpha'))) $arrayforcheckout['customer_email'] = GETPOST('email', 'alpha');
$sessionstripe = \Stripe\Checkout\Session::create($arrayforcheckout);
$arrayforcheckout = array(
'payment_method_types' => array('card'),
'line_items' => array(array(
'name' => $langs->transnoentitiesnoconv("Payment").' '.$TAG, // Label of product line
'description' => 'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''),
'amount' => $amountstripe,
'currency' => $currency,
//'images' => array($urllogofull),
'quantity' => 1,
)),
'client_reference_id' => $FULLTAG,
'success_url' => $urlok,
'cancel_url' => $urlko,
'payment_intent_data' => $arrayforpaymentintent
);
if ($stripecu) $arrayforcheckout['customer'] = $stripecu;
elseif (GETPOST('email', 'alpha') && isValidEmail(GETPOST('email', 'alpha'))) $arrayforcheckout['customer_email'] = GETPOST('email', 'alpha');
$sessionstripe = \Stripe\Checkout\Session::create($arrayforcheckout);
$remoteip = getUserRemoteIP();
$remoteip = getUserRemoteIP();
// Save some data for the paymentok
$_SESSION["currencyCodeType"] = $currency;
$_SESSION["paymentType"] = '';
$_SESSION["FinalPaymentAmt"] = $amount;
$_SESSION['ipaddress'] = ($remoteip ? $remoteip : 'unknown'); // Payer ip
$_SESSION['payerID'] = is_object($stripecu) ? $stripecu->id : '';
$_SESSION['TRANSACTIONID'] = $sessionstripe->id;
} catch (Exception $e)
{
print $e->getMessage();
}
?>
// Save some data for the paymentok
$_SESSION["currencyCodeType"] = $currency;
$_SESSION["paymentType"] = '';
$_SESSION["FinalPaymentAmt"] = $amount;
$_SESSION['ipaddress'] = ($remoteip ? $remoteip : 'unknown'); // Payer ip
$_SESSION['payerID'] = is_object($stripecu) ? $stripecu->id : '';
$_SESSION['TRANSACTIONID'] = $sessionstripe->id;
} catch (Exception $e)
{
print $e->getMessage();
}
?>
// Code for payment with option STRIPE_USE_NEW_CHECKOUT set
// Create a Stripe client.
@ -2024,9 +2024,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
<?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
// Create a Stripe client.
@ -2129,9 +2129,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
});
<?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
// 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) {
event.preventDefault();
<?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 */
stripe.createToken(card).then(function(result) {
if (result.error) {
@ -2196,9 +2196,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
}
});
<?php
} else // Ask credit card with 3DS test
{
?>
} else // Ask credit card with 3DS test
{
?>
/* Use 3DS source */
stripe.createSource(card).then(function(result) {
if (result.error) {
@ -2211,8 +2211,8 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
}
});
<?php
}
?>
}
?>
});
@ -2265,9 +2265,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
}
<?php
}
}
print '</script>';
print '</script>';
}
}
// 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')) {
define('NOCSRFCHECK', '1');
define('NOCSRFCHECK', '1');
}
// Do not check anti CSRF attack test
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
define('NOREQUIREMENU', '1');
}
// If there is no need to load and show top and left menu
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('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1');

View File

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

View File

@ -57,7 +57,7 @@ class RecruitmentJobPosition extends CommonObject
*/
public $isextrafieldmanaged = 1;
/**
/**
* @var string String with name of icon for recruitmentjobposition. Must be the part after the 'object_' into object_recruitmentjobposition.png
*/
public $picto = 'recruitmentjobposition';
@ -126,30 +126,30 @@ class RecruitmentJobPosition extends CommonObject
);
public $rowid;
/**
* @var string ref
*/
/**
* @var string ref
*/
public $ref;
public $entity;
/**
* @var string label
*/
/**
* @var string label
*/
public $label;
public $qty;
public $fk_soc;
public $fk_project;
public $fk_user_recruiter;
/**
* @var string recruiter email
*/
public $email_recruiter;
/**
* @var string recruiter email
*/
public $email_recruiter;
/**
* @var string suggested remuneration
*/
public $remuneration_suggested;
/**
* @var string suggested remuneration
*/
public $remuneration_suggested;
public $fk_user_supervisor;
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 ($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);
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);
}
// 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
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">';
foreach ($prospectstatic->cacheprospectstatus as $key => $val)
{
$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 ($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>';
if (!$i) $totalarray['nbfield']++;

View File

@ -40,7 +40,7 @@ if (GETPOSTISSET('status')) {
if (GETPOST('smp-status')) {
print '<html lang="en">';
print '<head>';
print '<meta charset="utf-8">
print '<meta charset="utf-8">
<title>The HTML5 Herald</title>
<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
if (empty($conf->global->MAIN_MODULE_WEBSERVICES))
{
$langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
print $langs->trans("ToActivateModule");
exit;
$langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
print $langs->trans("ToActivateModule");
exit;
}
// Create the soap Object
@ -57,36 +57,36 @@ $server->wsdl->schemaTargetNamespace = $ns;
// Define WSDL Authentication object
$server->wsdl->addComplexType(
'authentication',
'complexType',
'struct',
'all',
'',
array(
'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'),
'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'),
'login' => array('name'=>'login', 'type'=>'xsd:string'),
'password' => array('name'=>'password', 'type'=>'xsd:string'),
'entity' => array('name'=>'entity', 'type'=>'xsd:string'),
)
'authentication',
'complexType',
'struct',
'all',
'',
array(
'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'),
'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'),
'login' => array('name'=>'login', 'type'=>'xsd:string'),
'password' => array('name'=>'password', 'type'=>'xsd:string'),
'entity' => array('name'=>'entity', 'type'=>'xsd:string'),
)
);
// Define WSDL Return object
$server->wsdl->addComplexType(
'result',
'complexType',
'struct',
'all',
'',
array(
'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'),
'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'),
)
'result',
'complexType',
'struct',
'all',
'',
array(
'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'),
'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'),
)
);
$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_ext' => array('name'=>'ref_ext', '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
$server->wsdl->addComplexType(
'actioncomm',
'complexType',
'struct',
'all',
'',
'actioncomm',
'complexType',
'struct',
'all',
'',
$actioncomm_fields
);
@ -165,12 +165,12 @@ $server->wsdl->addComplexType(
'sequence',
'',
array(
'actioncommtype' => array(
'name' => 'actioncommtype',
'type' => 'tns:actioncommtype',
'minOccurs' => '0',
'maxOccurs' => 'unbounded'
)
'actioncommtype' => array(
'name' => 'actioncommtype',
'type' => 'tns:actioncommtype',
'minOccurs' => '0',
'maxOccurs' => 'unbounded'
)
)
);
@ -199,16 +199,16 @@ $server->register(
// Register WSDL
$server->register(
'getActionComm',
// Entry values
array('authentication'=>'tns:authentication', 'id'=>'xsd:string'),
// Exit values
array('result'=>'tns:result', 'actioncomm'=>'tns:actioncomm'),
$ns,
$ns.'#getActionComm',
$styledoc,
$styleuse,
'WS to get actioncomm'
'getActionComm',
// Entry values
array('authentication'=>'tns:authentication', 'id'=>'xsd:string'),
// Exit values
array('result'=>'tns:result', 'actioncomm'=>'tns:actioncomm'),
$ns,
$ns.'#getActionComm',
$styledoc,
$styleuse,
'WS to get actioncomm'
);
// Register WSDL
@ -251,100 +251,100 @@ $server->register(
*/
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
$objectresp = array();
$errorcode = ''; $errorlabel = '';
$error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters
if ($error || (!$id))
{
$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.";
}
// Init and check authentication
$objectresp = array();
$errorcode = ''; $errorlabel = '';
$error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters
if ($error || (!$id))
{
$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.";
}
if (!$error)
{
$fuser->getrights();
if (!$error)
{
$fuser->getrights();
if ($fuser->rights->agenda->allactions->read)
{
$actioncomm = new ActionComm($db);
$result = $actioncomm->fetch($id);
if ($result > 0)
{
$actioncomm_result_fields = array(
if ($fuser->rights->agenda->allactions->read)
{
$actioncomm = new ActionComm($db);
$result = $actioncomm->fetch($id);
if ($result > 0)
{
$actioncomm_result_fields = array(
'id' => $actioncomm->id,
'ref'=> $actioncomm->ref,
'ref_ext'=> $actioncomm->ref_ext,
'type_id'=> $actioncomm->type_id,
'type_code'=> $actioncomm->type_code,
'type'=> $actioncomm->type,
'label'=> $actioncomm->label,
'datep'=> dol_print_date($actioncomm->datep, 'dayhourrfc'),
'datef'=> dol_print_date($actioncomm->datef, 'dayhourrfc'),
'datec'=> dol_print_date($actioncomm->datec, 'dayhourrfc'),
'datem'=> dol_print_date($actioncomm->datem, 'dayhourrfc'),
'note'=> $actioncomm->note_private,
'percentage'=> $actioncomm->percentage,
'author'=> $actioncomm->authorid,
'usermod'=> $actioncomm->usermodid,
'userownerid'=> $actioncomm->userownerid,
'priority'=> $actioncomm->priority,
'fulldayevent'=> $actioncomm->fulldayevent,
'location'=> $actioncomm->location,
'socid'=> $actioncomm->socid,
'contactid'=> $actioncomm->contact_id,
'projectid'=> $actioncomm->fk_project,
'fk_element'=> $actioncomm->fk_element,
'elementtype'=> $actioncomm->elementtype
);
'ref_ext'=> $actioncomm->ref_ext,
'type_id'=> $actioncomm->type_id,
'type_code'=> $actioncomm->type_code,
'type'=> $actioncomm->type,
'label'=> $actioncomm->label,
'datep'=> dol_print_date($actioncomm->datep, 'dayhourrfc'),
'datef'=> dol_print_date($actioncomm->datef, 'dayhourrfc'),
'datec'=> dol_print_date($actioncomm->datec, 'dayhourrfc'),
'datem'=> dol_print_date($actioncomm->datem, 'dayhourrfc'),
'note'=> $actioncomm->note_private,
'percentage'=> $actioncomm->percentage,
'author'=> $actioncomm->authorid,
'usermod'=> $actioncomm->usermodid,
'userownerid'=> $actioncomm->userownerid,
'priority'=> $actioncomm->priority,
'fulldayevent'=> $actioncomm->fulldayevent,
'location'=> $actioncomm->location,
'socid'=> $actioncomm->socid,
'contactid'=> $actioncomm->contact_id,
'projectid'=> $actioncomm->fk_project,
'fk_element'=> $actioncomm->fk_element,
'elementtype'=> $actioncomm->elementtype
);
$elementtype = 'actioncomm';
$elementtype = 'actioncomm';
// Retrieve all extrafield for actioncomm
// fetch optionals attributes and labels
$extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true);
//Get extrafield values
$actioncomm->fetch_optionals();
// Retrieve all extrafield for actioncomm
// fetch optionals attributes and labels
$extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true);
//Get extrafield values
$actioncomm->fetch_optionals();
if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['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]));
}
}
if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['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]));
}
}
// Create
$objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''),
'actioncomm'=>$actioncomm_result_fields);
}
else {
$error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
}
}
else {
$error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
}
}
// Create
$objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''),
'actioncomm'=>$actioncomm_result_fields);
}
else {
$error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
}
}
else {
$error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
}
}
if ($error)
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
}
if ($error)
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
}
return $objectresp;
return $objectresp;
}
@ -384,8 +384,8 @@ function getListActionCommType($authentication)
}
$objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''),
'actioncommtypes'=>$resultarray);
'result'=>array('result_code'=>'OK', 'result_label'=>''),
'actioncommtypes'=>$resultarray);
} else {
$error++;
$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
if (empty($conf->global->MAIN_MODULE_WEBSERVICES))
{
$langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
print $langs->trans("ToActivateModule");
exit;
$langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
print $langs->trans("ToActivateModule");
exit;
}
// Create the soap Object
@ -53,31 +53,31 @@ $server->wsdl->schemaTargetNamespace = $ns;
// Define WSDL Authentication object
$server->wsdl->addComplexType(
'authentication',
'complexType',
'struct',
'all',
'',
array(
'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'),
'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'),
'login' => array('name'=>'login', 'type'=>'xsd:string'),
'password' => array('name'=>'password', 'type'=>'xsd:string'),
'entity' => array('name'=>'entity', 'type'=>'xsd:string'),
)
'authentication',
'complexType',
'struct',
'all',
'',
array(
'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'),
'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'),
'login' => array('name'=>'login', 'type'=>'xsd:string'),
'password' => array('name'=>'password', 'type'=>'xsd:string'),
'entity' => array('name'=>'entity', 'type'=>'xsd:string'),
)
);
// Define WSDL Return object
$server->wsdl->addComplexType(
'result',
'complexType',
'struct',
'all',
'',
array(
'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'),
'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'),
)
'result',
'complexType',
'struct',
'all',
'',
array(
'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'),
'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'),
)
);
$contact_fields = array(
@ -142,11 +142,11 @@ if (is_array($extrafield_array)) $contact_fields = array_merge($contact_fields,
// Define other specific objects
$server->wsdl->addComplexType(
'contact',
'complexType',
'struct',
'all',
'',
'contact',
'complexType',
'struct',
'all',
'',
$contact_fields
);
@ -179,16 +179,16 @@ $styleuse = 'encoded'; // encoded/literal/literal wrapped
// Register WSDL
$server->register(
'getContact',
// Entry values
array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref_ext'=>'xsd:string'),
// Exit values
array('result'=>'tns:result', 'contact'=>'tns:contact'),
$ns,
$ns.'#getContact',
$styledoc,
$styleuse,
'WS to get a contact'
'getContact',
// Entry values
array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref_ext'=>'xsd:string'),
// Exit values
array('result'=>'tns:result', 'contact'=>'tns:contact'),
$ns,
$ns.'#getContact',
$styledoc,
$styleuse,
'WS to get a contact'
);
// Register WSDL
@ -243,113 +243,113 @@ $server->register(
*/
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
$objectresp = array();
$errorcode = ''; $errorlabel = '';
$error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters
if (!$error && ($id && $ref_ext))
{
$error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be both provided. You must choose one or other but not both.";
}
// Init and check authentication
$objectresp = array();
$errorcode = ''; $errorlabel = '';
$error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters
if (!$error && ($id && $ref_ext))
{
$error++;
$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)
{
$fuser->getrights();
if (!$error)
{
$fuser->getrights();
$contact = new Contact($db);
$result = $contact->fetch($id, 0, $ref_ext);
if ($result > 0)
{
// Only internal user who have contact read permission
// Or for external user who have contact read permission, with restrict on societe_id
if (
$fuser->rights->societe->contact->lire && !$fuser->societe_id
|| ($fuser->rights->societe->contact->lire && ($fuser->societe_id == $contact->socid))
) {
$contact_result_fields = array(
'id' => $contact->id,
'ref_ext' => $contact->ref_ext,
'lastname' => $contact->lastname,
'firstname' => $contact->firstname,
'address' => $contact->address,
'zip' => $contact->zip,
'town' => $contact->town,
'state_id' => $contact->state_id,
'state_code' => $contact->state_code,
'state' => $contact->state,
'country_id' => $contact->country_id,
'country_code' => $contact->country_code,
'country' => $contact->country,
'socid' => $contact->socid,
'status' => $contact->statut,
'phone_pro' => $contact->phone_pro,
'fax' => $contact->fax,
'phone_perso' => $contact->phone_perso,
'phone_mobile' => $contact->phone_mobile,
'code' => $contact->code,
'email' => $contact->email,
'birthday' => $contact->birthday,
'default_lang' => $contact->default_lang,
'note' => $contact->note,
'ref_facturation' => $contact->ref_facturation,
'ref_contrat' => $contact->ref_contrat,
'ref_commande' => $contact->ref_commande,
'ref_propal' => $contact->ref_propal,
'user_id' => $contact->user_id,
'user_login' => $contact->user_login,
'civility_id' => $contact->civility_id,
'poste' => $contact->poste
);
$contact = new Contact($db);
$result = $contact->fetch($id, 0, $ref_ext);
if ($result > 0)
{
// Only internal user who have contact read permission
// Or for external user who have contact read permission, with restrict on societe_id
if (
$fuser->rights->societe->contact->lire && !$fuser->societe_id
|| ($fuser->rights->societe->contact->lire && ($fuser->societe_id == $contact->socid))
) {
$contact_result_fields = array(
'id' => $contact->id,
'ref_ext' => $contact->ref_ext,
'lastname' => $contact->lastname,
'firstname' => $contact->firstname,
'address' => $contact->address,
'zip' => $contact->zip,
'town' => $contact->town,
'state_id' => $contact->state_id,
'state_code' => $contact->state_code,
'state' => $contact->state,
'country_id' => $contact->country_id,
'country_code' => $contact->country_code,
'country' => $contact->country,
'socid' => $contact->socid,
'status' => $contact->statut,
'phone_pro' => $contact->phone_pro,
'fax' => $contact->fax,
'phone_perso' => $contact->phone_perso,
'phone_mobile' => $contact->phone_mobile,
'code' => $contact->code,
'email' => $contact->email,
'birthday' => $contact->birthday,
'default_lang' => $contact->default_lang,
'note' => $contact->note,
'ref_facturation' => $contact->ref_facturation,
'ref_contrat' => $contact->ref_contrat,
'ref_commande' => $contact->ref_commande,
'ref_propal' => $contact->ref_propal,
'user_id' => $contact->user_id,
'user_login' => $contact->user_login,
'civility_id' => $contact->civility_id,
'poste' => $contact->poste
);
$elementtype = 'socpeople';
$elementtype = 'socpeople';
//Retrieve all extrafield for thirdsparty
// fetch optionals attributes and labels
$extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true);
//Get extrafield values
$contact->fetch_optionals();
//Retrieve all extrafield for thirdsparty
// fetch optionals attributes and labels
$extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true);
//Get extrafield values
$contact->fetch_optionals();
if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['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]));
}
}
if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['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]));
}
}
// Create
$objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''),
'contact'=>$contact_result_fields
);
}
else {
$error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
}
}
else {
$error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref_ext='.$ref_ext;
}
}
// Create
$objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''),
'contact'=>$contact_result_fields
);
}
else {
$error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
}
}
else {
$error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref_ext='.$ref_ext;
}
}
if ($error)
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
}
if ($error)
{
$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.";
}
// Check parameters
if (!$error && ($id && $ref_ext))
{
$error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be all provided. You must choose one of them.";
}
if (!$error && ($id && $ref_ext))
{
$error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be all provided. You must choose one of them.";
}
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
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'url',
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'url',
);
/**
* @var Hook $hook {@type Hook}
*/
public $hook;
/**
* @var Hook $hook {@type Hook}
*/
public $hook;
/**
* Constructor
*
* @url GET /
*
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->hook = new Hook($this->db);
}
/**
* Constructor
*
* @url GET /
*
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->hook = new Hook($this->db);
}
/**
* Get properties of a hook object
*
* Return an array with hook informations
*
* @param int $id ID of hook
* @return array|mixed data without useless information
*
* @url GET /hooks/{id}
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401);
}
/**
* Get properties of a hook object
*
* Return an array with hook informations
*
* @param int $id ID of hook
* @return array|mixed data without useless information
*
* @url GET /hooks/{id}
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401);
}
$result = $this->hook->fetch($id);
if (!$result) {
throw new RestException(404, 'Hook not found');
}
$result = $this->hook->fetch($id);
if (!$result) {
throw new RestException(404, 'Hook not found');
}
if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
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
*
* Return an array with hook informations
* @param integer $id ID
*
* @return array|mixed data
*
* @url GET /getmoduleschoices/
* @throws RestException
*/
public function getModulesChoices($id)
{
if (!DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401);
}
$arraychoices = array(
'invoices' => 'Invoices',
'orders' => 'Orders',
'thirdparties' => 'Thirparties',
'contacts' => 'Contacts',
);
// $result = $this->hook->fetch($id);
// if (! $result ) {
// throw new RestException(404, 'Hook not found');
// }
/**
* Get list of possibles choices for module
*
* Return an array with hook informations
* @param integer $id ID
*
* @return array|mixed data
*
* @url GET /getmoduleschoices/
* @throws RestException
*/
public function getModulesChoices($id)
{
if (!DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401);
}
$arraychoices = array(
'invoices' => 'Invoices',
'orders' => 'Orders',
'thirdparties' => 'Thirparties',
'contacts' => 'Contacts',
);
// $result = $this->hook->fetch($id);
// if (! $result ) {
// throw new RestException(404, 'Hook not found');
// }
// if (! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
// throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
// }
// if (! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
// throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
// }
return $arraychoices;
}
return $arraychoices;
}
/**
* List hooks
*
* Get a list of hooks
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @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')"
* @return array Array of order objects
*
* @throws RestException
*
* @url GET /hooks/
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{
global $db, $conf;
/**
* List hooks
*
* Get a list of hooks
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @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')"
* @return array Array of order objects
*
* @throws RestException
*
* @url GET /hooks/
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{
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
$restrictonsocid = 0;
// Set to 1 if there is a field socid in table of object
$restrictonsocid = 0;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
$search_sale = DolibarrApiAccess::$user->id;
}
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
$search_sale = DolibarrApiAccess::$user->id;
}
$sql = "SELECT t.rowid";
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)
$sql .= ", sc.fk_soc, sc.fk_user";
}
$sql .= " FROM ".MAIN_DB_PREFIX."hook_mytable as t";
$sql = "SELECT t.rowid";
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)
$sql .= ", sc.fk_soc, sc.fk_user";
}
$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
$sql .= " WHERE 1 = 1";
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";
// Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
// Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
$tmpobject = new Hook($this->db);
if ($tmpobject->ismultientitymanaged) {
$sql .= ' AND t.entity IN ('.getEntity('hook').')';
}
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= " AND t.fk_soc = sc.fk_soc";
}
if ($restrictonsocid && $socid) {
$sql .= " AND t.fk_soc = ".$socid;
}
if ($restrictonsocid && $search_sale > 0) {
// Join for the needed table to filter by sale
$sql .= " AND t.rowid = sc.fk_soc";
}
// Insert sale filter
if ($restrictonsocid && $search_sale > 0) {
$sql .= " AND sc.fk_user = ".$search_sale;
}
if ($sqlfilters) {
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$tmpobject = new Hook($this->db);
if ($tmpobject->ismultientitymanaged) {
$sql .= ' AND t.entity IN ('.getEntity('hook').')';
}
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= " AND t.fk_soc = sc.fk_soc";
}
if ($restrictonsocid && $socid) {
$sql .= " AND t.fk_soc = ".$socid;
}
if ($restrictonsocid && $search_sale > 0) {
// Join for the needed table to filter by sale
$sql .= " AND t.rowid = sc.fk_soc";
}
// Insert sale filter
if ($restrictonsocid && $search_sale > 0) {
$sql .= " AND sc.fk_user = ".$search_sale;
}
if ($sqlfilters) {
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
$i = 0;
if ($result) {
$num = $this->db->num_rows($result);
while ($i < $num) {
$obj = $this->db->fetch_object($result);
$hook_static = new Hook($this->db);
if ($hook_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($hook_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve hook list');
}
if (!count($obj_ret)) {
throw new RestException(404, 'No hook found');
}
return $obj_ret;
}
$result = $this->db->query($sql);
$i = 0;
if ($result) {
$num = $this->db->num_rows($result);
while ($i < $num) {
$obj = $this->db->fetch_object($result);
$hook_static = new Hook($this->db);
if ($hook_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($hook_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve hook list');
}
if (!count($obj_ret)) {
throw new RestException(404, 'No hook found');
}
return $obj_ret;
}
/**
* Create hook object
*
* @param array $request_data Request datas
* @return int ID of hook
*
* @url POST /hook/
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401);
}
// Check mandatory fields
$fields = array(
'url',
);
$result = $this->validate($request_data, $fields);
/**
* Create hook object
*
* @param array $request_data Request datas
* @return int ID of hook
*
* @url POST /hook/
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401);
}
// Check mandatory fields
$fields = array(
'url',
);
$result = $this->validate($request_data, $fields);
foreach ($request_data as $field => $value) {
$this->hook->$field = $value;
}
$this->hook->fk_user = DolibarrApiAccess::$user->id;
// on crée le hook dans la base
if (!$this->hook->create(DolibarrApiAccess::$user)) {
throw new RestException(500, "Error creating Hook", array_merge(array($this->hook->error), $this->hook->errors));
}
return array(
'id' => $this->hook->id,
);
}
foreach ($request_data as $field => $value) {
$this->hook->$field = $value;
}
$this->hook->fk_user = DolibarrApiAccess::$user->id;
// on crée le hook dans la base
if (!$this->hook->create(DolibarrApiAccess::$user)) {
throw new RestException(500, "Error creating Hook", array_merge(array($this->hook->error), $this->hook->errors));
}
return array(
'id' => $this->hook->id,
);
}
// /**
// * Update hook
// *
// * @param int $id Id of hook to update
// * @param array $request_data Datas
// * @return int
// *
// * @url PUT /hooks/{id}
// */
/*public function put($id, $request_data = null)
// /**
// * Update hook
// *
// * @param int $id Id of hook to update
// * @param array $request_data Datas
// * @return int
// *
// * @url PUT /hooks/{id}
// */
/*public function put($id, $request_data = null)
{
if (! DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401);
@ -297,80 +297,80 @@ class ZapierApi extends DolibarrApi
}
}*/
/**
* Delete hook
*
* @param int $id Hook ID
* @return array
*
* @url DELETE /hook/{id}
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->zapier->delete) {
throw new RestException(401);
}
$result = $this->hook->fetch($id);
if (!$result) {
throw new RestException(404, 'Hook not found');
}
/**
* Delete hook
*
* @param int $id Hook ID
* @return array
*
* @url DELETE /hook/{id}
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->zapier->delete) {
throw new RestException(401);
}
$result = $this->hook->fetch($id);
if (!$result) {
throw new RestException(404, 'Hook not found');
}
if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!$this->hook->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when deleting Hook : '.$this->hook->error);
}
if (!$this->hook->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when deleting Hook : '.$this->hook->error);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Hook deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Hook deleted'
)
);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param object $object Object to clean
* @return array Array of cleaned object properties
*/
public function _cleanObjectDatas($object)
{
// phpcs:disable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param object $object Object to clean
* @return array Array of cleaned object properties
*/
public function _cleanObjectDatas($object)
{
// phpcs:disable
$object = parent::_cleanObjectDatas($object);
/*unset($object->note);
/*unset($object->note);
unset($object->address);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);*/
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array of data to validate
* @param array $fields Array of fields needed
* @return array
*
* @throws RestException
*/
private function validate($data, $fields)
{
$hook = array();
foreach ($fields as $field) {
if (!isset($data[$field])) {
throw new RestException(400, $field." field missing");
}
$hook[$field] = $data[$field];
}
return $hook;
}
/**
* Validate fields before create or update object
*
* @param array $data Array of data to validate
* @param array $fields Array of fields needed
* @return array
*
* @throws RestException
*/
private function validate($data, $fields)
{
$hook = array();
foreach ($fields as $field) {
if (!isset($data[$field])) {
throw new RestException(400, $field." field missing");
}
$hook[$field] = $data[$field];
}
return $hook;
}
}

View File

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