diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index 915a3e77176..ca88854d27e 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -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 '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - 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 = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'rowid', $linkback); + dol_banner_tab($object, 'rowid', $linkback); - print '
'; - print '
'; + print '
'; + print '
'; - print '
'; - print ''; + print '
'; + print '
'; // 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 ''; } - print '
'.$langs->trans("Password").''.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 '
'; + print ''; - print '
'; - print '
'; + print '
'; + print '
'; - print '
'; - print ''; + print '
'; + print '
'; // Birthday print ''; @@ -472,25 +472,25 @@ if ($rowid > 0) { print ''; } - // 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 ''; @@ -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 ' '; - } - print ''; - } - print ""; - $i++; - } + $accountstatic->ref = $objp->ref; + print $accountstatic->getNomUrl(1); + } else { + print ' '; + } + print ''; + } + print ""; + $i++; + } - if (empty($num)) { - $colspan = 6; - if (!empty($conf->banque->enabled)) $colspan++; - print ''; - } + if (empty($num)) { + $colspan = 6; + if (!empty($conf->banque->enabled)) $colspan++; + print ''; + } - print "
'.$langs->trans("Birthday").''.dol_print_date($object->birth, 'day').'
'.$langs->trans("SubscriptionEndDate").''; 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 '
'.$langs->trans("None").'
'.$langs->trans("None").'
"; - } else { - dol_print_error($db); - } - } + print ""; + } 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 '
'; + if ($useonlinepayment) { + print '
'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - print showOnlinePaymentUrl('membersubscription', $object->ref); - print '
'; - } - } + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + print showOnlinePaymentUrl('membersubscription', $object->ref); + print '
'; + } + } - /* + /* * Add new subscription form */ - if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->rights->adherent->cotisation->creer) { - print '
'; + if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->rights->adherent->cotisation->creer) { + print '
'; - 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\n"; + print "\n\n\n"; - if ($conf->use_javascript_ajax) { - //var_dump($bankdirect.'-'.$bankviainvoice.'-'.$invoiceonly.'-'.empty($conf->global->ADHERENT_BANK_USE)); - print "\n".''."\n"; - } + if (GETPOST('paymentsave')) print '$("#'.GETPOST('paymentsave').'").prop("checked",true);'; + print '});'; + print ''."\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 ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print dol_get_fiche_head(''); print "\n"; - print ''; + print ''; $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 ''; - // Date start subscription - print '"; + print ''; + // Date start subscription + print '"; - // 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 '"; + // 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 '"; - if ($adht->subscription) { - // Amount - print ''; + if ($adht->subscription) { + // Amount + print ''; - // Label - print ''; - print ''; + // Label + print ''; + print ''; - // 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 ''; + // Title payments + //print ''; - // No more action - print ''; - print ''; + print ''; + print ''; } } @@ -189,7 +189,7 @@ if ($result || empty($id)) { print ''."\n"; + $langs->load("members"); + $reg = array(); + if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."
\n"; + else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."
\n"; + $text = ''."\n"; } if (empty($text)) { - $text .= ''."\n"; - $text .= ''."\n"; + $text .= ''."\n"; + $text .= ''."\n"; } print $text; @@ -237,9 +237,9 @@ if ($source == 'proposal') // Creditor print ''."\n"; + print ''."\n"; // Debitor @@ -266,13 +266,13 @@ print '
'.$langs->trans("DateSubscription").''; - 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 "
'.$langs->trans("DateSubscription").''; + 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 "
'.$langs->trans("DateEndSubscription").''; - print $form->selectDate($dateto, 'end', '', '', '', "subscription", 1, 0); - print "
'.$langs->trans("DateEndSubscription").''; + print $form->selectDate($dateto, 'end', '', '', '', "subscription", 1, 0); + print "
'.$langs->trans("Amount").' '.$langs->trans("Currency".$conf->currency).'
'.$langs->trans("Amount").' '.$langs->trans("Currency".$conf->currency).'
'.$langs->trans("Label").'
'.$langs->trans("Label").'
'.$langs->trans("Payment").'
'.$langs->trans("Payment").'
'.$langs->trans('MoreActions'); - print ''; - print ' '.$langs->trans("None").'
'; - // Add entry into bank accoun - if (!empty($conf->banque->enabled)) { - print ' '.$langs->trans("MoreActionBankDirect").'
'; - } - // Add invoice with no payments - if (!empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { - print '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 ' - '; - print $langs->trans("CreateDolibarrThirdParty"); - print ')'; - } - if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0).''; + // No more action + print '
'.$langs->trans('MoreActions'); + print ''; + print ' '.$langs->trans("None").'
'; + // Add entry into bank accoun + if (!empty($conf->banque->enabled)) { + print ' '.$langs->trans("MoreActionBankDirect").'
'; + } + // Add invoice with no payments + if (!empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { + print '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 ' - '; + print $langs->trans("CreateDolibarrThirdParty"); + print ')'; + } + if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0).''; 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 '
'; - } - // Add invoice with payments - if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { - print '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 ' - '; - print $langs->trans("CreateDolibarrThirdParty"); - print ')'; - } - if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0).''; + print '
'; + } + // Add invoice with payments + if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { + print '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 ' - '; + print $langs->trans("CreateDolibarrThirdParty"); + print ')'; + } + if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0).''; 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); diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 2eb2c0edad1..2705ede5540 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -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" ? "".$langs->trans("Example").': '.$langs->transcountry("LocalTax2IsUsedExample", $mysoc->country_code)."\n" : ""); if (!isOnlyOneLocalTax(2)) { - print '
: '; - $formcompany->select_localtax(2, $conf->global->MAIN_INFO_VALUE_LOCALTAX2, "lt2"); + print '
: '; + $formcompany->select_localtax(2, $conf->global->MAIN_INFO_VALUE_LOCALTAX2, "lt2"); } print '
: '; print $form->selectarray("clt2", $opcions, $conf->global->MAIN_INFO_LOCALTAX_CALC2); diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index 987d7a256af..43ce69f6e02 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -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])."'"; diff --git a/htdocs/asset/class/asset.class.php b/htdocs/asset/class/asset.class.php index 036f31a99d7..05782b8ec67 100644 --- a/htdocs/asset/class/asset.class.php +++ b/htdocs/asset/class/asset.class.php @@ -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'); diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 8aeaa2a9fe8..5771ead70f1 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -97,7 +97,7 @@ class FactureRec extends CommonInvoice */ public $frequency; - /** + /** * @var string Unit frequency */ public $unit_frequency; @@ -317,46 +317,46 @@ class FactureRec extends CommonInvoice $tva_tx = $facsrc->lines[$i]->tva_tx; if (!empty($facsrc->lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')'; - $result_insert = $this->addline( - $facsrc->lines[$i]->desc, - $facsrc->lines[$i]->subprice, - $facsrc->lines[$i]->qty, + $result_insert = $this->addline( + $facsrc->lines[$i]->desc, + $facsrc->lines[$i]->subprice, + $facsrc->lines[$i]->qty, $tva_tx, - $facsrc->lines[$i]->localtax1_tx, - $facsrc->lines[$i]->localtax2_tx, - $facsrc->lines[$i]->fk_product, - $facsrc->lines[$i]->remise_percent, - 'HT', + $facsrc->lines[$i]->localtax1_tx, + $facsrc->lines[$i]->localtax2_tx, + $facsrc->lines[$i]->fk_product, + $facsrc->lines[$i]->remise_percent, + 'HT', $facsrc->lines[$i]->info_bits, - '', - 0, - $facsrc->lines[$i]->product_type, - $facsrc->lines[$i]->rang, - $facsrc->lines[$i]->special_code, - $facsrc->lines[$i]->label, + '', + 0, + $facsrc->lines[$i]->product_type, + $facsrc->lines[$i]->rang, + $facsrc->lines[$i]->special_code, + $facsrc->lines[$i]->label, $facsrc->lines[$i]->fk_unit, $facsrc->lines[$i]->multicurrency_subprice - ); + ); if ($result_insert < 0) { $error++; } else { - $objectline = new FactureLigneRec($this->db); - if ($objectline->fetch($result_insert)) - { - // Extrafields - if (method_exists($facsrc->lines[$i], 'fetch_optionals')) { - $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->rowid); - $objectline->array_options = $facsrc->lines[$i]->array_options; - } + $objectline = new FactureLigneRec($this->db); + if ($objectline->fetch($result_insert)) + { + // Extrafields + if (method_exists($facsrc->lines[$i], 'fetch_optionals')) { + $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->rowid); + $objectline->array_options = $facsrc->lines[$i]->array_options; + } - $result = $objectline->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + $result = $objectline->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } } } @@ -370,27 +370,27 @@ class FactureRec extends CommonInvoice { foreach ($this->linked_objects as $origin => $tmp_origin_id) { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - $this->error = $this->db->lasterror(); - $error++; - } - } - } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) - { - $origin_id = $tmp_origin_id; - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - $this->error = $this->db->lasterror(); - $error++; - } - } + if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + { + foreach ($tmp_origin_id as $origin_id) + { + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + $this->error = $this->db->lasterror(); + $error++; + } + } + } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + $this->error = $this->db->lasterror(); + $error++; + } + } } } @@ -422,7 +422,7 @@ class FactureRec extends CommonInvoice return $this->id; } } else { - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } @@ -442,46 +442,46 @@ class FactureRec extends CommonInvoice */ public function update(User $user, $notrigger = 0) { - global $conf; + global $conf; - $error = 0; + $error = 0; - $sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET"; - $sql .= " fk_soc = ".$this->fk_soc; - // TODO Add missing fields - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET"; + $sql .= " fk_soc = ".$this->fk_soc; + // TODO Add missing fields + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILLREC_UPDATE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -2; - } - // End call triggers - } - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -2; - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('BILLREC_UPDATE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -2; + } + // End call triggers + } + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -2; + } } /** @@ -498,13 +498,13 @@ class FactureRec extends CommonInvoice $sql .= ', f.remise_percent, f.remise_absolue, f.remise'; $sql .= ', f.date_lim_reglement as dlr'; $sql .= ', f.note_private, f.note_public, f.fk_user_author'; - $sql .= ', f.modelpdf'; + $sql .= ', f.modelpdf'; $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project'; $sql .= ', f.fk_account'; $sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.usenewprice, f.auto_validate'; - $sql .= ', f.generate_pdf'; - $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc"; - $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; + $sql .= ', f.generate_pdf'; + $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc"; + $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; //$sql.= ', el.fk_source'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f'; @@ -618,21 +618,21 @@ class FactureRec extends CommonInvoice */ public function getLinesArray() { - return $this->fetch_lines(); + return $this->fetch_lines(); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get lines of template invoices into this->lines * * @return int 1 if OK, < 0 if KO - */ + */ public function fetch_lines() { global $extrafields; - // phpcs:enable + // phpcs:enable $this->lines = array(); // Retrieve all extrafield for line @@ -710,7 +710,7 @@ class FactureRec extends CommonInvoice $line->rang = $objp->rang; $line->special_code = $objp->special_code; $line->fk_unit = $objp->fk_unit; - $line->fk_contract_line = $objp->fk_contract_line; + $line->fk_contract_line = $objp->fk_contract_line; // Ne plus utiliser $line->price = $objp->price; @@ -750,17 +750,17 @@ class FactureRec extends CommonInvoice */ public function delete(User $user, $notrigger = 0, $idwarehouse = -1) { - $rowid = $this->id; + $rowid = $this->id; - dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); + dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); - $error = 0; + $error = 0; $this->db->begin(); $main = MAIN_DB_PREFIX.'facturedet_rec'; - $ef = $main."_extrafields"; - $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)"; - dol_syslog($sqlef); + $ef = $main."_extrafields"; + $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)"; + dol_syslog($sqlef); $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".$rowid; dol_syslog($sql); if ($this->db->query($sqlef) && $this->db->query($sql)) @@ -773,8 +773,8 @@ class FactureRec extends CommonInvoice $res = $this->deleteObjectLinked(); if ($res < 0) $error = -3; // Delete extrafields - $res = $this->deleteExtraFields(); - if ($res < 0) $error = -4; + $res = $this->deleteExtraFields(); + if ($res < 0) $error = -4; } else { $this->error = $this->db->lasterror(); $error = -1; @@ -786,11 +786,11 @@ class FactureRec extends CommonInvoice if (!$error) { - $this->db->commit(); - return 1; + $this->db->commit(); + return 1; } else { - $this->db->rollback(); - return $error; + $this->db->rollback(); + return $error; } } @@ -798,33 +798,33 @@ class FactureRec extends CommonInvoice /** * Add a line to invoice * - * @param string $desc Description de la ligne - * @param double $pu_ht Prix unitaire HT (> 0 even for credit note) - * @param double $qty Quantite - * @param double $txtva Taux de tva force, sinon -1 + * @param string $desc Description de la ligne + * @param double $pu_ht Prix unitaire HT (> 0 even for credit note) + * @param double $qty Quantite + * @param double $txtva Taux de tva force, sinon -1 * @param double $txlocaltax1 Local tax 1 rate (deprecated) * @param double $txlocaltax2 Local tax 2 rate (deprecated) - * @param int $fk_product Product/Service ID predefined - * @param double $remise_percent Percentage discount of the line - * @param string $price_base_type HT or TTC - * @param int $info_bits VAT npr or not ? - * @param int $fk_remise_except Id remise - * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note) - * @param int $type Type of line (0=product, 1=service) - * @param int $rang Position of line - * @param int $special_code Special code - * @param string $label Label of the line - * @param string $fk_unit Unit + * @param int $fk_product Product/Service ID predefined + * @param double $remise_percent Percentage discount of the line + * @param string $price_base_type HT or TTC + * @param int $info_bits VAT npr or not ? + * @param int $fk_remise_except Id remise + * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note) + * @param int $type Type of line (0=product, 1=service) + * @param int $rang Position of line + * @param int $special_code Special code + * @param string $label Label of the line + * @param string $fk_unit Unit * @param double $pu_ht_devise Unit price in currency * @param int $date_start_fill 1=Flag to fill start date when generating invoice * @param int $date_end_fill 1=Flag to fill end date when generating invoice * @param int $fk_fournprice Supplier price id (to calculate margin) or '' * @param int $pa_ht Buying price of line (to calculate margin) or '' - * @return int <0 if KO, Id of line if OK + * @return int <0 if KO, Id of line if OK */ public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0) { - global $mysoc; + global $mysoc; $facid = $this->id; @@ -1008,131 +1008,131 @@ class FactureRec extends CommonInvoice */ public function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0) { - global $mysoc; + global $mysoc; - $facid = $this->id; + $facid = $this->id; - dol_syslog(get_class($this)."::updateline facid=".$facid." rowid=$rowid, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + dol_syslog(get_class($this)."::updateline facid=".$facid." rowid=$rowid, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; + // Clean parameters + if (empty($remise_percent)) $remise_percent = 0; - // Check parameters - if ($type < 0) return -1; + // Check parameters + if ($type < 0) return -1; - if ($this->brouillon) - { - // Clean parameters - $remise_percent = price2num($remise_percent); - $qty = price2num($qty); - if (empty($info_bits)) $info_bits = 0; - $pu_ht = price2num($pu_ht); - $pu_ttc = price2num($pu_ttc); - $pu_ht_devise = price2num($pu_ht_devise); - $txtva = price2num($txtva); - $txlocaltax1 = price2num($txlocaltax1); - $txlocaltax2 = price2num($txlocaltax2); - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; + if ($this->brouillon) + { + // Clean parameters + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + if (empty($info_bits)) $info_bits = 0; + $pu_ht = price2num($pu_ht); + $pu_ttc = price2num($pu_ttc); + $pu_ht_devise = price2num($pu_ht_devise); + $txtva = price2num($txtva); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); + if (empty($txlocaltax1)) $txlocaltax1 = 0; + if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; + if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; + if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; + if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; - if ($price_base_type == 'HT') - { - $pu = $pu_ht; - } else { - $pu = $pu_ttc; - } + if ($price_base_type == 'HT') + { + $pu = $pu_ht; + } else { + $pu = $pu_ttc; + } - // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); - // Clean vat code - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; - $pu_ht = $tabprice[3]; - $pu_tva = $tabprice[4]; - $pu_ttc = $tabprice[5]; + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; + $pu_ht = $tabprice[3]; + $pu_tva = $tabprice[4]; + $pu_ttc = $tabprice[5]; - // MultiCurrency - $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; - $pu_ht_devise = $tabprice[19]; + // MultiCurrency + $multicurrency_total_ht = $tabprice[16]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; + $pu_ht_devise = $tabprice[19]; - $product_type = $type; - if ($fk_product) - { - $product = new Product($this->db); - $result = $product->fetch($fk_product); - $product_type = $product->type; - } + $product_type = $type; + if ($fk_product) + { + $product = new Product($this->db); + $result = $product->fetch($fk_product); + $product_type = $product->type; + } - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET "; - $sql .= "fk_facture = ".((int) $facid); - $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); - $sql .= ", description='".$this->db->escape($desc)."'"; - $sql .= ", price=".price2num($pu_ht); - $sql .= ", qty=".price2num($qty); - $sql .= ", tva_tx=".price2num($txtva); - $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'"; - $sql .= ", localtax1_tx=".$txlocaltax1; - $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'"; - $sql .= ", localtax2_tx=".$txlocaltax2; - $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'"; - $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null"); - $sql .= ", product_type=".$product_type; - $sql .= ", remise_percent='".price2num($remise_percent)."'"; - $sql .= ", subprice='".price2num($pu_ht)."'"; - $sql .= ", total_ht='".price2num($total_ht)."'"; - $sql .= ", total_tva='".price2num($total_tva)."'"; - $sql .= ", total_localtax1='".price2num($total_localtax1)."'"; - $sql .= ", total_localtax2='".price2num($total_localtax2)."'"; - $sql .= ", total_ttc='".price2num($total_ttc)."'"; - $sql .= ", date_start_fill=".((int) $date_start_fill); - $sql .= ", date_end_fill=".((int) $date_end_fill); - $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : 'null'); - $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0); - $sql .= ", info_bits=".$info_bits; - $sql .= ", rang=".$rang; - $sql .= ", special_code=".$special_code; - $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); - $sql .= ', multicurrency_subprice = '.$pu_ht_devise; - $sql .= ', multicurrency_total_ht = '.$multicurrency_total_ht; - $sql .= ', multicurrency_total_tva = '.$multicurrency_total_tva; - $sql .= ', multicurrency_total_ttc = '.$multicurrency_total_ttc; - $sql .= " WHERE rowid = ".$rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET "; + $sql .= "fk_facture = ".((int) $facid); + $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); + $sql .= ", description='".$this->db->escape($desc)."'"; + $sql .= ", price=".price2num($pu_ht); + $sql .= ", qty=".price2num($qty); + $sql .= ", tva_tx=".price2num($txtva); + $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'"; + $sql .= ", localtax1_tx=".$txlocaltax1; + $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'"; + $sql .= ", localtax2_tx=".$txlocaltax2; + $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'"; + $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null"); + $sql .= ", product_type=".$product_type; + $sql .= ", remise_percent='".price2num($remise_percent)."'"; + $sql .= ", subprice='".price2num($pu_ht)."'"; + $sql .= ", total_ht='".price2num($total_ht)."'"; + $sql .= ", total_tva='".price2num($total_tva)."'"; + $sql .= ", total_localtax1='".price2num($total_localtax1)."'"; + $sql .= ", total_localtax2='".price2num($total_localtax2)."'"; + $sql .= ", total_ttc='".price2num($total_ttc)."'"; + $sql .= ", date_start_fill=".((int) $date_start_fill); + $sql .= ", date_end_fill=".((int) $date_end_fill); + $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : 'null'); + $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0); + $sql .= ", info_bits=".$info_bits; + $sql .= ", rang=".$rang; + $sql .= ", special_code=".$special_code; + $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); + $sql .= ', multicurrency_subprice = '.$pu_ht_devise; + $sql .= ', multicurrency_total_ht = '.$multicurrency_total_ht; + $sql .= ', multicurrency_total_tva = '.$multicurrency_total_tva; + $sql .= ', multicurrency_total_ttc = '.$multicurrency_total_ttc; + $sql .= " WHERE rowid = ".$rowid; - dol_syslog(get_class($this)."::updateline", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->id = $facid; - $this->update_price(); - return 1; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->id = $facid; + $this->update_price(); + return 1; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } } @@ -1328,8 +1328,8 @@ class FactureRec extends CommonInvoice * @param int $max Maxlength of ref * @param int $short 1=Return just URL * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @return string String with URL */ public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = '', $save_lastsearch_value = -1) @@ -1356,17 +1356,17 @@ class FactureRec extends CommonInvoice } } - $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$this->id; + $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$this->id; - if ($short) return $url; + if ($short) return $url; - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; - } + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; + if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + } $linkstart = ''; $linkend = ''; @@ -1391,7 +1391,7 @@ class FactureRec extends CommonInvoice return $this->LibStatut($this->frequency ? 1 : 0, $this->suspended, $mode, $alreadypaid, empty($this->type) ? 0 : $this->type); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return label of a status * @@ -1404,7 +1404,7 @@ class FactureRec extends CommonInvoice */ public function LibStatut($recur, $status, $mode = 0, $alreadypaid = -1, $type = 0) { - // phpcs:enable + // phpcs:enable global $langs; $langs->load('bills'); @@ -1553,7 +1553,7 @@ class FactureRec extends CommonInvoice $arraynow = dol_getdate($now); $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); - // Load array of products prodids + // Load array of products prodids $num_prods = 0; $prodids = array(); @@ -1690,190 +1690,190 @@ class FactureRec extends CommonInvoice } /** - * Update frequency and unit - * - * @param int $frequency value of frequency - * @param string $unit unit of frequency (d, m, y) - * @return int <0 if KO, >0 if OK - */ - public function setFrequencyAndUnit($frequency, $unit) - { - if (!$this->table_element) { - dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - if (!empty($frequency) && empty($unit)) { - dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with params frequency defined but unit not defined", LOG_ERR); - return -2; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null'); - if (!empty($unit)) { - $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\''; + * Update frequency and unit + * + * @param int $frequency value of frequency + * @param string $unit unit of frequency (d, m, y) + * @return int <0 if KO, >0 if OK + */ + public function setFrequencyAndUnit($frequency, $unit) + { + if (!$this->table_element) { + dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with property table_element not defined", LOG_ERR); + return -1; } - $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); - if ($this->db->query($sql)) { - $this->frequency = $frequency; - if (!empty($unit)) $this->unit_frequency = $unit; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + if (!empty($frequency) && empty($unit)) { + dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with params frequency defined but unit not defined", LOG_ERR); + return -2; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null'); + if (!empty($unit)) { + $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\''; + } + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); + if ($this->db->query($sql)) { + $this->frequency = $frequency; + if (!empty($unit)) $this->unit_frequency = $unit; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } /** - * Update the next date of execution - * - * @param datetime $date date of execution - * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done - * @return int <0 if KO, >0 if OK - */ - public function setNextDate($date, $increment_nb_gen_done = 0) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); - if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1'; - $sql .= ' WHERE rowid = '.$this->id; + * Update the next date of execution + * + * @param datetime $date date of execution + * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done + * @return int <0 if KO, >0 if OK + */ + public function setNextDate($date, $increment_nb_gen_done = 0) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); + if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1'; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->date_when = $date; - if ($increment_nb_gen_done > 0) $this->nb_gen_done++; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->date_when = $date; + if ($increment_nb_gen_done > 0) $this->nb_gen_done++; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } /** - * Update the maximum period - * - * @param int $nb number of maximum period - * @return int <0 if KO, >0 if OK - */ - public function setMaxPeriod($nb) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + * Update the maximum period + * + * @param int $nb number of maximum period + * @return int <0 if KO, >0 if OK + */ + public function setMaxPeriod($nb) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR); + return -1; + } - if (empty($nb)) $nb = 0; + if (empty($nb)) $nb = 0; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET nb_gen_max = '.$nb; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET nb_gen_max = '.$nb; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->nb_gen_max = $nb; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->nb_gen_max = $nb; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } /** - * Update the auto validate flag of invoice - * - * @param int $validate 0 to create in draft, 1 to create and validate invoice - * @return int <0 if KO, >0 if OK - */ - public function setAutoValidate($validate) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + * Update the auto validate flag of invoice + * + * @param int $validate 0 to create in draft, 1 to create and validate invoice + * @return int <0 if KO, >0 if OK + */ + public function setAutoValidate($validate) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined", LOG_ERR); + return -1; + } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET auto_validate = '.$validate; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET auto_validate = '.$validate; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->auto_validate = $validate; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->auto_validate = $validate; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } - /** - * Update the auto generate documents - * - * @param int $validate 0 no document, 1 to generate document - * @return int <0 if KO, >0 if OK - */ - public function setGeneratePdf($validate) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + /** + * Update the auto generate documents + * + * @param int $validate 0 no document, 1 to generate document + * @return int <0 if KO, >0 if OK + */ + public function setGeneratePdf($validate) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined", LOG_ERR); + return -1; + } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET generate_pdf = '.$validate; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET generate_pdf = '.$validate; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->generate_pdf = $validate; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->generate_pdf = $validate; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } - /** - * Update the model for documents - * - * @param string $model model of document generator - * @return int <0 if KO, >0 if OK - */ - public function setModelPdf($model) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + /** + * Update the model for documents + * + * @param string $model model of document generator + * @return int <0 if KO, >0 if OK + */ + public function setModelPdf($model) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined", LOG_ERR); + return -1; + } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET modelpdf = "'.$model.'"'; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET modelpdf = "'.$model.'"'; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->modelpdf = $model; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->modelpdf = $model; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } } @@ -1898,206 +1898,206 @@ class FactureLigneRec extends CommonInvoiceLine public $date_end_fill; - /** - * Delete line in database - * - * @param User $user Object user - * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function delete(User $user, $notrigger = false) - { - $error = 0; + /** + * Delete line in database + * + * @param User $user Object user + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + $error = 0; - $this->db->begin(); + $this->db->begin(); - if (!$error) { - if (!$notrigger) { - // Call triggers - $result = $this->call_trigger('LINEBILLREC_DELETE', $user); - if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail - // End call triggers - } - } + if (!$error) { + if (!$notrigger) { + // Call triggers + $result = $this->call_trigger('LINEBILLREC_DELETE', $user); + if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail + // End call triggers + } + } if (!$error) - { - $result = $this->deleteExtraFields(); - if ($result < 0) { - $error++; - } - } - - if (!$error) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; - - $res = $this->db->query($sql); - if ($res === false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - - // Commit or rollback - if ($error) { - $this->db->rollback(); - return -1; - } else { - $this->db->commit(); - return 1; + { + $result = $this->deleteExtraFields(); + if ($result < 0) { + $error++; + } } - } + + if (!$error) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; + + $res = $this->db->query($sql); + if ($res === false) { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } + + // Commit or rollback + if ($error) { + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return 1; + } + } - /** - * Get line of template invoice - * - * @param int $rowid Id of invoice - * @return int 1 if OK, < 0 if KO - */ - public function fetch($rowid) - { - $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; - $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; - $sql .= ' l.rang, l.special_code,'; - $sql .= ' l.fk_unit, l.fk_contract_line,'; - $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; - $sql .= ' WHERE l.rowid = '.$rowid; - $sql .= ' ORDER BY l.rang'; + /** + * Get line of template invoice + * + * @param int $rowid Id of invoice + * @return int 1 if OK, < 0 if KO + */ + public function fetch($rowid) + { + $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; + $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; + $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; + $sql .= ' l.rang, l.special_code,'; + $sql .= ' l.fk_unit, l.fk_contract_line,'; + $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; + $sql .= ' WHERE l.rowid = '.$rowid; + $sql .= ' ORDER BY l.rang'; - dol_syslog('FactureRec::fetch', LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $objp = $this->db->fetch_object($result); + dol_syslog('FactureRec::fetch', LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $objp = $this->db->fetch_object($result); - $this->id = $objp->rowid; - $this->label = $objp->custom_label; // Label line - $this->desc = $objp->description; // Description line - $this->description = $objp->description; // Description line - $this->product_type = $objp->product_type; // Type of line - $this->ref = $objp->product_ref; // Ref product - $this->product_ref = $objp->product_ref; // Ref product - $this->libelle = $objp->product_label; // deprecated - $this->product_label = $objp->product_label; // Label product - $this->product_desc = $objp->product_desc; // Description product - $this->fk_product_type = $objp->fk_product_type; // Type of product - $this->qty = $objp->qty; - $this->price = $objp->price; - $this->subprice = $objp->subprice; - $this->fk_facture = $objp->fk_facture; - $this->vat_src_code = $objp->vat_src_code; - $this->tva_tx = $objp->tva_tx; - $this->localtax1_tx = $objp->localtax1_tx; - $this->localtax2_tx = $objp->localtax2_tx; - $this->localtax1_type = $objp->localtax1_type; - $this->localtax2_type = $objp->localtax2_type; - $this->remise_percent = $objp->remise_percent; - $this->fk_remise_except = $objp->fk_remise_except; - $this->fk_product = $objp->fk_product; - $this->date_start_fill = $objp->date_start_fill; - $this->date_end_fill = $objp->date_end_fill; - $this->info_bits = $objp->info_bits; - $this->total_ht = $objp->total_ht; - $this->total_tva = $objp->total_tva; - $this->total_ttc = $objp->total_ttc; - $this->code_ventilation = $objp->fk_code_ventilation; - $this->rang = $objp->rang; - $this->special_code = $objp->special_code; - $this->fk_unit = $objp->fk_unit; - $this->fk_contract_line = $objp->fk_contract_line; + $this->id = $objp->rowid; + $this->label = $objp->custom_label; // Label line + $this->desc = $objp->description; // Description line + $this->description = $objp->description; // Description line + $this->product_type = $objp->product_type; // Type of line + $this->ref = $objp->product_ref; // Ref product + $this->product_ref = $objp->product_ref; // Ref product + $this->libelle = $objp->product_label; // deprecated + $this->product_label = $objp->product_label; // Label product + $this->product_desc = $objp->product_desc; // Description product + $this->fk_product_type = $objp->fk_product_type; // Type of product + $this->qty = $objp->qty; + $this->price = $objp->price; + $this->subprice = $objp->subprice; + $this->fk_facture = $objp->fk_facture; + $this->vat_src_code = $objp->vat_src_code; + $this->tva_tx = $objp->tva_tx; + $this->localtax1_tx = $objp->localtax1_tx; + $this->localtax2_tx = $objp->localtax2_tx; + $this->localtax1_type = $objp->localtax1_type; + $this->localtax2_type = $objp->localtax2_type; + $this->remise_percent = $objp->remise_percent; + $this->fk_remise_except = $objp->fk_remise_except; + $this->fk_product = $objp->fk_product; + $this->date_start_fill = $objp->date_start_fill; + $this->date_end_fill = $objp->date_end_fill; + $this->info_bits = $objp->info_bits; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_ttc = $objp->total_ttc; + $this->code_ventilation = $objp->fk_code_ventilation; + $this->rang = $objp->rang; + $this->special_code = $objp->special_code; + $this->fk_unit = $objp->fk_unit; + $this->fk_contract_line = $objp->fk_contract_line; - $this->db->free($result); - return 1; - } else { - $this->error = $this->db->lasterror(); - return -3; - } - } + $this->db->free($result); + return 1; + } else { + $this->error = $this->db->lasterror(); + return -3; + } + } - /** - * Update a line to invoice_rec. - * - * @param User $user User - * @param int $notrigger No trigger - * @return int <0 if KO, Id of line if OK - */ - public function update(User $user, $notrigger = 0) - { - global $conf; + /** + * Update a line to invoice_rec. + * + * @param User $user User + * @param int $notrigger No trigger + * @return int <0 if KO, Id of line if OK + */ + public function update(User $user, $notrigger = 0) + { + global $conf; - $error = 0; + $error = 0; - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET"; - $sql .= " fk_facture = ".$this->fk_facture; - $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); - $sql .= ", description='".$this->db->escape($this->desc)."'"; - $sql .= ", price=".price2num($this->price); - $sql .= ", qty=".price2num($this->qty); - $sql .= ", tva_tx=".price2num($this->tva_tx); - $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'"; - $sql .= ", localtax1_tx=".price2num($this->localtax1_tx); - $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; - $sql .= ", localtax2_tx=".price2num($this->localtax2_tx); - $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql .= ", fk_product=".($this->fk_product > 0 ? $this->fk_product : "null"); - $sql .= ", product_type=".$this->product_type; - $sql .= ", remise_percent='".price2num($this->remise_percent)."'"; - $sql .= ", subprice='".price2num($this->subprice)."'"; - $sql .= ", info_bits='".price2num($this->info_bits)."'"; - $sql .= ", date_start_fill=".(int) $this->date_start_fill; - $sql .= ", date_end_fill=".(int) $this->date_end_fill; - if (empty($this->skip_update_total)) { - $sql .= ", total_ht=".price2num($this->total_ht); - $sql .= ", total_tva=".price2num($this->total_tva); - $sql .= ", total_localtax1=".price2num($this->total_localtax1); - $sql .= ", total_localtax2=".price2num($this->total_localtax2); - $sql .= ", total_ttc=".price2num($this->total_ttc); - } - $sql .= ", rang=".$this->rang; - $sql .= ", special_code=".$this->special_code; - $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null"); - $sql .= ", fk_contract_line=".($this->fk_contract_line ? $this->fk_contract_line : "null"); - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET"; + $sql .= " fk_facture = ".$this->fk_facture; + $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", description='".$this->db->escape($this->desc)."'"; + $sql .= ", price=".price2num($this->price); + $sql .= ", qty=".price2num($this->qty); + $sql .= ", tva_tx=".price2num($this->tva_tx); + $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'"; + $sql .= ", localtax1_tx=".price2num($this->localtax1_tx); + $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; + $sql .= ", localtax2_tx=".price2num($this->localtax2_tx); + $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; + $sql .= ", fk_product=".($this->fk_product > 0 ? $this->fk_product : "null"); + $sql .= ", product_type=".$this->product_type; + $sql .= ", remise_percent='".price2num($this->remise_percent)."'"; + $sql .= ", subprice='".price2num($this->subprice)."'"; + $sql .= ", info_bits='".price2num($this->info_bits)."'"; + $sql .= ", date_start_fill=".(int) $this->date_start_fill; + $sql .= ", date_end_fill=".(int) $this->date_end_fill; + if (empty($this->skip_update_total)) { + $sql .= ", total_ht=".price2num($this->total_ht); + $sql .= ", total_tva=".price2num($this->total_tva); + $sql .= ", total_localtax1=".price2num($this->total_localtax1); + $sql .= ", total_localtax2=".price2num($this->total_localtax2); + $sql .= ", total_ttc=".price2num($this->total_ttc); + } + $sql .= ", rang=".$this->rang; + $sql .= ", special_code=".$this->special_code; + $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null"); + $sql .= ", fk_contract_line=".($this->fk_contract_line ? $this->fk_contract_line : "null"); + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::updateline", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('LINEBILLREC_UPDATE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -2; - } - // End call triggers - } - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('LINEBILLREC_UPDATE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -2; + } + // End call triggers + } + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } } diff --git a/htdocs/compta/localtax/card.php b/htdocs/compta/localtax/card.php index b99e4c35d1c..c3700d9e994 100644 --- a/htdocs/compta/localtax/card.php +++ b/htdocs/compta/localtax/card.php @@ -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 ''."\n"; - print ''; - print ''; - print ''; + print ''."\n"; + print ''; + print ''; + print ''; - print dol_get_fiche_head(); + print dol_get_fiche_head(); - print ''; + print '
'; - print ""; - print ''; + print ""; + print ''; - print ''; + print ''; // Label print ''; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index 11b225d0896..6e018e0bb84 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -32,79 +32,79 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; */ class ChargeSociales extends CommonObject { - /** + /** * @var string ID to identify managed object */ public $element = 'chargesociales'; - public $table = 'chargesociales'; + public $table = 'chargesociales'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'chargesociales'; - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'bill'; - - /** - * {@inheritdoc} - */ - protected $table_ref_field = 'ref'; - - /** - * @var integer|string $date_ech - */ - public $date_ech; - - - public $label; - public $type; - public $type_label; - public $amount; - public $paye; - public $periode; - - /** - * @var integer|string date_creation - */ - public $date_creation; - - /** - * @var integer|string $date_modification - */ - public $date_modification; - - /** - * @var integer|string $date_validation - */ - public $date_validation; - - /** - * @deprecated Use label instead - */ - public $lib; - - /** - * @var int account ID - */ - public $fk_account; + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'bill'; /** - * @var int account ID (identical to fk_account) - */ - public $accountid; + * {@inheritdoc} + */ + protected $table_ref_field = 'ref'; - /** - * @var int payment type (identical to mode_reglement_id in commonobject class) - */ - public $paiementtype; + /** + * @var integer|string $date_ech + */ + public $date_ech; - /** - * @var int ID - */ + + public $label; + public $type; + public $type_label; + public $amount; + public $paye; + public $periode; + + /** + * @var integer|string date_creation + */ + public $date_creation; + + /** + * @var integer|string $date_modification + */ + public $date_modification; + + /** + * @var integer|string $date_validation + */ + public $date_validation; + + /** + * @deprecated Use label instead + */ + public $lib; + + /** + * @var int account ID + */ + public $fk_account; + + /** + * @var int account ID (identical to fk_account) + */ + public $accountid; + + /** + * @var int payment type (identical to mode_reglement_id in commonobject class) + */ + public $paiementtype; + + /** + * @var int ID + */ public $fk_project; @@ -112,73 +112,73 @@ class ChargeSociales extends CommonObject const STATUS_PAID = 1; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Retrouve et charge une charge sociale - * - * @param int $id Id - * @param string $ref Ref - * @return int <0 KO >0 OK - */ - public function fetch($id, $ref = '') - { - $sql = "SELECT cs.rowid, cs.date_ech"; - $sql .= ", cs.libelle as label, cs.fk_type, cs.amount, cs.fk_projet as fk_project, cs.paye, cs.periode, cs.import_key"; - $sql .= ", cs.fk_account, cs.fk_mode_reglement"; - $sql .= ", c.libelle"; - $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; - $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id"; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id'; - $sql .= ' WHERE cs.entity IN ('.getEntity('tax').')'; - if ($ref) $sql .= " AND cs.rowid = ".$ref; - else $sql .= " AND cs.rowid = ".$id; + /** + * Retrouve et charge une charge sociale + * + * @param int $id Id + * @param string $ref Ref + * @return int <0 KO >0 OK + */ + public function fetch($id, $ref = '') + { + $sql = "SELECT cs.rowid, cs.date_ech"; + $sql .= ", cs.libelle as label, cs.fk_type, cs.amount, cs.fk_projet as fk_project, cs.paye, cs.periode, cs.import_key"; + $sql .= ", cs.fk_account, cs.fk_mode_reglement"; + $sql .= ", c.libelle"; + $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; + $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id'; + $sql .= ' WHERE cs.entity IN ('.getEntity('tax').')'; + if ($ref) $sql .= " AND cs.rowid = ".$ref; + else $sql .= " AND cs.rowid = ".$id; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->ref = $obj->rowid; - $this->date_ech = $this->db->jdate($obj->date_ech); - $this->lib = $obj->label; - $this->label = $obj->label; - $this->type = $obj->fk_type; - $this->type_label = $obj->libelle; - $this->fk_account = $obj->fk_account; - $this->mode_reglement_id = $obj->fk_mode_reglement; - $this->mode_reglement_code = $obj->mode_reglement_code; - $this->mode_reglement = $obj->mode_reglement_libelle; - $this->amount = $obj->amount; + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + $this->date_ech = $this->db->jdate($obj->date_ech); + $this->lib = $obj->label; + $this->label = $obj->label; + $this->type = $obj->fk_type; + $this->type_label = $obj->libelle; + $this->fk_account = $obj->fk_account; + $this->mode_reglement_id = $obj->fk_mode_reglement; + $this->mode_reglement_code = $obj->mode_reglement_code; + $this->mode_reglement = $obj->mode_reglement_libelle; + $this->amount = $obj->amount; $this->fk_project = $obj->fk_project; - $this->paye = $obj->paye; - $this->periode = $this->db->jdate($obj->periode); - $this->import_key = $this->import_key; + $this->paye = $obj->paye; + $this->periode = $this->db->jdate($obj->periode); + $this->import_key = $this->import_key; - $this->db->free($resql); + $this->db->free($resql); - return 1; - } else { - return 0; - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + return 1; + } else { + return 0; + } + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } /** * Check if a social contribution can be created into database @@ -189,59 +189,59 @@ class ChargeSociales extends CommonObject { $newamount = price2num($this->amount, 'MT'); - // Validation parametres - if (!$newamount > 0 || empty($this->date_ech) || empty($this->periode)) - { - return false; - } + // Validation parametres + if (!$newamount > 0 || empty($this->date_ech) || empty($this->periode)) + { + return false; + } return true; } - /** - * Create a social contribution into database - * - * @param User $user User making creation - * @return int <0 if KO, id if OK - */ - public function create($user) - { - global $conf; + /** + * Create a social contribution into database + * + * @param User $user User making creation + * @return int <0 if KO, id if OK + */ + public function create($user) + { + global $conf; $error = 0; - $now = dol_now(); + $now = dol_now(); - // Nettoyage parametres - $newamount = price2num($this->amount, 'MT'); + // Nettoyage parametres + $newamount = price2num($this->amount, 'MT'); if (!$this->check()) { $this->error = "ErrorBadParameter"; return -2; } - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."chargesociales (fk_type, fk_account, fk_mode_reglement, libelle, date_ech, periode, amount, fk_projet, entity, fk_user_author, date_creation)"; - $sql .= " VALUES (".$this->type; - $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); - $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : "NULL"); - $sql .= ", '".$this->db->escape($this->label ? $this->label : $this->lib)."'"; - $sql .= ", '".$this->db->idate($this->date_ech)."'"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."chargesociales (fk_type, fk_account, fk_mode_reglement, libelle, date_ech, periode, amount, fk_projet, entity, fk_user_author, date_creation)"; + $sql .= " VALUES (".$this->type; + $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); + $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : "NULL"); + $sql .= ", '".$this->db->escape($this->label ? $this->label : $this->lib)."'"; + $sql .= ", '".$this->db->idate($this->date_ech)."'"; $sql .= ", '".$this->db->idate($this->periode)."'"; - $sql .= ", '".price2num($newamount)."'"; + $sql .= ", '".price2num($newamount)."'"; $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : 'NULL'); - $sql .= ", ".$conf->entity; - $sql .= ", ".$user->id; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ")"; + $sql .= ", ".$conf->entity; + $sql .= ", ".$user->id; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."chargesociales"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."chargesociales"); - //dol_syslog("ChargesSociales::create this->id=".$this->id); + //dol_syslog("ChargesSociales::create this->id=".$this->id); $result = $this->call_trigger('SOCIALCONTRIBUTION_CREATE', $user); if ($result < 0) $error++; @@ -252,429 +252,429 @@ class ChargeSociales extends CommonObject $this->db->rollback(); return -1 * $error; } - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } - /** - * Delete a social contribution - * - * @param User $user Object user making delete - * @return int <0 if KO, >0 if OK - */ - public function delete($user) - { - $error = 0; + /** + * Delete a social contribution + * + * @param User $user Object user making delete + * @return int <0 if KO, >0 if OK + */ + public function delete($user) + { + $error = 0; - $this->db->begin(); + $this->db->begin(); - // Get bank transaction lines for this social contributions - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $account = new Account($this->db); - $lines_url = $account->get_url('', $this->id, 'sc'); + // Get bank transaction lines for this social contributions + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $account = new Account($this->db); + $lines_url = $account->get_url('', $this->id, 'sc'); - // Delete bank urls - foreach ($lines_url as $line_url) - { - if (!$error) - { - $accountline = new AccountLine($this->db); - $accountline->fetch($line_url['fk_bank']); - $result = $accountline->delete_urls($user); - if ($result < 0) - { - $error++; - } - } - } + // Delete bank urls + foreach ($lines_url as $line_url) + { + if (!$error) + { + $accountline = new AccountLine($this->db); + $accountline->fetch($line_url['fk_bank']); + $result = $accountline->delete_urls($user); + if ($result < 0) + { + $error++; + } + } + } - // Delete payments - if (!$error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."paiementcharge WHERE fk_charge=".$this->id; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->error = $this->db->lasterror(); - } - } + // Delete payments + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."paiementcharge WHERE fk_charge=".$this->id; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = $this->db->lasterror(); + } + } - if (!$error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."chargesociales WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->error = $this->db->lasterror(); - } - } + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."chargesociales WHERE rowid=".$this->id; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = $this->db->lasterror(); + } + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Update social or fiscal contribution - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0) - { - $error = 0; - $this->db->begin(); + /** + * Update social or fiscal contribution + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0) + { + $error = 0; + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales"; - $sql .= " SET libelle='".$this->db->escape($this->label ? $this->label : $this->lib)."'"; - $sql .= ", date_ech='".$this->db->idate($this->date_ech)."'"; - $sql .= ", periode='".$this->db->idate($this->periode)."'"; - $sql .= ", amount='".price2num($this->amount, 'MT')."'"; - $sql .= ", fk_projet=".($this->fk_project > 0 ? $this->db->escape($this->fk_project) : "NULL"); - $sql .= ", fk_user_modif=".$user->id; - $sql .= " WHERE rowid=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales"; + $sql .= " SET libelle='".$this->db->escape($this->label ? $this->label : $this->lib)."'"; + $sql .= ", date_ech='".$this->db->idate($this->date_ech)."'"; + $sql .= ", periode='".$this->db->idate($this->periode)."'"; + $sql .= ", amount='".price2num($this->amount, 'MT')."'"; + $sql .= ", fk_projet=".($this->fk_project > 0 ? $this->db->escape($this->fk_project) : "NULL"); + $sql .= ", fk_user_modif=".$user->id; + $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); - if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); - } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('SOCIALCHARGES_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } - } + if (!$error) + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('SOCIALCHARGES_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } + } - // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else { - $this->db->commit(); - return 1; - } - } + // Commit or rollback + if ($error) + { + foreach ($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } - /** - * Calculate amount remaining to pay by year - * - * @param int $year Year - * @return number - */ - public function solde($year = 0) - { - global $conf; + /** + * Calculate amount remaining to pay by year + * + * @param int $year Year + * @return number + */ + public function solde($year = 0) + { + global $conf; - $sql = "SELECT SUM(f.amount) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as f"; - $sql .= " WHERE f.entity = ".$conf->entity; - $sql .= " AND paye = 0"; + $sql = "SELECT SUM(f.amount) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as f"; + $sql .= " WHERE f.entity = ".$conf->entity; + $sql .= " AND paye = 0"; - if ($year) { - $sql .= " AND f.datev >= '".((int) $year)."-01-01' AND f.datev <= '".((int) $year)."-12-31' "; - } + if ($year) { + $sql .= " AND f.datev >= '".((int) $year)."-01-01' AND f.datev <= '".((int) $year)."-12-31' "; + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $this->db->free($result); - return $obj->amount; - } else { - return 0; - } - } else { - print $this->db->error(); - return -1; - } - } + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->db->free($result); + return $obj->amount; + } else { + return 0; + } + } else { + print $this->db->error(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Tag social contribution as payed completely - * - * @param User $user Object user making change - * @return int <0 if KO, >0 if OK - */ - public function set_paid($user) - { - // phpcs:enable - $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales SET"; - $sql .= " paye = 1"; - $sql .= " WHERE rowid = ".$this->id; - $return = $this->db->query($sql); - if ($return) return 1; - else return -1; - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Tag social contribution as payed completely + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function set_paid($user) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales SET"; + $sql .= " paye = 1"; + $sql .= " WHERE rowid = ".$this->id; + $return = $this->db->query($sql); + if ($return) return 1; + else return -1; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Remove tag payed on social contribution - * - * @param User $user Object user making change - * @return int <0 if KO, >0 if OK - */ - public function set_unpaid($user) - { - // phpcs:enable - $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales SET"; - $sql .= " paye = 0"; - $sql .= " WHERE rowid = ".$this->id; - $return = $this->db->query($sql); - if ($return) return 1; - else return -1; - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Remove tag payed on social contribution + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function set_unpaid($user) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales SET"; + $sql .= " paye = 0"; + $sql .= " WHERE rowid = ".$this->id; + $return = $this->db->query($sql); + if ($return) return 1; + else return -1; + } - /** - * Retourne le libelle du statut d'une charge (impaye, payee) - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto + /** + * Retourne le libelle du statut d'une charge (impaye, payee) + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise) - * @return string Label - */ - public function getLibStatut($mode = 0, $alreadypaid = -1) - { - return $this->LibStatut($this->paye, $mode, $alreadypaid); - } + * @return string Label + */ + public function getLibStatut($mode = 0, $alreadypaid = -1) + { + return $this->LibStatut($this->paye, $mode, $alreadypaid); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Renvoi le libelle d'un statut donne - * - * @param int $status Id status - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise) - * @return string Label - */ - public function LibStatut($status, $mode = 0, $alreadypaid = -1) - { - // phpcs:enable - global $langs; + * @return string Label + */ + public function LibStatut($status, $mode = 0, $alreadypaid = -1) + { + // phpcs:enable + global $langs; - // Load translation files required by the page - $langs->loadLangs(array("customers", "bills")); + // Load translation files required by the page + $langs->loadLangs(array("customers", "bills")); - // We reinit status array to force to redefine them because label may change according to properties values. - $this->labelStatus = array(); - $this->labelStatusShort = array(); + // We reinit status array to force to redefine them because label may change according to properties values. + $this->labelStatus = array(); + $this->labelStatusShort = array(); - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { - global $langs; - //$langs->load("mymodule"); - $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('Unpaid'); - $this->labelStatus[self::STATUS_PAID] = $langs->trans('Paid'); - if ($status == self::STATUS_UNPAID && $alreadypaid > 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); - $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('Unpaid'); - $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('Paid'); - if ($status == self::STATUS_UNPAID && $alreadypaid > 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); - } + if (empty($this->labelStatus) || empty($this->labelStatusShort)) + { + global $langs; + //$langs->load("mymodule"); + $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('Unpaid'); + $this->labelStatus[self::STATUS_PAID] = $langs->trans('Paid'); + if ($status == self::STATUS_UNPAID && $alreadypaid > 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('Unpaid'); + $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('Paid'); + if ($status == self::STATUS_UNPAID && $alreadypaid > 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } - $statusType = 'status1'; - if ($status == 0 && $alreadypaid > 0) $statusType = 'status3'; - if ($status == 1) $statusType = 'status6'; + $statusType = 'status1'; + if ($status == 0 && $alreadypaid > 0) $statusType = 'status3'; + if ($status == 1) $statusType = 'status6'; - return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); - } + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } - /** + /** * Return a link to the object card (with optionaly the picto) * * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) - * @param int $maxlen Max length of label - * @param int $notooltip 1=Disable tooltip + * @param int $maxlen Max length of label + * @param int $notooltip 1=Disable tooltip * @param int $short 1=Return just URL - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with link - */ - public function getNomUrl($withpicto = 0, $maxlen = 0, $notooltip = 0, $short = 0, $save_lastsearch_value = -1) - { - global $langs, $conf, $user, $form; + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with link + */ + public function getNomUrl($withpicto = 0, $maxlen = 0, $notooltip = 0, $short = 0, $save_lastsearch_value = -1) + { + global $langs, $conf, $user, $form; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - $result = ''; + $result = ''; - $url = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$this->id; - if ($short) return $url; + if ($short) return $url; - if ($option !== 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; - } + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; + if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + } - if (empty($this->ref)) $this->ref = $this->label; + if (empty($this->ref)) $this->ref = $this->label; - $label = ''.$langs->trans("SocialContribution").''; - if (!empty($this->ref)) - $label .= '
'.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->label)) - $label .= '
'.$langs->trans('Label').': '.$this->label; - if (!empty($this->type_label)) - $label .= '
'.$langs->trans('Type').': '.$this->type_label; + $label = ''.$langs->trans("SocialContribution").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->label)) + $label .= '
'.$langs->trans('Label').': '.$this->label; + if (!empty($this->type_label)) + $label .= '
'.$langs->trans('Type').': '.$this->type_label; - $linkclose = ''; - if (empty($notooltip) && $user->rights->facture->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("SocialContribution"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; - } + $linkclose = ''; + if (empty($notooltip) && $user->rights->facture->lire) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("SocialContribution"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } - $linkstart = ''; - $linkend = ''; + $linkstart = ''; + $linkend = ''; - $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref); - $result .= $linkend; + $result .= $linkstart; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref); + $result .= $linkend; - return $result; - } + return $result; + } - /** - * Return amount of payments already done - * - * @return int Amount of payment already done, <0 if KO - */ - public function getSommePaiement() - { - $table = 'paiementcharge'; - $field = 'fk_charge'; + /** + * Return amount of payments already done + * + * @return int Amount of payment already done, <0 if KO + */ + public function getSommePaiement() + { + $table = 'paiementcharge'; + $field = 'fk_charge'; - $sql = 'SELECT sum(amount) as amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$table; - $sql .= ' WHERE '.$field.' = '.$this->id; + $sql = 'SELECT sum(amount) as amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$table; + $sql .= ' WHERE '.$field.' = '.$this->id; - dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $amount = 0; + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $amount = 0; - $obj = $this->db->fetch_object($resql); - if ($obj) $amount = $obj->amount ? $obj->amount : 0; + $obj = $this->db->fetch_object($resql); + if ($obj) $amount = $obj->amount ? $obj->amount : 0; - $this->db->free($resql); - return $amount; - } else { - return -1; - } - } + $this->db->free($resql); + return $amount; + } else { + return -1; + } + } - /** - * Charge les informations d'ordre info dans l'objet entrepot - * - * @param int $id Id of social contribution - * @return int <0 if KO, >0 if OK - */ - public function info($id) - { - $sql = "SELECT e.rowid, e.tms as datem, e.date_creation as datec, e.date_valid as datev, e.import_key,"; - $sql .= " e.fk_user_author, e.fk_user_modif, e.fk_user_valid"; + /** + * Charge les informations d'ordre info dans l'objet entrepot + * + * @param int $id Id of social contribution + * @return int <0 if KO, >0 if OK + */ + public function info($id) + { + $sql = "SELECT e.rowid, e.tms as datem, e.date_creation as datec, e.date_valid as datev, e.import_key,"; + $sql .= " e.fk_user_author, e.fk_user_modif, e.fk_user_valid"; $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as e"; - $sql .= " WHERE e.rowid = ".$id; + $sql .= " WHERE e.rowid = ".$id; - dol_syslog(get_class($this)."::info", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + dol_syslog(get_class($this)."::info", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; + $this->id = $obj->rowid; - if ($obj->fk_user_author) { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } + if ($obj->fk_user_author) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } - if ($obj->fk_user_modif) { - $muser = new User($this->db); - $muser->fetch($obj->fk_user_modif); - $this->user_modification = $muser; - } + if ($obj->fk_user_modif) { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modif); + $this->user_modification = $muser; + } - if ($obj->fk_user_valid) { - $vuser = new User($this->db); - $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; - } + if ($obj->fk_user_valid) { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->datem); - $this->date_validation = $this->db->jdate($obj->datev); - $this->import_key = $obj->import_key; - } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + $this->import_key = $obj->import_key; + } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - /** - * 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() - { - // Initialize parameters - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->specimen = 1; - $this->paye = 0; - $this->date = dol_now(); - $this->date_ech = $this->date + 3600 * 24 * 30; - $this->periode = $this->date + 3600 * 24 * 30; - $this->amount = 100; - $this->label = 'Social contribution label'; - $this->type = 1; - $this->type_label = 'Type of social contribution'; - } + /** + * 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() + { + // Initialize parameters + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->specimen = 1; + $this->paye = 0; + $this->date = dol_now(); + $this->date_ech = $this->date + 3600 * 24 * 30; + $this->periode = $this->date + 3600 * 24 * 30; + $this->amount = 100; + $this->label = 'Social contribution label'; + $this->type = 1; + $this->type_label = 'Type of social contribution'; + } } diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 034e436a612..c278eaeedb7 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -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 diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 7cdf83f9961..6b76148d350 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -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; diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 8f06c0958c0..8b37604ce20 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -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; } } diff --git a/htdocs/core/lib/loan.lib.php b/htdocs/core/lib/loan.lib.php index 638eb83b9cd..3a34d3e57c4 100644 --- a/htdocs/core/lib/loan.lib.php +++ b/htdocs/core/lib/loan.lib.php @@ -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] .= ''.($nbFiles + $nbLinks).''; @@ -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; } diff --git a/htdocs/core/modules/project/task/mod_task_universal.php b/htdocs/core/modules/project/task/mod_task_universal.php index 0a15a99dfc0..011ac381254 100644 --- a/htdocs/core/modules/project/task/mod_task_universal.php +++ b/htdocs/core/modules/project/task/mod_task_universal.php @@ -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 .= ''; 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); + } } diff --git a/htdocs/don/class/don.class.php b/htdocs/don/class/don.class.php index a6fa9fa987d..8d5d22482b8 100644 --- a/htdocs/don/class/don.class.php +++ b/htdocs/don/class/don.class.php @@ -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 diff --git a/htdocs/expensereport/payment/payment.php b/htdocs/expensereport/payment/payment.php index a01eb50981d..19f979d0f16 100644 --- a/htdocs/expensereport/payment/payment.php +++ b/htdocs/expensereport/payment/payment.php @@ -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 "\n"; - } + print "\t});\n"; + print "\n"; + } print load_fiche_titre($langs->trans("DoPayment")); @@ -206,17 +206,17 @@ if ($action == 'create' || empty($action)) print ''; print ''; - print dol_get_fiche_head(null, '0', '', -1); + print dol_get_fiche_head(null, '0', '', -1); - $linkback = ''; - // $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''; + // $linkback = '' . $langs->trans("BackToList") . ''; - dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', ''); + dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', ''); - print '
'; - print '
'; + print '
'; + print '
'; - print '
'.$langs->trans("DatePayment").''; - print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1); - print '
'.$langs->trans("DatePayment").''; + print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1); + print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; - print $form->selectDate($datev, "datev", '', '', '', 'add', 1, 1); - print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; + print $form->selectDate($datev, "datev", '', '', '', 'add', 1, 1); + print '
'.$langs->trans("Label").'transcountry(($lttype == 2 ? "LT2Payment" : "LT1Payment"), $mysoc->country_code)).'">
'."\n"; + print '
'."\n"; print ''; print ''; @@ -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 ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // Number diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 06cfa6edfac..2d28ac799d7 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -61,13 +61,13 @@ function testSqlAndScriptInject($val, $type) // Decode string first // So debugbar->enabled) && !GETPOST('dol_use_jmobile') && empty($_SESSION['dol_use_jmobile'])) { - global $debugbar; - include_once DOL_DOCUMENT_ROOT.'/debugbar/class/DebugBar.php'; - $debugbar = new DolibarrDebugBar(); - $renderer = $debugbar->getRenderer(); - $conf->global->MAIN_HTML_HEADER .= $renderer->renderHead(); + global $debugbar; + include_once DOL_DOCUMENT_ROOT.'/debugbar/class/DebugBar.php'; + $debugbar = new DolibarrDebugBar(); + $renderer = $debugbar->getRenderer(); + $conf->global->MAIN_HTML_HEADER .= $renderer->renderHead(); - $debugbar['time']->startMeasure('pageaftermaster', 'Page generation (after environment init)'); + $debugbar['time']->startMeasure('pageaftermaster', 'Page generation (after environment init)'); } // Detection browser @@ -420,7 +420,7 @@ if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->gl if (GETPOSTISSET('disablemodules')) $_SESSION["disablemodules"] = GETPOST('disablemodules', 'alpha'); if (!empty($_SESSION["disablemodules"])) { - $modulepartkeys = array('css', 'js', 'tabs', 'triggers', 'login', 'substitutions', 'menus', 'theme', 'sms', 'tpl', 'barcode', 'models', 'societe', 'hooks', 'dir', 'syslog', 'tpllinkable', 'contactelement', 'moduleforexternal'); + $modulepartkeys = array('css', 'js', 'tabs', 'triggers', 'login', 'substitutions', 'menus', 'theme', 'sms', 'tpl', 'barcode', 'models', 'societe', 'hooks', 'dir', 'syslog', 'tpllinkable', 'contactelement', 'moduleforexternal'); $disabled_modules = explode(',', $_SESSION["disablemodules"]); foreach ($disabled_modules as $module) @@ -431,7 +431,7 @@ if (!empty($_SESSION["disablemodules"])) $conf->$module->enabled = false; foreach ($modulepartkeys as $modulepartkey) { - unset($conf->modules_parts[$modulepartkey][$module]); + unset($conf->modules_parts[$modulepartkey][$module]); } if ($module == 'fournisseur') // Special case { @@ -451,7 +451,7 @@ if (is_array($modulepart) && count($modulepart) > 0) if (in_array($module, $modulepart)) { $conf->modulepart = $module; - break; + break; } } } @@ -649,14 +649,14 @@ if (!defined('NOLOGIN')) if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED'; else { if ($_SERVER["HTTP_USER_AGENT"] == 'securitytest') { - http_response_code(401); // It makes easier to understand if session was broken during security tests + http_response_code(401); // It makes easier to understand if session was broken during security tests } dol_loginfunction($langs, $conf, (!empty($mysoc) ? $mysoc : '')); } exit; } - $resultFetchUser = $user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1)); // login was retrieved previously when checking password. + $resultFetchUser = $user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1)); // login was retrieved previously when checking password. if ($resultFetchUser <= 0) { dol_syslog('User not found, connexion refused'); @@ -757,48 +757,48 @@ if (!defined('NOLOGIN')) header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : '')); exit; } else { - // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context - $hookmanager->initHooks(array('main')); + // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context + $hookmanager->initHooks(array('main')); - // Code for search criteria persistence. - if (!empty($_GET['save_lastsearch_values'])) // We must use $_GET here - { - $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]); - $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server - // Clean $relativepathstring - if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); - $relativepathstring = preg_replace('/^\//', '', $relativepathstring); - $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); - //var_dump($relativepathstring); + // Code for search criteria persistence. + if (!empty($_GET['save_lastsearch_values'])) // We must use $_GET here + { + $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]); + $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server + // Clean $relativepathstring + if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); + $relativepathstring = preg_replace('/^\//', '', $relativepathstring); + $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); + //var_dump($relativepathstring); - // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp - if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring])) - { - $_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring]; - unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]); - } - if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring])) - { - $_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]; - unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]); - } - if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 0) - { - $_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring]; - unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]); - } - if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit) - { - $_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]; - unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]); - } - } + // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp + if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring])) + { + $_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring]; + unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]); + } + if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring])) + { + $_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]; + unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]); + } + if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 0) + { + $_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring]; + unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]); + } + if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit) + { + $_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]; + unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]); + } + } - $action = ''; - $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action); - if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } + $action = ''; + $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } } } @@ -1104,8 +1104,8 @@ if (!function_exists("llxHeader")) // If theme MD and classic layer, we open the menulayer by default. if ($conf->theme == 'md' && !in_array($conf->browser->layout, array('phone', 'tablet')) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - global $mainmenu; - if ($mainmenu != 'website') $tmpcsstouse = $morecssonbody; // We do not use sidebar-collpase by default to have menuhider open by default. + global $mainmenu; + if ($mainmenu != 'website') $tmpcsstouse = $morecssonbody; // We do not use sidebar-collpase by default to have menuhider open by default. } if (!empty($conf->global->MAIN_OPTIMIZEFORCOLORBLIND)) { @@ -1224,10 +1224,10 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr //print ''."\n"; if (empty($disablehead)) { - if (!is_object($hookmanager)) $hookmanager = new HookManager($db); - $hookmanager->initHooks(array("main")); + if (!is_object($hookmanager)) $hookmanager = new HookManager($db); + $hookmanager->initHooks(array("main")); - $ext = 'layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION); + $ext = 'layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION); print "\n"; @@ -1249,16 +1249,16 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print ''."\n"; //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print ''."\n"; - // Mobile appli like icon - $manifest = DOL_URL_ROOT.'/theme/'.$conf->theme.'/manifest.json.php'; - if (!empty($manifest)) { - print ''."\n"; - } + // Mobile appli like icon + $manifest = DOL_URL_ROOT.'/theme/'.$conf->theme.'/manifest.json.php'; + if (!empty($manifest)) { + print ''."\n"; + } - if (!empty($conf->global->THEME_ELDY_TOPMENU_BACK1)) { - // TODO: use auto theme color switch - print ''."\n"; - } + if (!empty($conf->global->THEME_ELDY_TOPMENU_BACK1)) { + // TODO: use auto theme color switch + print ''."\n"; + } // Auto refresh page if (GETPOST('autorefresh', 'int') > 0) print ''; @@ -1314,8 +1314,8 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr if (!defined('DISABLE_FONT_AWSOME')) { print ''."\n"; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; } print ''."\n"; @@ -1362,12 +1362,12 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr { foreach ($arrayofcss as $cssfile) { - if (preg_match('/^(http|\/\/)/i', $cssfile)) - { - $urltofile = $cssfile; - } else { - $urltofile = dol_buildpath($cssfile, 1); - } + if (preg_match('/^(http|\/\/)/i', $cssfile)) + { + $urltofile = $cssfile; + } else { + $urltofile = dol_buildpath($cssfile, 1); + } print ''."\n".''."\n"; print ''."\n"; } - // jQuery Timepicker - if (!empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER')) { - print ''."\n"; - print ''."\n"; - } - if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) { - // jQuery plugin "mutiselect", "multiple-select", "select2", ... - $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT; - print ''."\n"; // We include full because we need the support of containerCssClass - } - if (! defined('DISABLE_MULTISELECT')) // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool - { - print ''."\n"; - } + // jQuery Timepicker + if (!empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER')) { + print ''."\n"; + print ''."\n"; + } + if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) { + // jQuery plugin "mutiselect", "multiple-select", "select2", ... + $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT; + print ''."\n"; // We include full because we need the support of containerCssClass + } + if (! defined('DISABLE_MULTISELECT')) // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool + { + print ''."\n"; + } } - if (!$disablejs && !empty($conf->use_javascript_ajax)) { - // CKEditor - if ((!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) - { - print ''."\n"; - $pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/'; - $jsckeditor = 'ckeditor.js'; - if (constant('JS_CKEDITOR')) { - // To use external ckeditor 4 js lib - $pathckeditor = constant('JS_CKEDITOR'); - } - print ''."\n"; - print ''."\n"; - print ''."\n"; - } + if (!$disablejs && !empty($conf->use_javascript_ajax)) { + // CKEditor + if ((!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) + { + print ''."\n"; + $pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/'; + $jsckeditor = 'ckeditor.js'; + if (constant('JS_CKEDITOR')) { + // To use external ckeditor 4 js lib + $pathckeditor = constant('JS_CKEDITOR'); + } + print ''."\n"; + print ''."\n"; + print ''."\n"; + } - // Browser notifications (if NOREQUIREMENU is on, it is mostly a page for popup, so we do not enable notif too. We hide also for public pages). - if (!defined('NOBROWSERNOTIF') && !defined('NOREQUIREMENU') && !defined('NOLOGIN')) - { - $enablebrowsernotif = false; - if (!empty($conf->agenda->enabled) && !empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif = true; - if ($conf->browser->layout == 'phone') $enablebrowsernotif = false; - if ($enablebrowsernotif) - { - print ''."\n"; - print ''."\n"; - } - } + // Browser notifications (if NOREQUIREMENU is on, it is mostly a page for popup, so we do not enable notif too. We hide also for public pages). + if (!defined('NOBROWSERNOTIF') && !defined('NOREQUIREMENU') && !defined('NOLOGIN')) + { + $enablebrowsernotif = false; + if (!empty($conf->agenda->enabled) && !empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif = true; + if ($conf->browser->layout == 'phone') $enablebrowsernotif = false; + if ($enablebrowsernotif) + { + print ''."\n"; + print ''."\n"; + } + } - // Global js function - print ''."\n"; - print ''."\n"; + // Global js function + print ''."\n"; + print ''."\n"; - // JS forced by modules (relative url starting with /) - if (!empty($conf->modules_parts['js'])) // $conf->modules_parts['js'] is array('module'=>array('file1','file2')) - { - $arrayjs = (array) $conf->modules_parts['js']; - foreach ($arrayjs as $modjs => $filesjs) - { - $filesjs = (array) $filesjs; // To be sure filejs is an array - foreach ($filesjs as $jsfile) - { - // jsfile is a relative path - print ''."\n".''."\n"; - } - } - } - // JS forced by page in top_htmlhead (relative url starting with /) - if (is_array($arrayofjs)) - { - print ''."\n"; - foreach ($arrayofjs as $jsfile) - { - if (preg_match('/^(http|\/\/)/i', $jsfile)) - { - print ''."\n"; - } else { - print ''."\n"; - } - } - } - } + // JS forced by modules (relative url starting with /) + if (!empty($conf->modules_parts['js'])) // $conf->modules_parts['js'] is array('module'=>array('file1','file2')) + { + $arrayjs = (array) $conf->modules_parts['js']; + foreach ($arrayjs as $modjs => $filesjs) + { + $filesjs = (array) $filesjs; // To be sure filejs is an array + foreach ($filesjs as $jsfile) + { + // jsfile is a relative path + print ''."\n".''."\n"; + } + } + } + // JS forced by page in top_htmlhead (relative url starting with /) + if (is_array($arrayofjs)) + { + print ''."\n"; + foreach ($arrayofjs as $jsfile) + { + if (preg_match('/^(http|\/\/)/i', $jsfile)) + { + print ''."\n"; + } else { + print ''."\n"; + } + } + } + } - if (!empty($head)) print $head."\n"; - if (!empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n"; + if (!empty($head)) print $head."\n"; + if (!empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n"; - $parameters = array(); - $result = $hookmanager->executeHooks('addHtmlHeader', $parameters); // Note that $action and $object may have been modified by some hooks - print $hookmanager->resPrint; // Replace Title to show + $parameters = array(); + $result = $hookmanager->executeHooks('addHtmlHeader', $parameters); // Note that $action and $object may have been modified by some hooks + print $hookmanager->resPrint; // Replace Title to show - print "\n\n"; - } + print "\n\n"; + } - $conf->headerdone = 1; // To tell header was output + $conf->headerdone = 1; // To tell header was output } @@ -1759,99 +1759,99 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead */ function top_menu_user($hideloginname = 0, $urllogout = '') { - global $langs, $conf, $db, $hookmanager, $user; - global $dolibarr_main_authentication, $dolibarr_main_demo; - global $menumanager; + global $langs, $conf, $db, $hookmanager, $user; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; - $userImage = $userDropDownImage = ''; - if (!empty($user->photo)) - { - $userImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'photouserphoto userphoto', 'small', 0, 1); - $userDropDownImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'dropdown-user-image', 'small', 0, 1); - } else { - $nophoto = '/public/theme/common/user_anonymous.png'; - if ($user->gender == 'man') $nophoto = '/public/theme/common/user_man.png'; - if ($user->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png'; + $userImage = $userDropDownImage = ''; + if (!empty($user->photo)) + { + $userImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'photouserphoto userphoto', 'small', 0, 1); + $userDropDownImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'dropdown-user-image', 'small', 0, 1); + } else { + $nophoto = '/public/theme/common/user_anonymous.png'; + if ($user->gender == 'man') $nophoto = '/public/theme/common/user_man.png'; + if ($user->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png'; - $userImage = 'No photo'; - $userDropDownImage = 'No photo'; - } + $userImage = 'No photo'; + $userDropDownImage = 'No photo'; + } - $dropdownBody = ''; - $dropdownBody .= ' '.$langs->trans("ShowMoreInfos").''; - $dropdownBody .= '
'; + $dropdownBody = ''; + $dropdownBody .= ' '.$langs->trans("ShowMoreInfos").''; + $dropdownBody .= '
'; - // login infos - if (!empty($user->admin)) { - $dropdownBody .= '
'.$langs->trans("Administrator").': '.yn($user->admin); - } - if (!empty($user->socid)) // Add thirdparty for external users - { - $thirdpartystatic = new Societe($db); - $thirdpartystatic->fetch($user->socid); - $companylink = ' '.$thirdpartystatic->getNomUrl(2); // picto only of company - $company = ' ('.$langs->trans("Company").': '.$thirdpartystatic->name.')'; - } - $type = ($user->socid ? $langs->trans("External").$company : $langs->trans("Internal")); - $dropdownBody .= '
'.$langs->trans("Type").': '.$type; - $dropdownBody .= '
'.$langs->trans("Status").': '.$user->getLibStatut(0); - $dropdownBody .= '
'; + // login infos + if (!empty($user->admin)) { + $dropdownBody .= '
'.$langs->trans("Administrator").': '.yn($user->admin); + } + if (!empty($user->socid)) // Add thirdparty for external users + { + $thirdpartystatic = new Societe($db); + $thirdpartystatic->fetch($user->socid); + $companylink = ' '.$thirdpartystatic->getNomUrl(2); // picto only of company + $company = ' ('.$langs->trans("Company").': '.$thirdpartystatic->name.')'; + } + $type = ($user->socid ? $langs->trans("External").$company : $langs->trans("Internal")); + $dropdownBody .= '
'.$langs->trans("Type").': '.$type; + $dropdownBody .= '
'.$langs->trans("Status").': '.$user->getLibStatut(0); + $dropdownBody .= '
'; - $dropdownBody .= '
'.$langs->trans("Session").''; - $dropdownBody .= '
'.$langs->trans("IPAddress").': '.dol_escape_htmltag($_SERVER["REMOTE_ADDR"]); - if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) $dropdownBody .= '
'.$langs->trans("ConnectedOnMultiCompany").': '.$conf->entity.' (user entity '.$user->entity.')'; - $dropdownBody .= '
'.$langs->trans("AuthenticationMode").': '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'); - $dropdownBody .= '
'.$langs->trans("ConnectedSince").': '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser'); - $dropdownBody .= '
'.$langs->trans("PreviousConnexion").': '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser'); - $dropdownBody .= '
'.$langs->trans("CurrentTheme").': '.$conf->theme; - $dropdownBody .= '
'.$langs->trans("CurrentMenuManager").': '.$menumanager->name; - $langFlag = picto_from_langcode($langs->getDefaultLang()); - $dropdownBody .= '
'.$langs->trans("CurrentUserLanguage").': '.($langFlag ? $langFlag.' ' : '').$langs->getDefaultLang(); - $dropdownBody .= '
'.$langs->trans("Browser").': '.$conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.dol_escape_htmltag($_SERVER['HTTP_USER_AGENT']).')'; - $dropdownBody .= '
'.$langs->trans("Layout").': '.$conf->browser->layout; - $dropdownBody .= '
'.$langs->trans("Screen").': '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; - if ($conf->browser->layout == 'phone') $dropdownBody .= '
'.$langs->trans("Phone").': '.$langs->trans("Yes"); - if (!empty($_SESSION["disablemodules"])) $dropdownBody .= '
'.$langs->trans("DisabledModules").':
'.join(', ', explode(',', $_SESSION["disablemodules"])); - $dropdownBody .= '
'; + $dropdownBody .= '
'.$langs->trans("Session").''; + $dropdownBody .= '
'.$langs->trans("IPAddress").': '.dol_escape_htmltag($_SERVER["REMOTE_ADDR"]); + if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) $dropdownBody .= '
'.$langs->trans("ConnectedOnMultiCompany").': '.$conf->entity.' (user entity '.$user->entity.')'; + $dropdownBody .= '
'.$langs->trans("AuthenticationMode").': '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'); + $dropdownBody .= '
'.$langs->trans("ConnectedSince").': '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser'); + $dropdownBody .= '
'.$langs->trans("PreviousConnexion").': '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser'); + $dropdownBody .= '
'.$langs->trans("CurrentTheme").': '.$conf->theme; + $dropdownBody .= '
'.$langs->trans("CurrentMenuManager").': '.$menumanager->name; + $langFlag = picto_from_langcode($langs->getDefaultLang()); + $dropdownBody .= '
'.$langs->trans("CurrentUserLanguage").': '.($langFlag ? $langFlag.' ' : '').$langs->getDefaultLang(); + $dropdownBody .= '
'.$langs->trans("Browser").': '.$conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.dol_escape_htmltag($_SERVER['HTTP_USER_AGENT']).')'; + $dropdownBody .= '
'.$langs->trans("Layout").': '.$conf->browser->layout; + $dropdownBody .= '
'.$langs->trans("Screen").': '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; + if ($conf->browser->layout == 'phone') $dropdownBody .= '
'.$langs->trans("Phone").': '.$langs->trans("Yes"); + if (!empty($_SESSION["disablemodules"])) $dropdownBody .= '
'.$langs->trans("DisabledModules").':
'.join(', ', explode(',', $_SESSION["disablemodules"])); + $dropdownBody .= '
'; - // Execute hook - $parameters = array('user'=>$user, 'langs' => $langs); - $result = $hookmanager->executeHooks('printTopRightMenuLoginDropdownBody', $parameters); // Note that $action and $object may have been modified by some hooks - if (is_numeric($result)) - { - if ($result == 0) { - $dropdownBody .= $hookmanager->resPrint; // add - } else { - $dropdownBody = $hookmanager->resPrint; // replace - } - } + // Execute hook + $parameters = array('user'=>$user, 'langs' => $langs); + $result = $hookmanager->executeHooks('printTopRightMenuLoginDropdownBody', $parameters); // Note that $action and $object may have been modified by some hooks + if (is_numeric($result)) + { + if ($result == 0) { + $dropdownBody .= $hookmanager->resPrint; // add + } else { + $dropdownBody = $hookmanager->resPrint; // replace + } + } - if (empty($urllogout)) { - $urllogout = DOL_URL_ROOT.'/user/logout.php'; - } - $logoutLink = ' '.$langs->trans("Logout").''; - $profilLink = ' '.$langs->trans("Card").''; + if (empty($urllogout)) { + $urllogout = DOL_URL_ROOT.'/user/logout.php'; + } + $logoutLink = ' '.$langs->trans("Logout").''; + $profilLink = ' '.$langs->trans("Card").''; - $profilName = $user->getFullName($langs).' ('.$user->login.')'; + $profilName = $user->getFullName($langs).' ('.$user->login.')'; - if (!empty($user->admin)) { - $profilName = ' '.$profilName; - } + if (!empty($user->admin)) { + $profilName = ' '.$profilName; + } - // Define version to show - $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; + // Define version to show + $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; - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $btnUser = ' + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $btnUser = ''; - } + } - if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) // This may be set by some pages that use different jquery version to avoid errors - { - $btnUser .= ' + if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) // This may be set by some pages that use different jquery version to avoid errors + { + $btnUser .= ' '; - } + } - return $btnUser; + return $btnUser; } /** @@ -2160,24 +2160,24 @@ function top_menu_quickadd() */ function top_menu_bookmark() { - global $langs, $conf, $db, $user; + global $langs, $conf, $db, $user; $html = ''; - // Define $bookmarks + // Define $bookmarks if (empty($conf->bookmark->enabled) || empty($user->rights->bookmark->lire)) return $html; if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) // This may be set by some pages that use different jquery version to avoid errors - { - include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php'; - $langs->load("bookmarks"); + { + include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php'; + $langs->load("bookmarks"); - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $html .= ''; - } else { - $html .= ' + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $html .= ''; + } else { + $html .= ''; - } elseif ($conf->use_javascript_ajax && !empty($conf->global->MAIN_USE_OLD_SEARCH_FORM)) { - $searchform = '
'; - $searchform .= '' . "\n"; - $searchform .= '
'; - } - } + $searchform .= ''; + } + } // Left column print ''."\n"; @@ -2474,37 +2474,37 @@ function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_ { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new?labels=Bug'; + $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new?labels=Bug'; $bugbaseurl .= '&title='; $bugbaseurl .= urlencode("Bug: "); - $bugbaseurl .= '&body='; - $bugbaseurl .= urlencode("# Instructions\n"); - $bugbaseurl .= urlencode("*This is a template to help you report good issues. You may use [Github Markdown](https://help.github.com/articles/getting-started-with-writing-and-formatting-on-github/) syntax to format your issue report.*\n"); - $bugbaseurl .= urlencode("*Please:*\n"); - $bugbaseurl .= urlencode("- *replace the bracket enclosed texts with meaningful information*\n"); - $bugbaseurl .= urlencode("- *remove any unused sub-section*\n"); - $bugbaseurl .= urlencode("\n"); - $bugbaseurl .= urlencode("\n"); - $bugbaseurl .= urlencode("# Bug\n"); - $bugbaseurl .= urlencode("[*Short description*]\n"); - $bugbaseurl .= urlencode("\n"); - $bugbaseurl .= urlencode("## Environment\n"); - $bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n"); - $bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n"); - $bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n"); - $bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n"); - $bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n"); - $bugbaseurl .= urlencode("- **URL(s)**: ".$_SERVER["REQUEST_URI"]."\n"); - $bugbaseurl .= urlencode("\n"); - $bugbaseurl .= urlencode("## Expected and actual behavior\n"); - $bugbaseurl .= urlencode("[*Verbose description*]\n"); - $bugbaseurl .= urlencode("\n"); - $bugbaseurl .= urlencode("## Steps to reproduce the behavior\n"); - $bugbaseurl .= urlencode("[*Verbose description*]\n"); - $bugbaseurl .= urlencode("\n"); - $bugbaseurl .= urlencode("## [Attached files](https://help.github.com/articles/issue-attachments) (Screenshots, screencasts, dolibarr.log, debugging informations…)\n"); - $bugbaseurl .= urlencode("[*Files*]\n"); - $bugbaseurl .= urlencode("\n"); + $bugbaseurl .= '&body='; + $bugbaseurl .= urlencode("# Instructions\n"); + $bugbaseurl .= urlencode("*This is a template to help you report good issues. You may use [Github Markdown](https://help.github.com/articles/getting-started-with-writing-and-formatting-on-github/) syntax to format your issue report.*\n"); + $bugbaseurl .= urlencode("*Please:*\n"); + $bugbaseurl .= urlencode("- *replace the bracket enclosed texts with meaningful information*\n"); + $bugbaseurl .= urlencode("- *remove any unused sub-section*\n"); + $bugbaseurl .= urlencode("\n"); + $bugbaseurl .= urlencode("\n"); + $bugbaseurl .= urlencode("# Bug\n"); + $bugbaseurl .= urlencode("[*Short description*]\n"); + $bugbaseurl .= urlencode("\n"); + $bugbaseurl .= urlencode("## Environment\n"); + $bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n"); + $bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n"); + $bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n"); + $bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n"); + $bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n"); + $bugbaseurl .= urlencode("- **URL(s)**: ".$_SERVER["REQUEST_URI"]."\n"); + $bugbaseurl .= urlencode("\n"); + $bugbaseurl .= urlencode("## Expected and actual behavior\n"); + $bugbaseurl .= urlencode("[*Verbose description*]\n"); + $bugbaseurl .= urlencode("\n"); + $bugbaseurl .= urlencode("## Steps to reproduce the behavior\n"); + $bugbaseurl .= urlencode("[*Verbose description*]\n"); + $bugbaseurl .= urlencode("\n"); + $bugbaseurl .= urlencode("## [Attached files](https://help.github.com/articles/issue-attachments) (Screenshots, screencasts, dolibarr.log, debugging informations…)\n"); + $bugbaseurl .= urlencode("[*Files*]\n"); + $bugbaseurl .= urlencode("\n"); // Execute hook printBugtrackInfo @@ -2563,35 +2563,35 @@ function main_area($title = '') if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED)); - // Permit to add user company information on each printed document by set SHOW_SOCINFO_ON_PRINT - if (!empty($conf->global->SHOW_SOCINFO_ON_PRINT) && GETPOST('optioncss', 'aZ09') == 'print' && empty(GETPOST('disable_show_socinfo_on_print', 'az09'))) - { - global $hookmanager; - $hookmanager->initHooks(array('showsocinfoonprint')); - $parameters = array(); - $reshook = $hookmanager->executeHooks('showSocinfoOnPrint', $parameters); - if (empty($reshook)) - { - print ''."\n"; - print '
'."\n"; - print '
'.$langs->trans("Period").''.get_date_range($expensereport->date_debut, $expensereport->date_fin, "", $langs, 0).'
'.$langs->trans("Amount").''.price($expensereport->total_ttc, 0, $outputlangs, 1, -1, -1, $conf->currency).'
'.$langs->trans('AccountToDebit').''; - $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", "int") : $expensereport->accountid, "accountid", 0, '', 2); // Show open bank account list - print '
'.$langs->trans('AccountToDebit').''; + $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", "int") : $expensereport->accountid, "accountid", 0, '', 2); // Show open bank account list + print '
'."\n"; - print ''; - print ''."\n"; - print ''."\n"; - print ''."\n"; - if (!empty($conf->global->MAIN_INFO_SOCIETE_TEL)) print ''; - if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) print ''; - if (!empty($conf->global->MAIN_INFO_SOCIETE_WEB)) print ''; - print ''; - print '
'; - if ($conf->global->MAIN_SHOW_LOGO && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && !empty($conf->global->MAIN_INFO_SOCIETE_LOGO)) { - print ''; - } - print '
'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM).'
'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ADDRESS).'
'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ZIP).' '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TOWN).'
'.$langs->trans("Phone").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TEL).'
'.$langs->trans("Email").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_MAIL).'
'.$langs->trans("Web").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_WEB).'
'."\n"; - print ''."\n"; - print ''."\n"; - } - } + // Permit to add user company information on each printed document by set SHOW_SOCINFO_ON_PRINT + if (!empty($conf->global->SHOW_SOCINFO_ON_PRINT) && GETPOST('optioncss', 'aZ09') == 'print' && empty(GETPOST('disable_show_socinfo_on_print', 'az09'))) + { + global $hookmanager; + $hookmanager->initHooks(array('showsocinfoonprint')); + $parameters = array(); + $reshook = $hookmanager->executeHooks('showSocinfoOnPrint', $parameters); + if (empty($reshook)) + { + print ''."\n"; + print '
'."\n"; + print ''."\n"; + print ''; + print ''."\n"; + print ''."\n"; + print ''."\n"; + if (!empty($conf->global->MAIN_INFO_SOCIETE_TEL)) print ''; + if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) print ''; + if (!empty($conf->global->MAIN_INFO_SOCIETE_WEB)) print ''; + print ''; + print '
'; + if ($conf->global->MAIN_SHOW_LOGO && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && !empty($conf->global->MAIN_INFO_SOCIETE_LOGO)) { + print ''; + } + print '
'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM).'
'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ADDRESS).'
'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ZIP).' '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TOWN).'
'.$langs->trans("Phone").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TEL).'
'.$langs->trans("Email").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_MAIL).'
'.$langs->trans("Web").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_WEB).'
'."\n"; + print '
'."\n"; + print ''."\n"; + } + } } @@ -2906,5 +2906,5 @@ if (!function_exists("llxFooter")) print "\n"; print "\n"; - } + } } diff --git a/htdocs/paypal/lib/paypal.lib.php b/htdocs/paypal/lib/paypal.lib.php index f0833fd5f3e..00db8797a1f 100644 --- a/htdocs/paypal/lib/paypal.lib.php +++ b/htdocs/paypal/lib/paypal.lib.php @@ -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 = '

'; - $out .= img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'
'; - $url = getPaypalPaymentUrl(0, $type, $ref); - $out .= ''; - $out .= ajax_autoselect("paypalurl", 0); - return $out; + $langs->load("paybox"); + $servicename = 'PayPal'; + $out = '

'; + $out .= img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'
'; + $url = getPaypalPaymentUrl(0, $type, $ref); + $out .= ''; + $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 ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); - 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 ? '' : ''); - if ($mode == 1) $out .= 'order_ref'; - if ($mode == 0) $out .= urlencode($ref); - $out .= ($mode ? '' : ''); - 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 ? '' : ''); - 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 ? '' : ''); - } - } - } - if ($type == 'invoice') - { - $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'invoice_ref'; - if ($mode == 0) $out .= urlencode($ref); - $out .= ($mode ? '' : ''); - 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 ? '' : ''); - 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 ? '' : ''); - } - } - } - if ($type == 'contractline') - { - $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'contractline_ref'; - if ($mode == 0) $out .= urlencode($ref); - $out .= ($mode ? '' : ''); - 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 ? '' : ''); - 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 ? '' : ''); - } - } - } - if ($type == 'membersubscription') - { - $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'member_ref'; - if ($mode == 0) $out .= urlencode($ref); - $out .= ($mode ? '' : ''); - 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 ? '' : ''); - 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 ? '' : ''); - } - } - } + if ($type == 'free') + { + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); + 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 ? '' : ''); + if ($mode == 1) $out .= 'order_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + 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 ? '' : ''); + 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 ? '' : ''); + } + } + } + if ($type == 'invoice') + { + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode ? '' : ''); + if ($mode == 1) $out .= 'invoice_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + 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 ? '' : ''); + 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 ? '' : ''); + } + } + } + if ($type == 'contractline') + { + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode ? '' : ''); + if ($mode == 1) $out .= 'contractline_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + 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 ? '' : ''); + 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 ? '' : ''); + } + } + } + if ($type == 'membersubscription') + { + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); + if ($mode == 1) $out .= 'member_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + 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 ? '' : ''); + 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 ? '' : ''); + } + } + } - // 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).
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).
\n"; - } else { - $mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."
\n"; - $mesg .= $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."
\n"; - $mesg .= $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."
\n"; - $mesg .= $langs->trans('ErrorCode').": ".$ErrorCode."
\n"; - $mesg .= $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."
\n"; - } + if ($ErrorCode == 10729) + { + $mesg .= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).
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).
\n"; + } else { + $mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."
\n"; + $mesg .= $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."
\n"; + $mesg .= $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."
\n"; + $mesg .= $langs->trans('ErrorCode').": ".$ErrorCode."
\n"; + $mesg .= $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."
\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."
"; + /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."
"; print $USE_PROXY."-".$gv_ApiErrorURL."
"; 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; } /** diff --git a/htdocs/product/stats/card.php b/htdocs/product/stats/card.php index 24a6d7d36b8..d4df28e0902 100644 --- a/htdocs/product/stats/card.php +++ b/htdocs/product/stats/card.php @@ -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ódulo_Productos'; - //$title=$langs->trans("StatisticsOfProducts"); - $title = $langs->trans("Statistics"); - } elseif ($type == '1') { - $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - //$title=$langs->trans("StatisticsOfServices"); - $title = $langs->trans("Statistics"); - } else { - $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - //$title=$langs->trans("StatisticsOfProductsOrServices"); - $title = $langs->trans("Statistics"); - } + if ($type == '0') { + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + //$title=$langs->trans("StatisticsOfProducts"); + $title = $langs->trans("Statistics"); + } elseif ($type == '1') { + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + //$title=$langs->trans("StatisticsOfServices"); + $title = $langs->trans("Statistics"); + } else { + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Mó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 '
'.$langs->trans("Categories").''; - //$moreforfilter.='
'; - $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1); - //$moreforfilter.='
'; - print $moreforfilter; - print '
'.$langs->trans("Categories").''; + //$moreforfilter.='
'; + $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1); + //$moreforfilter.='
'; + print $moreforfilter; + print '
'.$langs->trans("Year").''; $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 ? ''.$mesg.'' : $langs->trans("ChartNotGenerated")); + $dategenerated = ($mesg ? ''.$mesg.'' : $langs->trans("ChartNotGenerated")); } $linktoregenerate = 'id).((string) $type != '' ? '&type='.$type : '').'&action=recalcul&mode='.$mode.'&search_year='.$search_year.'&search_categ='.$search_categ.'">'.img_picto($langs->trans("ReCalculate").' ('.$dategenerated.')', 'refresh').''; diff --git a/htdocs/product/stock/class/mouvementstock.class.php b/htdocs/product/stock/class/mouvementstock.class.php index 8a4697be2a1..0567c34a759 100644 --- a/htdocs/product/stock/class/mouvementstock.class.php +++ b/htdocs/product/stock/class/mouvementstock.class.php @@ -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) { diff --git a/htdocs/public/members/new.php b/htdocs/public/members/new.php index e398b23935c..923c57b4692 100644 --- a/htdocs/public/members/new.php +++ b/htdocs/public/members/new.php @@ -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 ''; + print ''; - // 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&modulepart=mycompany&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&modulepart=mycompany&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&modulepart=mycompany&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&modulepart=mycompany&file='.urlencode('logos/'.$mysoc->logo); + } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) { + $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg'; + } print '
'; - // Output html code for logo - if ($urllogo) { - print '
'; - print '
'; - print ''; - print '
'; - if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print ''; - } - print '
'; - } - print '
'; + // Output html code for logo + if ($urllogo) { + print '
'; + print '
'; + print ''; + print '
'; + if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { + print ''; + } + print '
'; + } + print ''; - print '
'; + print '
'; } /** @@ -139,12 +139,12 @@ function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $ */ function llxFooterVierge() { - print '
'; + print '
'; - printCommonFooter('public'); + printCommonFooter('public'); - print "\n"; - print "\n"; + print "\n"; + print "\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"))."
\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")."
\n"; - } - if (!isset($_POST["pass1"]) || !isset($_POST["pass2"]) || $_POST["pass1"] == '' || $_POST["pass2"] == '' || $_POST["pass1"] != $_POST["pass2"]) { - $error++; - $langs->load("errors"); - $errmsg .= $langs->trans("ErrorPasswordsMustMatch")."
\n"; - } - if (!GETPOST("email")) { - $error++; - $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."
\n"; - } - } - if (GETPOST('type') <= 0) { - $error++; - $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."
\n"; - } - if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) { - $error++; - $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."
\n"; - } - if (empty($_POST["lastname"])) { - $error++; - $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."
\n"; - } - if (empty($_POST["firstname"])) { - $error++; - $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."
\n"; - } - if (GETPOST("email") && !isValidEmail(GETPOST("email"))) { - $error++; - $langs->load("errors"); - $errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."
\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")."
\n"; - } - if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) { - if (GETPOST("morphy") == 'mor' && GETPOST('budget') <= 0) { - $error++; - $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TurnoverOrBudget"))."
\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"))."
\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")."
\n"; + } + if (!isset($_POST["pass1"]) || !isset($_POST["pass2"]) || $_POST["pass1"] == '' || $_POST["pass2"] == '' || $_POST["pass1"] != $_POST["pass2"]) { + $error++; + $langs->load("errors"); + $errmsg .= $langs->trans("ErrorPasswordsMustMatch")."
\n"; + } + if (!GETPOST("email")) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."
\n"; + } + } + if (GETPOST('type') <= 0) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."
\n"; + } + if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."
\n"; + } + if (empty($_POST["lastname"])) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."
\n"; + } + if (empty($_POST["firstname"])) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."
\n"; + } + if (GETPOST("email") && !isValidEmail(GETPOST("email"))) { + $error++; + $langs->load("errors"); + $errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."
\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")."
\n"; + } + if (!empty($conf->global->MEMBER_NEWFORM_DOLIBARRTURNOVER)) { + if (GETPOST("morphy") == 'mor' && GETPOST('budget') <= 0) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TurnoverOrBudget"))."
\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('
', $adh->errors); - } - } + if (!empty($entity)) $urlback .= '&entity='.$entity; + dol_syslog("member ".$adh->ref." was created, we redirect to ".$urlback); + } else { + $error++; + $errmsg .= join('
', $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 '
'; - print '
'; - print $langs->trans("NewMemberbyWeb"); - print '
'; + // Si on a pas ete redirige + print '
'; + print '
'; + print $langs->trans("NewMemberbyWeb"); + print '
'; - llxFooterVierge(); - exit; + llxFooterVierge(); + exit; } @@ -460,9 +460,9 @@ print '
'; print '
'; if (!empty($conf->global->MEMBER_NEWFORM_TEXT)) { - print $langs->trans($conf->global->MEMBER_NEWFORM_TEXT)."
\n"; + print $langs->trans($conf->global->MEMBER_NEWFORM_TEXT)."
\n"; } else { - print $langs->trans("NewSubscriptionDesc", $conf->global->MAIN_INFO_SOCIETE_MAIL)."
\n"; + print $langs->trans("NewSubscriptionDesc", $conf->global->MAIN_INFO_SOCIETE_MAIL)."
\n"; } print '
'; @@ -510,31 +510,31 @@ print ''." // 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 ''."\n"; + print ''."\n"; } else { - $adht->fetch($conf->global->MEMBER_NEWFORM_FORCETYPE); - print ''; + $adht->fetch($conf->global->MEMBER_NEWFORM_FORCETYPE); + print ''; } // Moral/Physic attribute $morphys["phy"] = $langs->trans("Physical"); $morphys["mor"] = $langs->trans("Moral"); if (empty($conf->global->MEMBER_NEWFORM_FORCEMORPHY)) { - print ''."\n"; + print ''."\n"; } else { - print $morphys[$conf->global->MEMBER_NEWFORM_FORCEMORPHY]; - print ''; + print $morphys[$conf->global->MEMBER_NEWFORM_FORCEMORPHY]; + print ''; } // Civility print ''; print ''; // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { - print ''; + print ''; } // EMail print ''."\n"; // Login if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { - print ''."\n"; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; } // Birthday print ''."\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 ''."\n"; + print ''."\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 ''; + 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 ''; } print "
'.$langs->trans("Type").' *'; - print $form->selectarray("type", $adht->liste_array(), GETPOST('type') ?GETPOST('type') : $defaulttype, $isempty); - print '
'.$langs->trans("Type").' *'; + print $form->selectarray("type", $adht->liste_array(), GETPOST('type') ?GETPOST('type') : $defaulttype, $isempty); + print '
'.$langs->trans('MemberNature').' *'."\n"; - print $form->selectarray("morphy", $morphys, GETPOST('morphy'), 1); - print '
'.$langs->trans('MemberNature').' *'."\n"; + print $form->selectarray("morphy", $morphys, GETPOST('morphy'), 1); + print '
'.$langs->trans('UserTitle').''; @@ -564,34 +564,34 @@ print '
'.$langs->trans('Country').''; $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 '
'.$langs->trans('State').''; - if ($country_code) print $formcompany->select_state(GETPOST("state_id"), $country_code); - else print ''; - print '
'.$langs->trans('State').''; + if ($country_code) print $formcompany->select_state(GETPOST("state_id"), $country_code); + else print ''; + print '
'.$langs->trans("Email").' *
'.$langs->trans("Login").' *
'.$langs->trans("Password").' *
'.$langs->trans("PasswordAgain").' *
'.$langs->trans("Login").' *
'.$langs->trans("Password").' *
'.$langs->trans("PasswordAgain").' *
'.$langs->trans("DateToBirth").''; @@ -612,12 +612,12 @@ print '
'.$langs->trans("TurnoverOrBudget").' *'; - 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 '
'.$langs->trans("TurnoverOrBudget").' *'; + print $form->selectarray('budget', $arraybudget, GETPOST('budget'), 1); + print ' € or $'; - print ''; - print '
'.$langs->trans("Subscription").''; - if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { - print ''; - } else { - print ''; - print ''; - } - print ' '.$langs->trans("Currency".$conf->currency); - print '
'.$langs->trans("Subscription").''; + if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { + print ''; + } else { + print ''; + print ''; + } + print ' '.$langs->trans("Currency".$conf->currency); + print '
\n"; @@ -682,7 +682,7 @@ print dol_get_fiche_end(); print '
'; print ''; if (!empty($backtopage)) { - print '     '; + print '     '; } print '
'; diff --git a/htdocs/public/onlinesign/newonlinesign.php b/htdocs/public/onlinesign/newonlinesign.php index 7c58d0ef944..1291035760f 100644 --- a/htdocs/public/onlinesign/newonlinesign.php +++ b/htdocs/public/onlinesign/newonlinesign.php @@ -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 ''."\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])."
\n"; - else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."
\n"; - $text = '

'.$text.'

'.$text.'

'.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'
'.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'


'.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'
'.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'

'.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
'.$creditor.''; + print ''; + print '
'."\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 ''."\n"; diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index a44428808a4..90ded9e8008 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -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 ''."\n"; if ($object->datefin > 0) { - print ''.$langs->trans("DateEndSubscription"); - print ''.dol_print_date($member->datefin, 'day'); - print ''."\n"; + print ''.$langs->trans("DateEndSubscription"); + print ''.dol_print_date($member->datefin, 'day'); + print ''."\n"; } if ($member->last_subscription_date || $member->last_subscription_amount) @@ -1667,13 +1667,13 @@ if ($action != 'dopayment') { print '

'.$langs->trans("DonationPaid").''; } else { - // Membership can be paid and we still allow to make renewal - if ($source == 'membersubscription' && $object->datefin > dol_now()) - { - $langs->load("members"); - print '
'.$langs->trans("MembershipPaid", dol_print_date($object->datefin, 'day')).'
'; - print '
'.$langs->trans("PaymentWillBeRecordedForNextPeriod").'
'; - } + // Membership can be paid and we still allow to make renewal + if ($source == 'membersubscription' && $object->datefin > dol_now()) + { + $langs->load("members"); + print '
'.$langs->trans("MembershipPaid", dol_print_date($object->datefin, 'day')).'
'; + print '
'.$langs->trans("PaymentWillBeRecordedForNextPeriod").'
'; + } // 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 ' '; - print '
'; - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { - print '
'; - } + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + { + print '
'; + } - print '
'; - print ''; + print '
'; + print ''; - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { - print '
'; - } + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + { + print '
'; + } - print '
+ print '
'; - print ' + print '
'; - print '
'; - print ''; - print ''; + print '
'; + print ''; + print ''; - print '
'; + print ''; + print ''; //} if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { - if (empty($paymentintent)) - { - print '
'.$langs->trans("Error").'
'; - } else { - print ''; - //$_SESSION["paymentintent_id"] = $paymentintent->id; - } + if (empty($paymentintent)) + { + print '
'.$langs->trans("Error").'
'; + } else { + print ''; + //$_SESSION["paymentintent_id"] = $paymentintent->id; + } } print ''."\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 ''; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; - // Code to ask the credit card. This use the default "API version". No way to force API version when using JS code. - print ''; + print ''; } } // This hook is used to show the embedded form to make payments with external payment modules (ie Payzen, ...) diff --git a/htdocs/public/recruitment/index.php b/htdocs/public/recruitment/index.php index a5be30aab49..504ecadfc71 100644 --- a/htdocs/public/recruitment/index.php +++ b/htdocs/public/recruitment/index.php @@ -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'); diff --git a/htdocs/public/ticket/create_ticket.php b/htdocs/public/ticket/create_ticket.php index 91ce8993bef..bd7b5416efb 100644 --- a/htdocs/public/ticket/create_ticket.php +++ b/htdocs/public/ticket/create_ticket.php @@ -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')) { diff --git a/htdocs/recruitment/class/recruitmentjobposition.class.php b/htdocs/recruitment/class/recruitmentjobposition.class.php index 6e27164ba23..ffe2a1373e8 100644 --- a/htdocs/recruitment/class/recruitmentjobposition.class.php +++ b/htdocs/recruitment/class/recruitmentjobposition.class.php @@ -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; diff --git a/htdocs/resource/class/dolresource.class.php b/htdocs/resource/class/dolresource.class.php index d392375fdd0..ef4252f41df 100644 --- a/htdocs/resource/class/dolresource.class.php +++ b/htdocs/resource/class/dolresource.class.php @@ -52,8 +52,8 @@ class Dolresource extends CommonObject public $mandatory; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_create; public $type_label; @@ -63,75 +63,75 @@ class Dolresource extends CommonObject public $oldcopy; - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Create object into database - * - * @param User $user User that creates - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs, $hookmanager; - $error = 0; + /** + * Create object into database + * + * @param User $user User that creates + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs, $hookmanager; + $error = 0; - // Clean parameters + // Clean parameters - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->description)) $this->description = trim($this->description); - if (!is_numeric($this->country_id)) $this->country_id = 0; - if (isset($this->fk_code_type_resource)) $this->fk_code_type_resource = trim($this->fk_code_type_resource); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); + if (isset($this->ref)) $this->ref = trim($this->ref); + if (isset($this->description)) $this->description = trim($this->description); + if (!is_numeric($this->country_id)) $this->country_id = 0; + if (isset($this->fk_code_type_resource)) $this->fk_code_type_resource = trim($this->fk_code_type_resource); + if (isset($this->note_public)) $this->note_public = trim($this->note_public); + if (isset($this->note_private)) $this->note_private = trim($this->note_private); - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."("; - $sql .= "entity,"; - $sql .= "ref,"; - $sql .= "description,"; - $sql .= "fk_country,"; - $sql .= "fk_code_type_resource,"; - $sql .= "note_public,"; - $sql .= "note_private"; - $sql .= ") VALUES ("; - $sql .= $conf->entity.", "; - $sql .= " ".(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").","; - $sql .= " ".(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").","; - $sql .= " ".($this->country_id > 0 ? $this->country_id : 'null').","; - $sql .= " ".(!isset($this->fk_code_type_resource) ? 'NULL' : "'".$this->db->escape($this->fk_code_type_resource)."'").","; - $sql .= " ".(!isset($this->note_public) ? 'NULL' : "'".$this->db->escape($this->note_public)."'").","; - $sql .= " ".(!isset($this->note_private) ? 'NULL' : "'".$this->db->escape($this->note_private)."'"); - $sql .= ")"; + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."("; + $sql .= "entity,"; + $sql .= "ref,"; + $sql .= "description,"; + $sql .= "fk_country,"; + $sql .= "fk_code_type_resource,"; + $sql .= "note_public,"; + $sql .= "note_private"; + $sql .= ") VALUES ("; + $sql .= $conf->entity.", "; + $sql .= " ".(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").","; + $sql .= " ".(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").","; + $sql .= " ".($this->country_id > 0 ? $this->country_id : 'null').","; + $sql .= " ".(!isset($this->fk_code_type_resource) ? 'NULL' : "'".$this->db->escape($this->fk_code_type_resource)."'").","; + $sql .= " ".(!isset($this->note_public) ? 'NULL' : "'".$this->db->escape($this->note_public)."'").","; + $sql .= " ".(!isset($this->note_private) ? 'NULL' : "'".$this->db->escape($this->note_private)."'"); + $sql .= ")"; - $this->db->begin(); + $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); - } + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - } + if (!$error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + } - if (!$error) - { - $action = 'create'; + if (!$error) + { + $action = 'create'; - // Actions on extra fields + // Actions on extra fields if (!$error) { $result = $this->insertExtraFields(); @@ -139,100 +139,100 @@ class Dolresource extends CommonObject { $error++; } - } - } + } + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('RESOURCE_CREATE', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('RESOURCE_CREATE', $user); + if ($result < 0) $error++; + // End call triggers + } - // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else { - $this->db->commit(); - return $this->id; - } - } + // Commit or rollback + if ($error) + { + foreach ($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return $this->id; + } + } - /** - * Load object in memory from database - * - * @param int $id Id of object - * @param string $ref Ref of object - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '') - { - global $langs; - $sql = "SELECT"; - $sql .= " t.rowid,"; - $sql .= " t.entity,"; - $sql .= " t.ref,"; - $sql .= " t.description,"; + /** + * Load object in memory from database + * + * @param int $id Id of object + * @param string $ref Ref of object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '') + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.entity,"; + $sql .= " t.ref,"; + $sql .= " t.description,"; $sql .= " t.fk_country,"; - $sql .= " t.fk_code_type_resource,"; - $sql .= " t.note_public,"; - $sql .= " t.note_private,"; - $sql .= " t.tms,"; - $sql .= " ty.label as type_label"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; - if ($id) $sql .= " WHERE t.rowid = ".$this->db->escape($id); - else $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'"; + $sql .= " t.fk_code_type_resource,"; + $sql .= " t.note_public,"; + $sql .= " t.note_private,"; + $sql .= " t.tms,"; + $sql .= " ty.label as type_label"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; + if ($id) $sql .= " WHERE t.rowid = ".$this->db->escape($id); + else $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'"; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->entity = $obj->entity; - $this->ref = $obj->ref; - $this->description = $obj->description; - $this->country_id = $obj->fk_country; - $this->fk_code_type_resource = $obj->fk_code_type_resource; - $this->note_public = $obj->note_public; - $this->note_private = $obj->note_private; - $this->type_label = $obj->type_label; + $this->id = $obj->rowid; + $this->entity = $obj->entity; + $this->ref = $obj->ref; + $this->description = $obj->description; + $this->country_id = $obj->fk_country; + $this->fk_code_type_resource = $obj->fk_code_type_resource; + $this->note_public = $obj->note_public; + $this->note_private = $obj->note_private; + $this->type_label = $obj->type_label; - // Retrieve all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); - } - $this->db->free($resql); + // Retrieve all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); + } + $this->db->free($resql); - return $this->id; - } else { - $this->error = "Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); - return -1; - } - } + return $this->id; + } else { + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); + return -1; + } + } - /** - * Update object into database - * - * @param User $user User that modifies - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user = null, $notrigger = 0) + /** + * Update object into database + * + * @param User $user User that modifies + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) { global $conf, $langs, $hookmanager; $error = 0; @@ -241,7 +241,7 @@ class Dolresource extends CommonObject if (isset($this->ref)) $this->ref = trim($this->ref); if (isset($this->fk_code_type_resource)) $this->fk_code_type_resource = trim($this->fk_code_type_resource); if (isset($this->description)) $this->description = trim($this->description); - if (!is_numeric($this->country_id)) $this->country_id = 0; + if (!is_numeric($this->country_id)) $this->country_id = 0; if (empty($this->oldcopy)) { @@ -327,19 +327,19 @@ class Dolresource extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load object in memory from database - * - * @param int $id id object - * @return int <0 if KO, >0 if OK - */ - public function fetch_element_resource($id) - { - // phpcs:enable - global $langs; - $sql = "SELECT"; - $sql .= " t.rowid,"; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load object in memory from database + * + * @param int $id id object + * @return int <0 if KO, >0 if OK + */ + public function fetch_element_resource($id) + { + // phpcs:enable + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; $sql .= " t.resource_id,"; $sql .= " t.resource_type,"; $sql .= " t.element_id,"; @@ -349,24 +349,24 @@ class Dolresource extends CommonObject $sql .= " t.fk_user_create,"; $sql .= " t.tms"; $sql .= " FROM ".MAIN_DB_PREFIX."element_resources as t"; - $sql .= " WHERE t.rowid = ".$this->db->escape($id); + $sql .= " WHERE t.rowid = ".$this->db->escape($id); - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->resource_id = $obj->resource_id; - $this->resource_type = $obj->resource_type; - $this->element_id = $obj->element_id; - $this->element_type = $obj->element_type; - $this->busy = $obj->busy; - $this->mandatory = $obj->mandatory; - $this->fk_user_create = $obj->fk_user_create; + $this->id = $obj->rowid; + $this->resource_id = $obj->resource_id; + $this->resource_type = $obj->resource_type; + $this->element_id = $obj->element_id; + $this->element_type = $obj->element_type; + $this->busy = $obj->busy; + $this->mandatory = $obj->mandatory; + $this->fk_user_create = $obj->fk_user_create; if ($obj->resource_id && $obj->resource_type) { $this->objresource = fetchObjectByElement($obj->resource_id, $obj->resource_type); @@ -374,27 +374,27 @@ class Dolresource extends CommonObject if ($obj->element_id && $obj->element_type) { $this->objelement = fetchObjectByElement($obj->element_id, $obj->element_type); } - } - $this->db->free($resql); + } + $this->db->free($resql); - return $this->id; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } + return $this->id; + } else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } - /** - * Delete a resource object - * - * @param int $rowid Id of resource line to delete - * @param int $notrigger Disable all triggers - * @return int >0 if OK, <0 if KO - */ - public function delete($rowid, $notrigger = 0) + /** + * Delete a resource object + * + * @param int $rowid Id of resource line to delete + * @param int $notrigger Disable all triggers + * @return int >0 if OK, <0 if KO + */ + public function delete($rowid, $notrigger = 0) { global $user, $langs, $conf; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error = 0; @@ -467,108 +467,108 @@ class Dolresource extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load resource objects into $this->lines - * - * @param string $sortorder sort order - * @param string $sortfield sort field - * @param int $limit limit page - * @param int $offset page - * @param array $filter filter output - * @return int <0 if KO, >0 if OK - */ - public function fetch_all($sortorder, $sortfield, $limit, $offset, $filter = '') - { - // phpcs:enable - global $conf; - - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - - $sql = "SELECT "; - $sql .= " t.rowid,"; - $sql .= " t.entity,"; - $sql .= " t.ref,"; - $sql .= " t.description,"; - $sql .= " t.fk_code_type_resource,"; - $sql .= " t.tms,"; - // Add fields from extrafields - if (!empty($extrafields->attributes[$this->table_element]['label'])) - foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); - $sql .= " ty.label as type_label"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$this->table_element."_extrafields as ef ON ef.fk_object=t.rowid"; - $sql .= " WHERE t.entity IN (".getEntity('resource').")"; - // Manage filter - if (!empty($filter)) { - foreach ($filter as $key => $value) { - if (strpos($key, 'date')) { - $sql .= ' AND '.$key.' = \''.$this->db->idate($value).'\''; - } elseif (strpos($key, 'ef.') !== false) { - $sql .= $value; - } else { - $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; - } - } - } - $sql .= $this->db->order($sortfield, $sortorder); - $this->num_all = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $this->db->query($sql); - $this->num_all = $this->db->num_rows($result); - } - if ($limit) $sql .= $this->db->plimit($limit, $offset); - dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); - - $this->lines = array(); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - while ($obj = $this->db->fetch_object($resql)) - { - $line = new Dolresource($this->db); - $line->id = $obj->rowid; - $line->ref = $obj->ref; - $line->description = $obj->description; - $line->country_id = $obj->fk_country; - $line->fk_code_type_resource = $obj->fk_code_type_resource; - $line->type_label = $obj->type_label; - - // fetch optionals attributes and labels - - $line->fetch_optionals(); - - $this->lines[] = $line; - } - $this->db->free($resql); - } - return $num; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load all objects into $this->lines - * - * @param string $sortorder sort order + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load resource objects into $this->lines + * + * @param string $sortorder sort order * @param string $sortfield sort field * @param int $limit limit page * @param int $offset page * @param array $filter filter output * @return int <0 if KO, >0 if OK - */ - public function fetch_all_resources($sortorder, $sortfield, $limit, $offset, $filter = '') - { - // phpcs:enable + */ + public function fetch_all($sortorder, $sortfield, $limit, $offset, $filter = '') + { + // phpcs:enable + global $conf; + + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + + $sql = "SELECT "; + $sql .= " t.rowid,"; + $sql .= " t.entity,"; + $sql .= " t.ref,"; + $sql .= " t.description,"; + $sql .= " t.fk_code_type_resource,"; + $sql .= " t.tms,"; + // Add fields from extrafields + if (!empty($extrafields->attributes[$this->table_element]['label'])) + foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + $sql .= " ty.label as type_label"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$this->table_element."_extrafields as ef ON ef.fk_object=t.rowid"; + $sql .= " WHERE t.entity IN (".getEntity('resource').")"; + // Manage filter + if (!empty($filter)) { + foreach ($filter as $key => $value) { + if (strpos($key, 'date')) { + $sql .= ' AND '.$key.' = \''.$this->db->idate($value).'\''; + } elseif (strpos($key, 'ef.') !== false) { + $sql .= $value; + } else { + $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } + $sql .= $this->db->order($sortfield, $sortorder); + $this->num_all = 0; + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + { + $result = $this->db->query($sql); + $this->num_all = $this->db->num_rows($result); + } + if ($limit) $sql .= $this->db->plimit($limit, $offset); + dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); + + $this->lines = array(); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num) + { + while ($obj = $this->db->fetch_object($resql)) + { + $line = new Dolresource($this->db); + $line->id = $obj->rowid; + $line->ref = $obj->ref; + $line->description = $obj->description; + $line->country_id = $obj->fk_country; + $line->fk_code_type_resource = $obj->fk_code_type_resource; + $line->type_label = $obj->type_label; + + // fetch optionals attributes and labels + + $line->fetch_optionals(); + + $this->lines[] = $line; + } + $this->db->free($resql); + } + return $num; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load all objects into $this->lines + * + * @param string $sortorder sort order + * @param string $sortfield sort field + * @param int $limit limit page + * @param int $offset page + * @param array $filter filter output + * @return int <0 if KO, >0 if OK + */ + public function fetch_all_resources($sortorder, $sortfield, $limit, $offset, $filter = '') + { + // phpcs:enable global $conf; $sql = "SELECT "; $sql .= " t.rowid,"; @@ -593,7 +593,7 @@ class Dolresource extends CommonObject } } } - $sql .= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) $sql .= $this->db->plimit($limit + 1, $offset); dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); @@ -619,7 +619,7 @@ class Dolresource extends CommonObject $line->objresource = fetchObjectByElement($obj->resource_id, $obj->resource_type); if ($obj->element_id && $obj->element_type) $line->objelement = fetchObjectByElement($obj->element_id, $obj->element_type); - $this->lines[] = $line; + $this->lines[] = $line; } $this->db->free($resql); } @@ -628,119 +628,119 @@ class Dolresource extends CommonObject $this->error = $this->db->lasterror(); return -1; } - } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load all objects into $this->lines - * - * @param string $sortorder sort order - * @param string $sortfield sort field - * @param int $limit limit page - * @param int $offset page - * @param array $filter filter output - * @return int <0 if KO, >0 if OK - */ - public function fetch_all_used($sortorder, $sortfield, $limit, $offset = 1, $filter = '') - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load all objects into $this->lines + * + * @param string $sortorder sort order + * @param string $sortfield sort field + * @param int $limit limit page + * @param int $offset page + * @param array $filter filter output + * @return int <0 if KO, >0 if OK + */ + public function fetch_all_used($sortorder, $sortfield, $limit, $offset = 1, $filter = '') + { + // phpcs:enable + global $conf; - if (!$sortorder) $sortorder = "ASC"; - if (!$sortfield) $sortfield = "t.rowid"; + if (!$sortorder) $sortorder = "ASC"; + if (!$sortfield) $sortfield = "t.rowid"; - $sql = "SELECT "; - $sql .= " t.rowid,"; - $sql .= " t.resource_id,"; - $sql .= " t.resource_type,"; - $sql .= " t.element_id,"; - $sql .= " t.element_type,"; - $sql .= " t.busy,"; - $sql .= " t.mandatory,"; - $sql .= " t.fk_user_create,"; - $sql .= " t.tms"; - $sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources as t '; - $sql .= " WHERE t.entity IN (".getEntity('resource').")"; + $sql = "SELECT "; + $sql .= " t.rowid,"; + $sql .= " t.resource_id,"; + $sql .= " t.resource_type,"; + $sql .= " t.element_id,"; + $sql .= " t.element_type,"; + $sql .= " t.busy,"; + $sql .= " t.mandatory,"; + $sql .= " t.fk_user_create,"; + $sql .= " t.tms"; + $sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources as t '; + $sql .= " WHERE t.entity IN (".getEntity('resource').")"; - //Manage filter - if (!empty($filter)) { - foreach ($filter as $key => $value) { - if (strpos($key, 'date')) { - $sql .= ' AND '.$key.' = \''.$this->db->idate($value).'\''; - } else { - $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; - } - } - } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) $sql .= $this->db->plimit($limit + 1, $offset); - dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); + //Manage filter + if (!empty($filter)) { + foreach ($filter as $key => $value) { + if (strpos($key, 'date')) { + $sql .= ' AND '.$key.' = \''.$this->db->idate($value).'\''; + } else { + $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) $sql .= $this->db->plimit($limit + 1, $offset); + dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - $this->lines = array(); - while ($obj = $this->db->fetch_object($resql)) - { - $line = new Dolresource($this->db); - $line->id = $obj->rowid; - $line->resource_id = $obj->resource_id; - $line->resource_type = $obj->resource_type; - $line->element_id = $obj->element_id; - $line->element_type = $obj->element_type; - $line->busy = $obj->busy; - $line->mandatory = $obj->mandatory; - $line->fk_user_create = $obj->fk_user_create; + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num) + { + $this->lines = array(); + while ($obj = $this->db->fetch_object($resql)) + { + $line = new Dolresource($this->db); + $line->id = $obj->rowid; + $line->resource_id = $obj->resource_id; + $line->resource_type = $obj->resource_type; + $line->element_id = $obj->element_id; + $line->element_type = $obj->element_type; + $line->busy = $obj->busy; + $line->mandatory = $obj->mandatory; + $line->fk_user_create = $obj->fk_user_create; - $this->lines[] = fetchObjectByElement($obj->resource_id, $obj->resource_type); - } - $this->db->free($resql); - } - return $num; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + $this->lines[] = fetchObjectByElement($obj->resource_id, $obj->resource_type); + } + $this->db->free($resql); + } + return $num; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Fetch all resources available, declared by modules - * Load available resource in array $this->available_resources - * - * @return int number of available resources declared by modules - * @deprecated, remplaced by hook getElementResources - * @see getElementResources() - */ - public function fetch_all_available() - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Fetch all resources available, declared by modules + * Load available resource in array $this->available_resources + * + * @return int number of available resources declared by modules + * @deprecated, remplaced by hook getElementResources + * @see getElementResources() + */ + public function fetch_all_available() + { + // phpcs:enable + global $conf; - if (!empty($conf->modules_parts['resources'])) - { - $this->available_resources = (array) $conf->modules_parts['resources']; + if (!empty($conf->modules_parts['resources'])) + { + $this->available_resources = (array) $conf->modules_parts['resources']; - return count($this->available_resources); - } - return 0; - } + return count($this->available_resources); + } + return 0; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update element resource into database - * - * @param User $user User that modifies - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update_element_resource($user = null, $notrigger = 0) - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update element resource into database + * + * @param User $user User that modifies + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update_element_resource($user = null, $notrigger = 0) + { + // phpcs:enable + global $conf, $langs; $error = 0; // Clean parameters @@ -751,8 +751,8 @@ class Dolresource extends CommonObject if (isset($this->busy)) $this->busy = trim($this->busy); if (isset($this->mandatory)) $this->mandatory = trim($this->mandatory); - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."element_resources SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."element_resources SET"; $sql .= " resource_id=".(isset($this->resource_id) ? "'".$this->db->escape($this->resource_id)."'" : "null").","; $sql .= " resource_type=".(isset($this->resource_type) ? "'".$this->db->escape($this->resource_type)."'" : "null").","; $sql .= " element_id=".(isset($this->element_id) ? $this->element_id : "null").","; @@ -761,32 +761,32 @@ class Dolresource extends CommonObject $sql .= " mandatory=".(isset($this->mandatory) ? $this->mandatory : "null").","; $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { if (!$notrigger) { - // Call trigger - $result = $this->call_trigger('RESOURCE_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } + // Call trigger + $result = $this->call_trigger('RESOURCE_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } } - // Commit or rollback + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; @@ -794,201 +794,201 @@ class Dolresource extends CommonObject $this->db->commit(); return 1; } - } + } - /** - * Return an array with resources linked to the element - * - * @param string $element Element - * @param int $element_id Id - * @param string $resource_type Type - * @return array Aray of resources - */ - public function getElementResources($element, $element_id, $resource_type = '') - { - $resources = array(); + /** + * Return an array with resources linked to the element + * + * @param string $element Element + * @param int $element_id Id + * @param string $resource_type Type + * @return array Aray of resources + */ + public function getElementResources($element, $element_id, $resource_type = '') + { + $resources = array(); - // Links beetween objects are stored in this table - $sql = 'SELECT rowid, resource_id, resource_type, busy, mandatory'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources'; - $sql .= " WHERE element_id=".$element_id." AND element_type='".$this->db->escape($element)."'"; - if ($resource_type) - $sql .= " AND resource_type LIKE '%".$this->db->escape($resource_type)."%'"; - $sql .= ' ORDER BY resource_type'; + // Links beetween objects are stored in this table + $sql = 'SELECT rowid, resource_id, resource_type, busy, mandatory'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources'; + $sql .= " WHERE element_id=".$element_id." AND element_type='".$this->db->escape($element)."'"; + if ($resource_type) + $sql .= " AND resource_type LIKE '%".$this->db->escape($resource_type)."%'"; + $sql .= ' ORDER BY resource_type'; - dol_syslog(get_class($this)."::getElementResources", LOG_DEBUG); + dol_syslog(get_class($this)."::getElementResources", LOG_DEBUG); - $resources = array(); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + $resources = array(); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $resources[$i] = array( - 'rowid' => $obj->rowid, - 'resource_id' => $obj->resource_id, - 'resource_type'=>$obj->resource_type, - 'busy'=>$obj->busy, - 'mandatory'=>$obj->mandatory - ); - $i++; - } - } + $resources[$i] = array( + 'rowid' => $obj->rowid, + 'resource_id' => $obj->resource_id, + 'resource_type'=>$obj->resource_type, + 'busy'=>$obj->busy, + 'mandatory'=>$obj->mandatory + ); + $i++; + } + } - return $resources; - } + return $resources; + } - /** - * Return an int number of resources linked to the element - * - * @param string $element Element type - * @param int $element_id Element id - * @return int Nb of resources loaded - */ - public function fetchElementResources($element, $element_id) - { - $resources = $this->getElementResources($element, $element_id); - $i = 0; - foreach ($resources as $nb => $resource) { - $this->lines[$i] = fetchObjectByElement($resource['resource_id'], $resource['resource_type']); - $i++; - } - return $i; - } + /** + * Return an int number of resources linked to the element + * + * @param string $element Element type + * @param int $element_id Element id + * @return int Nb of resources loaded + */ + public function fetchElementResources($element, $element_id) + { + $resources = $this->getElementResources($element, $element_id); + $i = 0; + foreach ($resources as $nb => $resource) { + $this->lines[$i] = fetchObjectByElement($resource['resource_id'], $resource['resource_type']); + $i++; + } + return $i; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load in cache resource type code (setup in dictionary) - * - * @return int Number of lines loaded, 0 if already loaded, <0 if KO - */ - public function load_cache_code_type_resource() - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load in cache resource type code (setup in dictionary) + * + * @return int Number of lines loaded, 0 if already loaded, <0 if KO + */ + public function load_cache_code_type_resource() + { + // phpcs:enable + global $langs; - if (is_array($this->cache_code_type_resource) && count($this->cache_code_type_resource)) return 0; // Cache deja charge + if (is_array($this->cache_code_type_resource) && count($this->cache_code_type_resource)) return 0; // Cache deja charge - $sql = "SELECT rowid, code, label, active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_resource"; - $sql .= " WHERE active > 0"; - $sql .= " ORDER BY rowid"; - dol_syslog(get_class($this)."::load_cache_code_type_resource", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label = ($langs->trans("ResourceTypeShort".$obj->code) != ("ResourceTypeShort".$obj->code) ? $langs->trans("ResourceTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : '')); - $this->cache_code_type_resource[$obj->rowid]['code'] = $obj->code; - $this->cache_code_type_resource[$obj->rowid]['label'] = $label; - $this->cache_code_type_resource[$obj->rowid]['active'] = $obj->active; - $i++; - } - return $num; - } else { - dol_print_error($this->db); - return -1; - } - } + $sql = "SELECT rowid, code, label, active"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_resource"; + $sql .= " WHERE active > 0"; + $sql .= " ORDER BY rowid"; + dol_syslog(get_class($this)."::load_cache_code_type_resource", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label = ($langs->trans("ResourceTypeShort".$obj->code) != ("ResourceTypeShort".$obj->code) ? $langs->trans("ResourceTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : '')); + $this->cache_code_type_resource[$obj->rowid]['code'] = $obj->code; + $this->cache_code_type_resource[$obj->rowid]['label'] = $label; + $this->cache_code_type_resource[$obj->rowid]['active'] = $obj->active; + $i++; + } + return $num; + } else { + dol_print_error($this->db); + return -1; + } + } - /** - * Return clicable link of object (with eventually picto) - * - * @param int $withpicto Add picto into link - * @param string $option Where point the link ('compta', 'expedition', 'document', ...) - * @param string $get_params Parametres added to url - * @param int $notooltip 1=Disable tooltip - * @param string $morecss Add more css on link - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) - { - global $conf, $langs; + /** + * Return clicable link of object (with eventually picto) + * + * @param int $withpicto Add picto into link + * @param string $option Where point the link ('compta', 'expedition', 'document', ...) + * @param string $get_params Parametres added to url + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $conf, $langs; - $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("Resource").''; - $label .= '
'; - $label .= ''.$langs->trans('Ref').': '.$this->ref; - /*if (isset($this->status)) { + $result = ''; + $label = img_picto('', $this->picto).' '.$langs->trans("Resource").''; + $label .= '
'; + $label .= ''.$langs->trans('Ref').': '.$this->ref; + /*if (isset($this->status)) { $label.= '
' . $langs->trans("Status").": ".$this->getLibStatut(5); }*/ - if (isset($this->type_label)) { - $label .= '
'.$langs->trans("ResourceType").": ".$this->type_label; - } + if (isset($this->type_label)) { + $label .= '
'.$langs->trans("ResourceType").": ".$this->type_label; + } - $url = DOL_URL_ROOT.'/resource/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/resource/card.php?id='.$this->id; - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; - } + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; + if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + } - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowMyObject"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); - $linkstart = ''; - $linkend = ''; - /*$linkstart = ''; + $linkstart = ''; + $linkend = ''; + /*$linkstart = ''; $linkend = '';*/ - $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; - $result .= $linkend; + $result .= $linkstart; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= $this->ref; + $result .= $linkend; - return $result; - } + return $result; + } - /** - * Retourne le libelle du status d'un user (actif, inactif) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Label of status - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->status, $mode); - } + /** + * Retourne le libelle du status d'un user (actif, inactif) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Label of status + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return the status - * - * @param int $status Id status - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto - * @return string Label of status - */ - public static function LibStatut($status, $mode = 0) - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto + * @return string Label of status + */ + public static function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; - return ''; - } + return ''; + } } diff --git a/htdocs/salaries/class/paymentsalary.class.php b/htdocs/salaries/class/paymentsalary.class.php index 1d46981d8d3..4f5209eb123 100644 --- a/htdocs/salaries/class/paymentsalary.class.php +++ b/htdocs/salaries/class/paymentsalary.class.php @@ -31,668 +31,668 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; */ class PaymentSalary extends CommonObject { - /** - * @var string ID to identify managed object - */ - public $element = 'payment_salary'; - - /** - * @var string Name of table without prefix where object is stored - */ - public $table_element = 'payment_salary'; - - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'payment'; - - public $tms; - - /** - * @var int User ID - */ - public $fk_user; - - public $datep; - public $datev; - public $amount; - - /** - * @var int ID - */ - public $fk_project; - - public $type_payment; - public $num_payment; - - /** - * @var string salary payments label - */ - public $label; - - public $datesp; - public $dateep; - - /** - * @var int ID - */ - public $fk_bank; - - /** - * @var int ID - */ - public $fk_user_author; - - /** - * @var int ID - */ - public $fk_user_modif; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - $this->element = 'payment_salary'; - $this->table_element = 'payment_salary'; - } - - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=no, 1=yes (no update trigger) - * @return int <0 if KO, >0 if OK - */ - public function update($user = null, $notrigger = 0) - { - global $conf, $langs; - - $error = 0; - - // Clean parameters - $this->amount = trim($this->amount); - $this->label = trim($this->label); - $this->note = trim($this->note); - - // Check parameters - if (empty($this->fk_user) || $this->fk_user < 0) - { - $this->error = 'ErrorBadParameter'; - return -1; - } - - $this->db->begin(); - - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."payment_salary SET"; - - $sql .= " tms='".$this->db->idate($this->tms)."',"; - $sql .= " fk_user=".$this->fk_user.","; - $sql .= " datep='".$this->db->idate($this->datep)."',"; - $sql .= " datev='".$this->db->idate($this->datev)."',"; - $sql .= " amount=".price2num($this->amount).","; - $sql .= " fk_projet=".((int) $this->fk_project).","; - $sql .= " fk_typepayment=".$this->fk_typepayment."',"; - $sql .= " num_payment='".$this->db->escape($this->num_payment)."',"; - $sql .= " label='".$this->db->escape($this->label)."',"; - $sql .= " datesp='".$this->db->idate($this->datesp)."',"; - $sql .= " dateep='".$this->db->idate($this->dateep)."',"; - $sql .= " note='".$this->db->escape($this->note)."',"; - $sql .= " fk_bank=".($this->fk_bank > 0 ? (int) $this->fk_bank : "null").","; - $sql .= " fk_user_author=".((int) $this->fk_user_author).","; - $sql .= " fk_user_modif=".($this->fk_user_modif > 0 ? (int) $this->fk_user_modif : 'null'); - - $sql .= " WHERE rowid=".$this->id; - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - - // Update extrafield - if (!$error) - { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('PAYMENT_SALARY_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } - - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } - - - /** - * Load object in memory from database - * - * @param int $id id object - * @param User $user User that load - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $user = null) - { - global $langs; - $sql = "SELECT"; - $sql .= " s.rowid,"; - - $sql .= " s.tms,"; - $sql .= " s.fk_user,"; - $sql .= " s.datep,"; - $sql .= " s.datev,"; - $sql .= " s.amount,"; - $sql .= " s.fk_projet as fk_project,"; - $sql .= " s.fk_typepayment,"; - $sql .= " s.num_payment,"; - $sql .= " s.label,"; - $sql .= " s.datesp,"; - $sql .= " s.dateep,"; - $sql .= " s.note,"; - $sql .= " s.fk_bank,"; - $sql .= " s.fk_user_author,"; - $sql .= " s.fk_user_modif,"; - $sql .= " b.fk_account,"; - $sql .= " b.fk_type,"; - $sql .= " b.rappro"; - - $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; - $sql .= " WHERE s.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->ref = $obj->rowid; - $this->tms = $this->db->jdate($obj->tms); - $this->fk_user = $obj->fk_user; - $this->datep = $this->db->jdate($obj->datep); - $this->datev = $this->db->jdate($obj->datev); - $this->amount = $obj->amount; - $this->fk_project = $obj->fk_project; - $this->type_payement = $obj->fk_typepayment; - $this->num_payment = $obj->num_payment; - $this->label = $obj->label; - $this->datesp = $this->db->jdate($obj->datesp); - $this->dateep = $this->db->jdate($obj->dateep); - $this->note = $obj->note; - $this->fk_bank = $obj->fk_bank; - $this->fk_user_author = $obj->fk_user_author; - $this->fk_user_modif = $obj->fk_user_modif; - $this->fk_account = $obj->fk_account; - $this->fk_type = $obj->fk_type; - $this->rappro = $obj->rappro; - - // Retrieve all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); - } - $this->db->free($resql); - - return 1; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } - - - /** - * Delete object in database - * - * @param User $user User that delete - * @return int <0 if KO, >0 if OK - */ - public function delete($user) - { - global $conf, $langs; - - $error = 0; - - // Call trigger - $result = $this->call_trigger('PAYMENT_SALARY_DELETE', $user); - if ($result < 0) return -1; - // End call triggers - - // Delete donation - if (!$error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary_extrafields"; - $sql .= " WHERE fk_object=".$this->id; - - $resql = $this->db->query($sql); - if (!$resql) - { - $this->errors[] = $this->db->lasterror(); - $error++; - } - } - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary"; - $sql .= " WHERE rowid=".$this->id; - - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - - return 1; - } - - - /** - * 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() - { - $this->id = 0; - - $this->tms = ''; - $this->fk_user = ''; - $this->datep = ''; - $this->datev = ''; - $this->amount = ''; - $this->label = ''; - $this->datesp = ''; - $this->dateep = ''; - $this->note = ''; - $this->fk_bank = ''; - $this->fk_user_author = ''; - $this->fk_user_modif = ''; - } - - /** - * Create in database - * - * @param User $user User that create - * @return int <0 if KO, >0 if OK - */ - public function create($user) - { - global $conf, $langs; - - $error = 0; - $now = dol_now(); - - // Clean parameters - $this->amount = price2num(trim($this->amount)); - $this->label = trim($this->label); - $this->note = trim($this->note); - $this->fk_bank = trim($this->fk_bank); - $this->fk_user_author = trim($this->fk_user_author); - $this->fk_user_modif = trim($this->fk_user_modif); - - // Check parameters - if (!$this->label) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); - return -3; - } - if ($this->fk_user < 0 || $this->fk_user == '') - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Employee")); - return -4; - } - if ($this->amount < 0 || $this->amount == '') - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); - return -5; - } - if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); - return -6; - } - if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); - return -7; - } - - $this->db->begin(); - - // Insert into llx_payment_salary - $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_salary (fk_user"; - $sql .= ", datep"; - $sql .= ", datev"; - $sql .= ", amount"; - $sql .= ", fk_projet"; - $sql .= ", salary"; - $sql .= ", fk_typepayment"; - $sql .= ", num_payment"; - if ($this->note) $sql .= ", note"; - $sql .= ", label"; - $sql .= ", datesp"; - $sql .= ", dateep"; - $sql .= ", fk_user_author"; - $sql .= ", datec"; - $sql .= ", fk_bank"; - $sql .= ", entity"; - $sql .= ") "; - $sql .= " VALUES ("; - $sql .= "'".$this->db->escape($this->fk_user)."'"; - $sql .= ", '".$this->db->idate($this->datep)."'"; - $sql .= ", '".$this->db->idate($this->datev)."'"; - $sql .= ", ".$this->amount; - $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : 0); - $sql .= ", ".($this->salary > 0 ? $this->salary : "null"); - $sql .= ", ".$this->db->escape($this->type_payment); - $sql .= ", '".$this->db->escape($this->num_payment)."'"; - if ($this->note) $sql .= ", '".$this->db->escape($this->note)."'"; - $sql .= ", '".$this->db->escape($this->label)."'"; - $sql .= ", '".$this->db->idate($this->datesp)."'"; - $sql .= ", '".$this->db->idate($this->dateep)."'"; - $sql .= ", '".$this->db->escape($user->id)."'"; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", NULL"; - $sql .= ", ".$conf->entity; - $sql .= ")"; - - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_salary"); - - if ($this->id > 0) - { - if (!empty($conf->banque->enabled) && !empty($this->amount)) - { - // Insert into llx_bank - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - - $acc = new Account($this->db); - $result = $acc->fetch($this->accountid); - if ($result <= 0) dol_print_error($this->db); - - // Update extrafield - if (!$error) { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - - // Insert payment into llx_bank - // Add link 'payment_salary' in bank_url between payment and bank transaction - $bank_line_id = $acc->addline( - $this->datep, - $this->type_payment, - $this->label, - -abs($this->amount), - $this->num_payment, - '', - $user, - '', - '', - '', - $this->datev - ); - - // Update fk_bank into llx_paiement. - // So we know the payment which has generate the banking ecriture - if ($bank_line_id > 0) - { - $this->update_fk_bank($bank_line_id); - } else { - $this->error = $acc->error; - $error++; - } - - if (!$error) - { - // Add link 'payment_salary' in bank_url between payment and bank transaction - $url = DOL_URL_ROOT.'/salaries/card.php?id='; - - $result = $acc->add_url_line($bank_line_id, $this->id, $url, "(SalaryPayment)", "payment_salary"); - if ($result <= 0) - { - $this->error = $acc->error; - $error++; - } - } - - $fuser = new User($this->db); - $fuser->fetch($this->fk_user); - - // Add link 'user' in bank_url between operation and bank transaction - $result = $acc->add_url_line( - $bank_line_id, - $this->fk_user, - DOL_URL_ROOT.'/user/card.php?id=', - $fuser->getFullName($langs), - // $langs->trans("SalaryPayment").' '.$fuser->getFullName($langs).' '.dol_print_date($this->datesp,'dayrfc').' '.dol_print_date($this->dateep,'dayrfc'), - 'user' - ); - - if ($result <= 0) - { - $this->error = $acc->error; - $error++; - } - } - - // Call trigger - $result = $this->call_trigger('PAYMENT_SALARY_CREATE', $user); - if ($result < 0) $error++; - // End call triggers - } else $error++; - - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -2; - } - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update link between payment salary and line generate into llx_bank - * - * @param int $id_bank Id bank account - * @return int <0 if KO, >0 if OK - */ - public function update_fk_bank($id_bank) - { - // phpcs:enable - $sql = 'UPDATE '.MAIN_DB_PREFIX.'payment_salary SET fk_bank = '.$id_bank; - $sql .= ' WHERE rowid = '.$this->id; - $result = $this->db->query($sql); - if ($result) - { - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - - /** - * Send name clicable (with possibly the picto) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option link option - * @param int $notooltip 1=Disable tooltip - * @param string $morecss Add more css on link - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string Chaine with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) - { - global $db, $conf, $langs, $hookmanager; - global $dolibarr_main_authentication, $dolibarr_main_demo; - global $menumanager; - - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - - $result = ''; - - $label = ''.$langs->trans("ShowSalaryPayment").''; - $label .= '
'; - $label .= ''.$langs->trans('Ref').': '.$this->ref; - - $url = DOL_URL_ROOT.'/salaries/card.php?id='.$this->id; - - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; - } - - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowMyObject"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* + /** + * @var string ID to identify managed object + */ + public $element = 'payment_salary'; + + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'payment_salary'; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'payment'; + + public $tms; + + /** + * @var int User ID + */ + public $fk_user; + + public $datep; + public $datev; + public $amount; + + /** + * @var int ID + */ + public $fk_project; + + public $type_payment; + public $num_payment; + + /** + * @var string salary payments label + */ + public $label; + + public $datesp; + public $dateep; + + /** + * @var int ID + */ + public $fk_bank; + + /** + * @var int ID + */ + public $fk_user_author; + + /** + * @var int ID + */ + public $fk_user_modif; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + $this->element = 'payment_salary'; + $this->table_element = 'payment_salary'; + } + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=no, 1=yes (no update trigger) + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) + { + global $conf, $langs; + + $error = 0; + + // Clean parameters + $this->amount = trim($this->amount); + $this->label = trim($this->label); + $this->note = trim($this->note); + + // Check parameters + if (empty($this->fk_user) || $this->fk_user < 0) + { + $this->error = 'ErrorBadParameter'; + return -1; + } + + $this->db->begin(); + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."payment_salary SET"; + + $sql .= " tms='".$this->db->idate($this->tms)."',"; + $sql .= " fk_user=".$this->fk_user.","; + $sql .= " datep='".$this->db->idate($this->datep)."',"; + $sql .= " datev='".$this->db->idate($this->datev)."',"; + $sql .= " amount=".price2num($this->amount).","; + $sql .= " fk_projet=".((int) $this->fk_project).","; + $sql .= " fk_typepayment=".$this->fk_typepayment."',"; + $sql .= " num_payment='".$this->db->escape($this->num_payment)."',"; + $sql .= " label='".$this->db->escape($this->label)."',"; + $sql .= " datesp='".$this->db->idate($this->datesp)."',"; + $sql .= " dateep='".$this->db->idate($this->dateep)."',"; + $sql .= " note='".$this->db->escape($this->note)."',"; + $sql .= " fk_bank=".($this->fk_bank > 0 ? (int) $this->fk_bank : "null").","; + $sql .= " fk_user_author=".((int) $this->fk_user_author).","; + $sql .= " fk_user_modif=".($this->fk_user_modif > 0 ? (int) $this->fk_user_modif : 'null'); + + $sql .= " WHERE rowid=".$this->id; + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + + // Update extrafield + if (!$error) + { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('PAYMENT_SALARY_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } + + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Load object in memory from database + * + * @param int $id id object + * @param User $user User that load + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $user = null) + { + global $langs; + $sql = "SELECT"; + $sql .= " s.rowid,"; + + $sql .= " s.tms,"; + $sql .= " s.fk_user,"; + $sql .= " s.datep,"; + $sql .= " s.datev,"; + $sql .= " s.amount,"; + $sql .= " s.fk_projet as fk_project,"; + $sql .= " s.fk_typepayment,"; + $sql .= " s.num_payment,"; + $sql .= " s.label,"; + $sql .= " s.datesp,"; + $sql .= " s.dateep,"; + $sql .= " s.note,"; + $sql .= " s.fk_bank,"; + $sql .= " s.fk_user_author,"; + $sql .= " s.fk_user_modif,"; + $sql .= " b.fk_account,"; + $sql .= " b.fk_type,"; + $sql .= " b.rappro"; + + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; + $sql .= " WHERE s.rowid = ".$id; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + $this->tms = $this->db->jdate($obj->tms); + $this->fk_user = $obj->fk_user; + $this->datep = $this->db->jdate($obj->datep); + $this->datev = $this->db->jdate($obj->datev); + $this->amount = $obj->amount; + $this->fk_project = $obj->fk_project; + $this->type_payement = $obj->fk_typepayment; + $this->num_payment = $obj->num_payment; + $this->label = $obj->label; + $this->datesp = $this->db->jdate($obj->datesp); + $this->dateep = $this->db->jdate($obj->dateep); + $this->note = $obj->note; + $this->fk_bank = $obj->fk_bank; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_modif = $obj->fk_user_modif; + $this->fk_account = $obj->fk_account; + $this->fk_type = $obj->fk_type; + $this->rappro = $obj->rappro; + + // Retrieve all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Delete object in database + * + * @param User $user User that delete + * @return int <0 if KO, >0 if OK + */ + public function delete($user) + { + global $conf, $langs; + + $error = 0; + + // Call trigger + $result = $this->call_trigger('PAYMENT_SALARY_DELETE', $user); + if ($result < 0) return -1; + // End call triggers + + // Delete donation + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary_extrafields"; + $sql .= " WHERE fk_object=".$this->id; + + $resql = $this->db->query($sql); + if (!$resql) + { + $this->errors[] = $this->db->lasterror(); + $error++; + } + } + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary"; + $sql .= " WHERE rowid=".$this->id; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + + return 1; + } + + + /** + * 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() + { + $this->id = 0; + + $this->tms = ''; + $this->fk_user = ''; + $this->datep = ''; + $this->datev = ''; + $this->amount = ''; + $this->label = ''; + $this->datesp = ''; + $this->dateep = ''; + $this->note = ''; + $this->fk_bank = ''; + $this->fk_user_author = ''; + $this->fk_user_modif = ''; + } + + /** + * Create in database + * + * @param User $user User that create + * @return int <0 if KO, >0 if OK + */ + public function create($user) + { + global $conf, $langs; + + $error = 0; + $now = dol_now(); + + // Clean parameters + $this->amount = price2num(trim($this->amount)); + $this->label = trim($this->label); + $this->note = trim($this->note); + $this->fk_bank = trim($this->fk_bank); + $this->fk_user_author = trim($this->fk_user_author); + $this->fk_user_modif = trim($this->fk_user_modif); + + // Check parameters + if (!$this->label) + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); + return -3; + } + if ($this->fk_user < 0 || $this->fk_user == '') + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Employee")); + return -4; + } + if ($this->amount < 0 || $this->amount == '') + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); + return -5; + } + if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); + return -6; + } + if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); + return -7; + } + + $this->db->begin(); + + // Insert into llx_payment_salary + $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_salary (fk_user"; + $sql .= ", datep"; + $sql .= ", datev"; + $sql .= ", amount"; + $sql .= ", fk_projet"; + $sql .= ", salary"; + $sql .= ", fk_typepayment"; + $sql .= ", num_payment"; + if ($this->note) $sql .= ", note"; + $sql .= ", label"; + $sql .= ", datesp"; + $sql .= ", dateep"; + $sql .= ", fk_user_author"; + $sql .= ", datec"; + $sql .= ", fk_bank"; + $sql .= ", entity"; + $sql .= ") "; + $sql .= " VALUES ("; + $sql .= "'".$this->db->escape($this->fk_user)."'"; + $sql .= ", '".$this->db->idate($this->datep)."'"; + $sql .= ", '".$this->db->idate($this->datev)."'"; + $sql .= ", ".$this->amount; + $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : 0); + $sql .= ", ".($this->salary > 0 ? $this->salary : "null"); + $sql .= ", ".$this->db->escape($this->type_payment); + $sql .= ", '".$this->db->escape($this->num_payment)."'"; + if ($this->note) $sql .= ", '".$this->db->escape($this->note)."'"; + $sql .= ", '".$this->db->escape($this->label)."'"; + $sql .= ", '".$this->db->idate($this->datesp)."'"; + $sql .= ", '".$this->db->idate($this->dateep)."'"; + $sql .= ", '".$this->db->escape($user->id)."'"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", NULL"; + $sql .= ", ".$conf->entity; + $sql .= ")"; + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_salary"); + + if ($this->id > 0) + { + if (!empty($conf->banque->enabled) && !empty($this->amount)) + { + // Insert into llx_bank + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + + $acc = new Account($this->db); + $result = $acc->fetch($this->accountid); + if ($result <= 0) dol_print_error($this->db); + + // Update extrafield + if (!$error) { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + + // Insert payment into llx_bank + // Add link 'payment_salary' in bank_url between payment and bank transaction + $bank_line_id = $acc->addline( + $this->datep, + $this->type_payment, + $this->label, + -abs($this->amount), + $this->num_payment, + '', + $user, + '', + '', + '', + $this->datev + ); + + // Update fk_bank into llx_paiement. + // So we know the payment which has generate the banking ecriture + if ($bank_line_id > 0) + { + $this->update_fk_bank($bank_line_id); + } else { + $this->error = $acc->error; + $error++; + } + + if (!$error) + { + // Add link 'payment_salary' in bank_url between payment and bank transaction + $url = DOL_URL_ROOT.'/salaries/card.php?id='; + + $result = $acc->add_url_line($bank_line_id, $this->id, $url, "(SalaryPayment)", "payment_salary"); + if ($result <= 0) + { + $this->error = $acc->error; + $error++; + } + } + + $fuser = new User($this->db); + $fuser->fetch($this->fk_user); + + // Add link 'user' in bank_url between operation and bank transaction + $result = $acc->add_url_line( + $bank_line_id, + $this->fk_user, + DOL_URL_ROOT.'/user/card.php?id=', + $fuser->getFullName($langs), + // $langs->trans("SalaryPayment").' '.$fuser->getFullName($langs).' '.dol_print_date($this->datesp,'dayrfc').' '.dol_print_date($this->dateep,'dayrfc'), + 'user' + ); + + if ($result <= 0) + { + $this->error = $acc->error; + $error++; + } + } + + // Call trigger + $result = $this->call_trigger('PAYMENT_SALARY_CREATE', $user); + if ($result < 0) $error++; + // End call triggers + } else $error++; + + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -2; + } + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update link between payment salary and line generate into llx_bank + * + * @param int $id_bank Id bank account + * @return int <0 if KO, >0 if OK + */ + public function update_fk_bank($id_bank) + { + // phpcs:enable + $sql = 'UPDATE '.MAIN_DB_PREFIX.'payment_salary SET fk_bank = '.$id_bank; + $sql .= ' WHERE rowid = '.$this->id; + $result = $this->db->query($sql); + if ($result) + { + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + + /** + * Send name clicable (with possibly the picto) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param string $option link option + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $db, $conf, $langs, $hookmanager; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + + $result = ''; + + $label = ''.$langs->trans("ShowSalaryPayment").''; + $label .= '
'; + $label .= ''.$langs->trans('Ref').': '.$this->ref; + + $url = DOL_URL_ROOT.'/salaries/card.php?id='.$this->id; + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; + if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + } + + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + + /* $hookmanager->initHooks(array('myobjectdao')); $parameters=array('id'=>$this->id); $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if ($reshook > 0) $linkclose = $hookmanager->resPrint; */ - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); - $linkstart = ''; - $linkend = ''; + $linkstart = ''; + $linkend = ''; - $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; - $result .= $linkend; - //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + $result .= $linkstart; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= $this->ref; + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); - global $action, $hookmanager; - $hookmanager->initHooks(array('salarypayment')); - $parameters = array('id'=>$this->id, 'getnomurl'=>$result); - $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + global $action, $hookmanager; + $hookmanager->initHooks(array('salarypayment')); + $parameters = array('id'=>$this->id, 'getnomurl'=>$result); + $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $result = $hookmanager->resPrint; + else $result .= $hookmanager->resPrint; - return $result; - } + return $result; + } - /** - * Information on record - * - * @param int $id Id of record - * @return void - */ - public function info($id) - { - $sql = 'SELECT ps.rowid, ps.datec, ps.fk_user_author'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'payment_salary as ps'; - $sql .= ' WHERE ps.rowid = '.$id; + /** + * Information on record + * + * @param int $id Id of record + * @return void + */ + public function info($id) + { + $sql = 'SELECT ps.rowid, ps.datec, ps.fk_user_author'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'payment_salary as ps'; + $sql .= ' WHERE ps.rowid = '.$id; - dol_syslog(get_class($this).'::info', LOG_DEBUG); - $result = $this->db->query($sql); + dol_syslog(get_class($this).'::info', LOG_DEBUG); + $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; - if ($obj->fk_user_author) - { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } - $this->date_creation = $this->db->jdate($obj->datec); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + $this->date_creation = $this->db->jdate($obj->datec); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - /** - * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->statut, $mode); - } + /** + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->statut, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Renvoi le libelle d'un statut donne - * - * @param int $status Statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage - $langs->load('compta'); - /*if ($mode == 0) + $langs->load('compta'); + /*if ($mode == 0) { if ($status == 0) return $langs->trans('ToValidate'); if ($status == 1) return $langs->trans('Validated'); @@ -727,6 +727,6 @@ class PaymentSalary extends CommonObject if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); }*/ - return ''; - } + return ''; + } } diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index 50c740e7be3..c48a0c4be3c 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -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 '
'; - print '
' . $companystatic->LibProspCommStatut($obj->stcomm_id, 2, $prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto); + print '
'.$companystatic->LibProspCommStatut($obj->stcomm_id, 2, $prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto); print '
-
'; 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 '' . img_action($titlealt, $val['code'], $val['picto']) . ''; + if ($obj->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; } print '
'; if (!$i) $totalarray['nbfield']++; diff --git a/htdocs/takepos/smpcb.php b/htdocs/takepos/smpcb.php index f138438a707..1e02e9bc591 100644 --- a/htdocs/takepos/smpcb.php +++ b/htdocs/takepos/smpcb.php @@ -40,7 +40,7 @@ if (GETPOSTISSET('status')) { if (GETPOST('smp-status')) { print ''; print ''; - print ' + print ' The HTML5 Herald diff --git a/htdocs/webservices/server_actioncomm.php b/htdocs/webservices/server_actioncomm.php index d3a59962d88..7864c93243f 100644 --- a/htdocs/webservices/server_actioncomm.php +++ b/htdocs/webservices/server_actioncomm.php @@ -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').'.

'; - print $langs->trans("ToActivateModule"); - exit; + $langs->load("admin"); + dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); + print $langs->trans("WarningModuleNotActive", 'WebServices').'.

'; + 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; diff --git a/htdocs/webservices/server_contact.php b/htdocs/webservices/server_contact.php index c4818d050f6..9abc7b6088f 100644 --- a/htdocs/webservices/server_contact.php +++ b/htdocs/webservices/server_contact.php @@ -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').'.

'; - print $langs->trans("ToActivateModule"); - exit; + $langs->load("admin"); + dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); + print $langs->trans("WarningModuleNotActive", 'WebServices').'.

'; + 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) { diff --git a/htdocs/webservices/server_productorservice.php b/htdocs/webservices/server_productorservice.php index 327cab7bed9..224b2f00fa7 100644 --- a/htdocs/webservices/server_productorservice.php +++ b/htdocs/webservices/server_productorservice.php @@ -44,11 +44,11 @@ $langs->load("main"); // 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').'.

'; - print $langs->trans("ToActivateModule"); - exit; + $langs->load("admin"); + dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); + print $langs->trans("WarningModuleNotActive", 'WebServices').'.

'; + print $langs->trans("ToActivateModule"); + exit; } // Create the soap Object @@ -62,72 +62,72 @@ $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') + ) ); $productorservice_fields = array( - 'id' => array('name'=>'id', 'type'=>'xsd:string'), - 'ref' => array('name'=>'ref', 'type'=>'xsd:string'), - 'ref_ext' => array('name'=>'ref_ext', 'type'=>'xsd:string'), - 'type' => array('name'=>'type', 'type'=>'xsd:string'), - 'label' => array('name'=>'label', 'type'=>'xsd:string'), - 'description' => array('name'=>'description', 'type'=>'xsd:string'), - 'date_creation' => array('name'=>'date_creation', 'type'=>'xsd:dateTime'), - 'date_modification' => array('name'=>'date_modification', 'type'=>'xsd:dateTime'), - 'note' => array('name'=>'note', 'type'=>'xsd:string'), - 'status_tobuy' => array('name'=>'status_tobuy', 'type'=>'xsd:string'), - 'status_tosell' => array('name'=>'status_tosell', 'type'=>'xsd:string'), - 'barcode' => array('name'=>'barcode', 'type'=>'xsd:string'), - 'barcode_type' => array('name'=>'barcode_type', 'type'=>'xsd:string'), - 'country_id' => array('name'=>'country_id', 'type'=>'xsd:string'), - 'country_code' => array('name'=>'country_code', 'type'=>'xsd:string'), - 'customcode' => array('name'=>'customcode', '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' => array('name'=>'type', 'type'=>'xsd:string'), + 'label' => array('name'=>'label', 'type'=>'xsd:string'), + 'description' => array('name'=>'description', 'type'=>'xsd:string'), + 'date_creation' => array('name'=>'date_creation', 'type'=>'xsd:dateTime'), + 'date_modification' => array('name'=>'date_modification', 'type'=>'xsd:dateTime'), + 'note' => array('name'=>'note', 'type'=>'xsd:string'), + 'status_tobuy' => array('name'=>'status_tobuy', 'type'=>'xsd:string'), + 'status_tosell' => array('name'=>'status_tosell', 'type'=>'xsd:string'), + 'barcode' => array('name'=>'barcode', 'type'=>'xsd:string'), + 'barcode_type' => array('name'=>'barcode_type', 'type'=>'xsd:string'), + 'country_id' => array('name'=>'country_id', 'type'=>'xsd:string'), + 'country_code' => array('name'=>'country_code', 'type'=>'xsd:string'), + 'customcode' => array('name'=>'customcode', 'type'=>'xsd:string'), - 'price_net' => array('name'=>'price_net', 'type'=>'xsd:string'), - 'price' => array('name'=>'price', 'type'=>'xsd:string'), - 'price_min_net' => array('name'=>'price_min_net', 'type'=>'xsd:string'), - 'price_min' => array('name'=>'price_min', 'type'=>'xsd:string'), + 'price_net' => array('name'=>'price_net', 'type'=>'xsd:string'), + 'price' => array('name'=>'price', 'type'=>'xsd:string'), + 'price_min_net' => array('name'=>'price_min_net', 'type'=>'xsd:string'), + 'price_min' => array('name'=>'price_min', 'type'=>'xsd:string'), - 'price_base_type' => array('name'=>'price_base_type', 'type'=>'xsd:string'), + 'price_base_type' => array('name'=>'price_base_type', 'type'=>'xsd:string'), - 'vat_rate' => array('name'=>'vat_rate', 'type'=>'xsd:string'), - 'vat_npr' => array('name'=>'vat_npr', 'type'=>'xsd:string'), - 'localtax1_tx' => array('name'=>'localtax1_tx', 'type'=>'xsd:string'), - 'localtax2_tx' => array('name'=>'localtax2_tx', 'type'=>'xsd:string'), + 'vat_rate' => array('name'=>'vat_rate', 'type'=>'xsd:string'), + 'vat_npr' => array('name'=>'vat_npr', 'type'=>'xsd:string'), + 'localtax1_tx' => array('name'=>'localtax1_tx', 'type'=>'xsd:string'), + 'localtax2_tx' => array('name'=>'localtax2_tx', 'type'=>'xsd:string'), - 'stock_alert' => array('name'=>'stock_alert', 'type'=>'xsd:string'), - 'stock_real' => array('name'=>'stock_real', 'type'=>'xsd:string'), - 'stock_pmp' => array('name'=>'stock_pmp', 'type'=>'xsd:string'), - 'warehouse_ref' => array('name'=>'warehouse_ref', 'type'=>'xsd:string'), // Used only for create or update to set which warehouse to use for stock correction if stock_real differs from database + 'stock_alert' => array('name'=>'stock_alert', 'type'=>'xsd:string'), + 'stock_real' => array('name'=>'stock_real', 'type'=>'xsd:string'), + 'stock_pmp' => array('name'=>'stock_pmp', 'type'=>'xsd:string'), + 'warehouse_ref' => array('name'=>'warehouse_ref', 'type'=>'xsd:string'), // Used only for create or update to set which warehouse to use for stock correction if stock_real differs from database - 'canvas' => array('name'=>'canvas', 'type'=>'xsd:string'), - 'import_key' => array('name'=>'import_key', 'type'=>'xsd:string'), + 'canvas' => array('name'=>'canvas', 'type'=>'xsd:string'), + 'import_key' => array('name'=>'import_key', 'type'=>'xsd:string'), - 'dir' => array('name'=>'dir', 'type'=>'xsd:string'), - 'images' => array('name'=>'images', 'type'=>'tns:ImagesArray') + 'dir' => array('name'=>'dir', 'type'=>'xsd:string'), + 'images' => array('name'=>'images', 'type'=>'tns:ImagesArray') ); @@ -158,12 +158,12 @@ if (is_array($extrafield_array)) $productorservice_fields = array_merge($product // Define other specific objects $server->wsdl->addComplexType( - 'product', - 'complexType', - 'struct', - 'all', - '', - $productorservice_fields + 'product', + 'complexType', + 'struct', + 'all', + '', + $productorservice_fields ); @@ -206,33 +206,33 @@ $server->wsdl->addComplexType( // Define other specific objects $server->wsdl->addComplexType( - 'filterproduct', - 'complexType', - 'struct', - 'all', - '', - array( - //'limit' => array('name'=>'limit','type'=>'xsd:string'), + 'filterproduct', + 'complexType', + 'struct', + 'all', + '', + array( + //'limit' => array('name'=>'limit','type'=>'xsd:string'), 'type' => array('name'=>'type', 'type'=>'xsd:string'), - 'status_tobuy' => array('name'=>'status_tobuy', 'type'=>'xsd:string'), - 'status_tosell' => array('name'=>'status_tosell', 'type'=>'xsd:string'), - ) + 'status_tobuy' => array('name'=>'status_tobuy', 'type'=>'xsd:string'), + 'status_tosell' => array('name'=>'status_tosell', 'type'=>'xsd:string'), + ) ); $server->wsdl->addComplexType( - 'ProductsArray2', - 'complexType', - 'array', - 'sequence', - '', - array( - 'product' => array( - 'name' => 'product', - 'type' => 'tns:product', - 'minOccurs' => '0', - 'maxOccurs' => 'unbounded' - ) - ) + 'ProductsArray2', + 'complexType', + 'array', + 'sequence', + '', + array( + 'product' => array( + 'name' => 'product', + 'type' => 'tns:product', + 'minOccurs' => '0', + 'maxOccurs' => 'unbounded' + ) + ) ); @@ -247,72 +247,72 @@ $styleuse = 'encoded'; // encoded/literal/literal wrapped // Register WSDL $server->register( - 'getProductOrService', - // Entry values - array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string', 'lang'=>'xsd:string'), - // Exit values - array('result'=>'tns:result', 'product'=>'tns:product'), - $ns, - $ns.'#getProductOrService', - $styledoc, - $styleuse, - 'WS to get product or service' + 'getProductOrService', + // Entry values + array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string', 'lang'=>'xsd:string'), + // Exit values + array('result'=>'tns:result', 'product'=>'tns:product'), + $ns, + $ns.'#getProductOrService', + $styledoc, + $styleuse, + 'WS to get product or service' ); // Register WSDL $server->register( - 'createProductOrService', - // Entry values - array('authentication'=>'tns:authentication', 'product'=>'tns:product'), - // Exit values - array('result'=>'tns:result', 'id'=>'xsd:string'), - $ns, - $ns.'#createProductOrService', - $styledoc, - $styleuse, - 'WS to create a product or service' + 'createProductOrService', + // Entry values + array('authentication'=>'tns:authentication', 'product'=>'tns:product'), + // Exit values + array('result'=>'tns:result', 'id'=>'xsd:string'), + $ns, + $ns.'#createProductOrService', + $styledoc, + $styleuse, + 'WS to create a product or service' ); // Register WSDL $server->register( - 'updateProductOrService', - // Entry values - array('authentication'=>'tns:authentication', 'product'=>'tns:product'), - // Exit values - array('result'=>'tns:result', 'id'=>'xsd:string'), - $ns, - $ns.'#updateProductOrService', - $styledoc, - $styleuse, - 'WS to update a product or service' + 'updateProductOrService', + // Entry values + array('authentication'=>'tns:authentication', 'product'=>'tns:product'), + // Exit values + array('result'=>'tns:result', 'id'=>'xsd:string'), + $ns, + $ns.'#updateProductOrService', + $styledoc, + $styleuse, + 'WS to update a product or service' ); // Register WSDL $server->register( - 'deleteProductOrService', - // Entry values - array('authentication'=>'tns:authentication', 'listofid'=>'xsd:string'), - // Exit values - array('result'=>'tns:result', 'nbdeleted'=>'xsd:int'), - $ns, - $ns.'#deleteProductOrService', - $styledoc, - $styleuse, - 'WS to delete a product or service' + 'deleteProductOrService', + // Entry values + array('authentication'=>'tns:authentication', 'listofid'=>'xsd:string'), + // Exit values + array('result'=>'tns:result', 'nbdeleted'=>'xsd:int'), + $ns, + $ns.'#deleteProductOrService', + $styledoc, + $styleuse, + 'WS to delete a product or service' ); // Register WSDL $server->register( - 'getListOfProductsOrServices', - // Entry values - array('authentication'=>'tns:authentication', 'filterproduct'=>'tns:filterproduct'), - // Exit values - array('result'=>'tns:result', 'products'=>'tns:ProductsArray2'), - $ns, - $ns.'#getListOfProductsOrServices', - $styledoc, - $styleuse, - 'WS to get list of all products or services id and ref' + 'getListOfProductsOrServices', + // Entry values + array('authentication'=>'tns:authentication', 'filterproduct'=>'tns:filterproduct'), + // Exit values + array('result'=>'tns:result', 'products'=>'tns:ProductsArray2'), + $ns, + $ns.'#getListOfProductsOrServices', + $styledoc, + $styleuse, + 'WS to get list of all products or services id and ref' ); // Register WSDL @@ -342,131 +342,131 @@ $server->register( */ function getProductOrService($authentication, $id = '', $ref = '', $ref_ext = '', $lang = '') { - global $db, $conf, $langs; + global $db, $conf, $langs; - dol_syslog("Function: getProductOrService login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); + dol_syslog("Function: getProductOrService login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); - $langcode = ($lang ? $lang : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT)); - $langs->setDefaultLang($langcode); + $langcode = ($lang ? $lang : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT)); + $langs->setDefaultLang($langcode); - 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) || ($id && $ref_ext) || ($ref && $ref_ext))) - { - $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 && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) + { + $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) - { - $langcode = ($lang ? $lang : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT)); - $langs->setDefaultLang($langcode); + if (!$error) + { + $langcode = ($lang ? $lang : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT)); + $langs->setDefaultLang($langcode); - $fuser->getrights(); + $fuser->getrights(); - $nbmax = 10; - if ($fuser->rights->produit->lire || $fuser->rights->service->lire) - { - $product = new Product($db); - $result = $product->fetch($id, $ref, $ref_ext); + $nbmax = 10; + if ($fuser->rights->produit->lire || $fuser->rights->service->lire) + { + $product = new Product($db); + $result = $product->fetch($id, $ref, $ref_ext); - if ($result > 0) - { - $product->load_stock(); + if ($result > 0) + { + $product->load_stock(); - $dir = (!empty($conf->product->dir_output) ? $conf->product->dir_output : $conf->service->dir_output); - $pdir = get_exdir($product->id, 2, 0, 0, $product, 'product').$product->ref."/"; - $dir = $dir.'/'.$pdir; + $dir = (!empty($conf->product->dir_output) ? $conf->product->dir_output : $conf->service->dir_output); + $pdir = get_exdir($product->id, 2, 0, 0, $product, 'product').$product->ref."/"; + $dir = $dir.'/'.$pdir; - if (!empty($product->multilangs[$langs->defaultlang]["label"])) $product->label = $product->multilangs[$langs->defaultlang]["label"]; - if (!empty($product->multilangs[$langs->defaultlang]["description"])) $product->description = $product->multilangs[$langs->defaultlang]["description"]; - if (!empty($product->multilangs[$langs->defaultlang]["note"])) $product->note = $product->multilangs[$langs->defaultlang]["note"]; + if (!empty($product->multilangs[$langs->defaultlang]["label"])) $product->label = $product->multilangs[$langs->defaultlang]["label"]; + if (!empty($product->multilangs[$langs->defaultlang]["description"])) $product->description = $product->multilangs[$langs->defaultlang]["description"]; + if (!empty($product->multilangs[$langs->defaultlang]["note"])) $product->note = $product->multilangs[$langs->defaultlang]["note"]; - $productorservice_result_fields = array( - 'id' => $product->id, - 'ref' => $product->ref, - 'ref_ext' => $product->ref_ext, - 'label' => $product->label, - 'description' => $product->description, - 'date_creation' => dol_print_date($product->date_creation, 'dayhourrfc'), - 'date_modification' => dol_print_date($product->date_modification, 'dayhourrfc'), - 'note' => $product->note, - 'status_tosell' => $product->status, - 'status_tobuy' => $product->status_buy, - 'type' => $product->type, - 'barcode' => $product->barcode, - 'barcode_type' => $product->barcode_type, - 'country_id' => $product->country_id > 0 ? $product->country_id : '', - 'country_code' => $product->country_code, - 'custom_code' => $product->customcode, + $productorservice_result_fields = array( + 'id' => $product->id, + 'ref' => $product->ref, + 'ref_ext' => $product->ref_ext, + 'label' => $product->label, + 'description' => $product->description, + 'date_creation' => dol_print_date($product->date_creation, 'dayhourrfc'), + 'date_modification' => dol_print_date($product->date_modification, 'dayhourrfc'), + 'note' => $product->note, + 'status_tosell' => $product->status, + 'status_tobuy' => $product->status_buy, + 'type' => $product->type, + 'barcode' => $product->barcode, + 'barcode_type' => $product->barcode_type, + 'country_id' => $product->country_id > 0 ? $product->country_id : '', + 'country_code' => $product->country_code, + 'custom_code' => $product->customcode, - 'price_net' => $product->price, - 'price' => $product->price_ttc, - 'price_min_net' => $product->price_min, - 'price_min' => $product->price_min_ttc, - 'price_base_type' => $product->price_base_type, - 'vat_rate' => $product->tva_tx, - //! French VAT NPR - 'vat_npr' => $product->tva_npr, - //! Spanish local taxes - 'localtax1_tx' => $product->localtax1_tx, - 'localtax2_tx' => $product->localtax2_tx, + 'price_net' => $product->price, + 'price' => $product->price_ttc, + 'price_min_net' => $product->price_min, + 'price_min' => $product->price_min_ttc, + 'price_base_type' => $product->price_base_type, + 'vat_rate' => $product->tva_tx, + //! French VAT NPR + 'vat_npr' => $product->tva_npr, + //! Spanish local taxes + 'localtax1_tx' => $product->localtax1_tx, + 'localtax2_tx' => $product->localtax2_tx, - 'stock_real' => $product->stock_reel, - 'stock_virtual' => $product->stock_theorique, - 'stock_alert' => $product->seuil_stock_alerte, - 'pmp' => $product->pmp, - 'import_key' => $product->import_key, - 'dir' => $pdir, - 'images' => $product->liste_photos($dir, $nbmax) - ); + 'stock_real' => $product->stock_reel, + 'stock_virtual' => $product->stock_theorique, + 'stock_alert' => $product->seuil_stock_alerte, + 'pmp' => $product->pmp, + 'import_key' => $product->import_key, + 'dir' => $pdir, + 'images' => $product->liste_photos($dir, $nbmax) + ); - $elementtype = 'product'; + $elementtype = 'product'; - //Retrieve all extrafield for thirdsparty - // fetch optionals attributes and labels - $extrafields = new ExtraFields($db); - $extrafields->fetch_name_optionals_label($elementtype, true); - //Get extrafield values - $product->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 + $product->fetch_optionals(); - if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { - $productorservice_result_fields = array_merge($productorservice_result_fields, array('options_'.$key => $product->array_options['options_'.$key])); - } - } + if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) + { + foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) + { + $productorservice_result_fields = array_merge($productorservice_result_fields, array('options_'.$key => $product->array_options['options_'.$key])); + } + } - // Create - $objectresp = array( - 'result'=>array('result_code'=>'OK', 'result_label'=>''), - 'product'=>$productorservice_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'=>''), + 'product'=>$productorservice_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)); + } //var_dump($objectresp);exit; - return $objectresp; + return $objectresp; } @@ -479,54 +479,54 @@ function getProductOrService($authentication, $id = '', $ref = '', $ref_ext = '' */ function createProductOrService($authentication, $product) { - global $db, $conf, $langs; + global $db, $conf, $langs; - $now = dol_now(); + $now = dol_now(); - dol_syslog("Function: createProductOrService login=".$authentication['login']); + dol_syslog("Function: createProductOrService login=".$authentication['login']); - 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 ($product['price_net'] > 0) $product['price_base_type'] = 'HT'; - if ($product['price'] > 0) $product['price_base_type'] = 'TTC'; + // Init and check authentication + $objectresp = array(); + $errorcode = ''; $errorlabel = ''; + $error = 0; + $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); + // Check parameters + if ($product['price_net'] > 0) $product['price_base_type'] = 'HT'; + if ($product['price'] > 0) $product['price_base_type'] = 'TTC'; - if ($product['price_net'] > 0 && $product['price'] > 0) - { - $error++; $errorcode = 'KO'; $errorlabel = "You must choose between price or price_net to provide price."; - } + if ($product['price_net'] > 0 && $product['price'] > 0) + { + $error++; $errorcode = 'KO'; $errorlabel = "You must choose between price or price_net to provide price."; + } - if ($product['barcode'] && !$product['barcode_type']) - { - $error++; $errorcode = 'KO'; $errorlabel = "You must set a barcode type when setting a barcode."; - } + if ($product['barcode'] && !$product['barcode_type']) + { + $error++; $errorcode = 'KO'; $errorlabel = "You must set a barcode type when setting a barcode."; + } - if (!$error) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + if (!$error) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $newobject = new Product($db); - $newobject->ref = $product['ref']; - $newobject->ref_ext = $product['ref_ext']; - $newobject->type = $product['type']; - $newobject->label = $product['label']; - $newobject->description = $product['description']; - $newobject->note_public = $product['note_public']; - $newobject->note_private = $product['note_private']; - $newobject->status = $product['status_tosell']; - $newobject->status_buy = $product['status_tobuy']; - $newobject->price = $product['price_net']; - $newobject->price_ttc = $product['price']; - $newobject->tva_tx = $product['vat_rate']; - $newobject->price_base_type = $product['price_base_type']; - $newobject->date_creation = $now; + $newobject = new Product($db); + $newobject->ref = $product['ref']; + $newobject->ref_ext = $product['ref_ext']; + $newobject->type = $product['type']; + $newobject->label = $product['label']; + $newobject->description = $product['description']; + $newobject->note_public = $product['note_public']; + $newobject->note_private = $product['note_private']; + $newobject->status = $product['status_tosell']; + $newobject->status_buy = $product['status_tobuy']; + $newobject->price = $product['price_net']; + $newobject->price_ttc = $product['price']; + $newobject->tva_tx = $product['vat_rate']; + $newobject->price_base_type = $product['price_base_type']; + $newobject->date_creation = $now; if ($product['barcode']) { @@ -534,16 +534,16 @@ function createProductOrService($authentication, $product) $newobject->barcode_type = $product['barcode_type']; } - $newobject->stock_reel = $product['stock_real']; - $newobject->pmp = $product['pmp']; - $newobject->seuil_stock_alert = $product['stock_alert']; + $newobject->stock_reel = $product['stock_real']; + $newobject->pmp = $product['pmp']; + $newobject->seuil_stock_alert = $product['stock_alert']; - $newobject->country_id = $product['country_id']; - if ($product['country_code']) $newobject->country_id = getCountry($product['country_code'], 3); - $newobject->customcode = $product['customcode']; + $newobject->country_id = $product['country_id']; + if ($product['country_code']) $newobject->country_id = getCountry($product['country_code'], 3); + $newobject->customcode = $product['customcode']; - $newobject->canvas = $product['canvas']; - /*foreach($product['lines'] as $line) + $newobject->canvas = $product['canvas']; + /*foreach($product['lines'] as $line) { $newline=new FactureLigne($db); $newline->type=$line['type']; @@ -556,13 +556,13 @@ function createProductOrService($authentication, $product) $newline->qty=$line['qty']; $newline->fk_product=$line['product_id']; }*/ - //var_dump($product['ref_ext']); - //var_dump($product['lines'][0]['type']); + //var_dump($product['ref_ext']); + //var_dump($product['lines'][0]['type']); - $elementtype = 'product'; + $elementtype = 'product'; - $extrafields = new ExtraFields($db); - $extrafields->fetch_name_optionals_label($elementtype, true); + $extrafields = new ExtraFields($db); + $extrafields->fetch_name_optionals_label($elementtype, true); if (is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) @@ -572,17 +572,17 @@ function createProductOrService($authentication, $product) } } - $db->begin(); + $db->begin(); - $result = $newobject->create($fuser, 0); - if ($result <= 0) - { - $error++; - } + $result = $newobject->create($fuser, 0); + if ($result <= 0) + { + $error++; + } - if (!$error) - { - // Update stock if stock count is provided and differs from database after creation or update + if (!$error) + { + // Update stock if stock count is provided and differs from database after creation or update if (isset($product['stock_real']) && $product['stock_real'] != '' && !empty($conf->global->stock->enabled)) { include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; @@ -619,25 +619,25 @@ function createProductOrService($authentication, $product) } } - if (!$error) - { - $db->commit(); - $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); - } - else { - $db->rollback(); - $error++; - $errorcode = 'KO'; - $errorlabel = $newobject->error; - } - } + if (!$error) + { + $db->commit(); + $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); + } + else { + $db->rollback(); + $error++; + $errorcode = 'KO'; + $errorlabel = $newobject->error; + } + } - 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; } @@ -728,15 +728,15 @@ function updateProductOrService($authentication, $product) } } - $db->begin(); + $db->begin(); - $result = $newobject->update($newobject->id, $fuser); - if ($result <= 0) - { - $error++; - } - else { - // Update stock if stock count is provided and differs from database after creation or update + $result = $newobject->update($newobject->id, $fuser); + if ($result <= 0) + { + $error++; + } + else { + // Update stock if stock count is provided and differs from database after creation or update if (isset($product['stock_real']) && $product['stock_real'] != '' && !empty($conf->global->stock->enabled)) { include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; @@ -771,47 +771,47 @@ function updateProductOrService($authentication, $product) } } } - } + } - if (!$error) - { - if ($newobject->price_base_type == 'HT') - { - $result = $newobject->updatePrice($newobject->price, $newobject->price_base_type, $fuser); - if ($result <= 0) - { - $error++; - } - } - elseif ($newobject->price_base_type == 'TTC') - { - $result = $newobject->updatePrice($newobject->price_ttc, $newobject->price_base_type); - if ($result <= 0) - { - $error++; - } - } - } + if (!$error) + { + if ($newobject->price_base_type == 'HT') + { + $result = $newobject->updatePrice($newobject->price, $newobject->price_base_type, $fuser); + if ($result <= 0) + { + $error++; + } + } + elseif ($newobject->price_base_type == 'TTC') + { + $result = $newobject->updatePrice($newobject->price_ttc, $newobject->price_base_type); + if ($result <= 0) + { + $error++; + } + } + } - if (!$error) - { - $db->commit(); - $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); - } - else { - $db->rollback(); - $error++; - $errorcode = 'KO'; - $errorlabel = $newobject->error; - } - } + if (!$error) + { + $db->commit(); + $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); + } + else { + $db->rollback(); + $error++; + $errorcode = 'KO'; + $errorlabel = $newobject->error; + } + } - 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; } @@ -824,87 +824,87 @@ function updateProductOrService($authentication, $product) */ function deleteProductOrService($authentication, $listofidstring) { - global $db, $conf, $langs; + global $db, $conf, $langs; - dol_syslog("Function: deleteProductOrService login=".$authentication['login']); + dol_syslog("Function: deleteProductOrService login=".$authentication['login']); - 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); + // Init and check authentication + $objectresp = array(); + $errorcode = ''; $errorlabel = ''; + $error = 0; + $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // User must be defined to user authenticated - global $user; - $user = $fuser; + global $user; + $user = $fuser; - $listofid = explode(',', trim($listofidstring)); - $listofiddeleted = array(); + $listofid = explode(',', trim($listofidstring)); + $listofiddeleted = array(); - // Check parameters - if (count($listofid) == 0 || empty($listofid[0])) - { - $error++; $errorcode = 'KO'; $errorlabel = "List of Id of products or services to delete are required."; - } + // Check parameters + if (count($listofid) == 0 || empty($listofid[0])) + { + $error++; $errorcode = 'KO'; $errorlabel = "List of Id of products or services to delete are required."; + } - if (!$error) - { - $firsterror = ''; + if (!$error) + { + $firsterror = ''; $db->begin(); - foreach ($listofid as $key => $id) + foreach ($listofid as $key => $id) { - $newobject = new Product($db); - $result = $newobject->fetch($id); + $newobject = new Product($db); + $result = $newobject->fetch($id); - if ($result == 0) - { - $error++; - $firsterror = 'Product or service with id '.$id.' not found'; - break; - } - else { - $result = $newobject->delete($user); - if ($result <= 0) - { - $error++; - $firsterror = $newobject->error; - break; - } + if ($result == 0) + { + $error++; + $firsterror = 'Product or service with id '.$id.' not found'; + break; + } + else { + $result = $newobject->delete($user); + if ($result <= 0) + { + $error++; + $firsterror = $newobject->error; + break; + } - $listofiddeleted[] = $id; + $listofiddeleted[] = $id; } } - if (!$error) - { - $db->commit(); - //$objectresp=array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'listofid'=>$listofiddeleted); - $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'nbdeleted'=>count($listofiddeleted)); - } - else { - $db->rollback(); - $error++; - $errorcode = 'KO'; - $errorlabel = $firsterror; + if (!$error) + { + $db->commit(); + //$objectresp=array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'listofid'=>$listofiddeleted); + $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'nbdeleted'=>count($listofiddeleted)); } - } + else { + $db->rollback(); + $error++; + $errorcode = 'KO'; + $errorlabel = $firsterror; + } + } - if ($error) - { - //$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'listofid'=>$listofiddeleted); - $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'nbdeleted'=>0); - } - elseif (count($listofiddeleted) == 0) - { + if ($error) + { + //$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'listofid'=>$listofiddeleted); + $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'nbdeleted'=>0); + } + elseif (count($listofiddeleted) == 0) + { //$objectresp=array('result'=>array('result_code'=>'NOT_FOUND', 'result_label'=>'No product or service with id '.join(',',$listofid).' found'), 'listofid'=>$listofiddeleted); $objectresp = array('result'=>array('result_code'=>'NOT_FOUND', 'result_label'=>'No product or service with id '.join(',', $listofid).' found'), 'nbdeleted'=>0); - } + } - return $objectresp; + return $objectresp; } @@ -917,65 +917,65 @@ function deleteProductOrService($authentication, $listofidstring) */ function getListOfProductsOrServices($authentication, $filterproduct) { - global $db, $conf, $langs; + global $db, $conf, $langs; - dol_syslog("Function: getListOfProductsOrServices login=".$authentication['login']); + dol_syslog("Function: getListOfProductsOrServices login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) $conf->entity = $authentication['entity']; - // Init and check authentication - $objectresp = array(); - $arrayproducts = array(); - $errorcode = ''; $errorlabel = ''; - $error = 0; - $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - // Check parameters + // Init and check authentication + $objectresp = array(); + $arrayproducts = array(); + $errorcode = ''; $errorlabel = ''; + $error = 0; + $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); + // Check parameters - if (!$error) - { - $sql = "SELECT rowid, ref, ref_ext"; - $sql .= " FROM ".MAIN_DB_PREFIX."product"; - $sql .= " WHERE entity=".$conf->entity; - foreach ($filterproduct as $key => $val) - { - if ($key == 'type' && $val >= 0) $sql .= " AND fk_product_type = ".$db->escape($val); - if ($key == 'status_tosell') $sql .= " AND tosell = ".$db->escape($val); - if ($key == 'status_tobuy') $sql .= " AND tobuy = ".$db->escape($val); - } + if (!$error) + { + $sql = "SELECT rowid, ref, ref_ext"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity=".$conf->entity; + foreach ($filterproduct as $key => $val) + { + if ($key == 'type' && $val >= 0) $sql .= " AND fk_product_type = ".$db->escape($val); + if ($key == 'status_tosell') $sql .= " AND tosell = ".$db->escape($val); + if ($key == 'status_tobuy') $sql .= " AND tobuy = ".$db->escape($val); + } $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); + if ($resql) + { + $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - $arrayproducts[] = array('id'=>$obj->rowid, 'ref'=>$obj->ref, 'ref_ext'=>$obj->ref_ext); - $i++; - } - } - else { - $error++; - $errorcode = $db->lasterrno(); - $errorlabel = $db->lasterror(); - } - } + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $arrayproducts[] = array('id'=>$obj->rowid, 'ref'=>$obj->ref, 'ref_ext'=>$obj->ref_ext); + $i++; + } + } + else { + $error++; + $errorcode = $db->lasterrno(); + $errorlabel = $db->lasterror(); + } + } - if ($error) - { - $objectresp = array( + if ($error) + { + $objectresp = array( 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), - 'products'=>$arrayproducts - ); - } else { - $objectresp = array( + 'products'=>$arrayproducts + ); + } else { + $objectresp = array( 'result'=>array('result_code' => 'OK', 'result_label' => ''), - 'products'=>$arrayproducts - ); - } + 'products'=>$arrayproducts + ); + } - return $objectresp; + return $objectresp; } @@ -1050,34 +1050,34 @@ function getProductsForCategory($authentication, $id, $lang = '') $dir = $dir.'/'.$pdir; $products[] = array( - 'id' => $tmpproduct->id, + 'id' => $tmpproduct->id, 'ref' => $tmpproduct->ref, 'ref_ext' => $tmpproduct->ref_ext, - 'label' => !empty($tmpproduct->multilangs[$langs->defaultlang]["label"]) ? $tmpproduct->multilangs[$langs->defaultlang]["label"] : $tmpproduct->label, - 'description' => !empty($tmpproduct->multilangs[$langs->defaultlang]["description"]) ? $tmpproduct->multilangs[$langs->defaultlang]["description"] : $tmpproduct->description, - 'date_creation' => dol_print_date($tmpproduct->date_creation, 'dayhourrfc'), - 'date_modification' => dol_print_date($tmpproduct->date_modification, 'dayhourrfc'), - 'note' => !empty($tmpproduct->multilangs[$langs->defaultlang]["note"]) ? $tmpproduct->multilangs[$langs->defaultlang]["note"] : $tmpproduct->note, - 'status_tosell' => $tmpproduct->status, - 'status_tobuy' => $tmpproduct->status_buy, - 'type' => $tmpproduct->type, - 'barcode' => $tmpproduct->barcode, - 'barcode_type' => $tmpproduct->barcode_type, - 'country_id' => $tmpproduct->country_id > 0 ? $tmpproduct->country_id : '', - 'country_code' => $tmpproduct->country_code, - 'custom_code' => $tmpproduct->customcode, + 'label' => !empty($tmpproduct->multilangs[$langs->defaultlang]["label"]) ? $tmpproduct->multilangs[$langs->defaultlang]["label"] : $tmpproduct->label, + 'description' => !empty($tmpproduct->multilangs[$langs->defaultlang]["description"]) ? $tmpproduct->multilangs[$langs->defaultlang]["description"] : $tmpproduct->description, + 'date_creation' => dol_print_date($tmpproduct->date_creation, 'dayhourrfc'), + 'date_modification' => dol_print_date($tmpproduct->date_modification, 'dayhourrfc'), + 'note' => !empty($tmpproduct->multilangs[$langs->defaultlang]["note"]) ? $tmpproduct->multilangs[$langs->defaultlang]["note"] : $tmpproduct->note, + 'status_tosell' => $tmpproduct->status, + 'status_tobuy' => $tmpproduct->status_buy, + 'type' => $tmpproduct->type, + 'barcode' => $tmpproduct->barcode, + 'barcode_type' => $tmpproduct->barcode_type, + 'country_id' => $tmpproduct->country_id > 0 ? $tmpproduct->country_id : '', + 'country_code' => $tmpproduct->country_code, + 'custom_code' => $tmpproduct->customcode, - 'price_net' => $tmpproduct->price, - 'price' => $tmpproduct->price_ttc, - 'vat_rate' => $tmpproduct->tva_tx, + 'price_net' => $tmpproduct->price, + 'price' => $tmpproduct->price_ttc, + 'vat_rate' => $tmpproduct->tva_tx, 'price_base_type' => $tmpproduct->price_base_type, - 'stock_real' => $tmpproduct->stock_reel, - 'stock_alert' => $tmpproduct->seuil_stock_alerte, - 'pmp' => $tmpproduct->pmp, - 'import_key' => $tmpproduct->import_key, - 'dir' => $pdir, + 'stock_real' => $tmpproduct->stock_reel, + 'stock_alert' => $tmpproduct->seuil_stock_alerte, + 'pmp' => $tmpproduct->pmp, + 'import_key' => $tmpproduct->import_key, + 'dir' => $pdir, 'images' => $tmpproduct->liste_photos($dir, $nbmax) ); diff --git a/htdocs/zapier/class/api_zapier.class.php b/htdocs/zapier/class/api_zapier.class.php index 76c610fa2cd..5ad97434d07 100644 --- a/htdocs/zapier/class/api_zapier.class.php +++ b/htdocs/zapier/class/api_zapier.class.php @@ -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; + } } diff --git a/htdocs/zapier/hook_list.php b/htdocs/zapier/hook_list.php index 9e987d88322..8450ec3e0d8 100644 --- a/htdocs/zapier/hook_list.php +++ b/htdocs/zapier/hook_list.php @@ -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'] = ''.$langs->trans("Delete"); if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); @@ -337,9 +337,9 @@ print ''; $newcardbutton = ''; //if ($user->rights->zapier->creer) //{ - $newcardbutton = ''.$langs->trans('New').''; - $newcardbutton .= ''; - $newcardbutton .= ''; + $newcardbutton = ''.$langs->trans('New').''; + $newcardbutton .= ''; + $newcardbutton .= ''; //} //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 '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } $moreforfilter = ''; @@ -373,9 +373,9 @@ if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; if (!empty($moreforfilter)) { - print '
'; - print $moreforfilter; - print '
'; + print '
'; + print $moreforfilter; + print '
'; } $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; @@ -390,22 +390,22 @@ print ''; 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 ''; - } + $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 ''; + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -426,25 +426,25 @@ print ''."\n"; // -------------------------------------------------------------------- print ''; 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 ''."\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 ''; - 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 ''; + 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 ''; - 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 ''; - 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 ''; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['t.'.$key]['checked'])) { + 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 ''; + 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 ''; + if (!$i) $totalarray['nbfield']++; - print ''; + print ''; - $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 ''; + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print ''; } $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 ''."\n"; print ''."\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('&', '&', $param); + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $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
'; - 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 ''; - } - print ''; + 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 ''; + } + print '
'.$langs->trans("NoRecordFound").'
'.$langs->trans("NoRecordFound").'