diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index afc40bfdff9..3c98c59c0c6 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -297,12 +297,12 @@ print ''; print ''.$langs->trans("ACCOUNTANCY_COMBO_FOR_AUX").''; if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; } else { print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; } print ''; @@ -310,12 +310,12 @@ print ''; print ''.$langs->trans("ACCOUNTING_MANAGE_ZERO").''; if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; } else { print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; } print ''; @@ -387,7 +387,7 @@ foreach ($list_binding as $key) } elseif ($key == 'ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER') { $array=array(0=>$langs->trans("PreviousMonth"), 1=>$langs->trans("CurrentMonth"), 2=>$langs->trans("Fiscalyear")); print $form->selectarray($key, $array, (isset($conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER)?$conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER:0)); - } else { + } else { print ''; } diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index b7027282281..7790271f842 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -140,48 +140,48 @@ if (empty($reshook)) if ($massaction == 'ventil') { - $msg = ''; + $msg = ''; - //print '
' . $langs->trans("Processing") . '...
'; - if (!empty($mesCasesCochees)) { - $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; - $msg .= '
'; - $cpt = 0; - $ok = 0; - $ko = 0; + //print '
' . $langs->trans("Processing") . '...
'; + if (!empty($mesCasesCochees)) { + $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; + $msg .= '
'; + $cpt = 0; + $ok = 0; + $ko = 0; - foreach ($mesCasesCochees as $maLigneCochee) { - $maLigneCourante = explode("_", $maLigneCochee); - $monId = $maLigneCourante[0]; - $monCompte = GETPOST('codeventil'.$monId); + foreach ($mesCasesCochees as $maLigneCochee) { + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monCompte = GETPOST('codeventil'.$monId); - if ($monCompte <= 0) - { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; - $ko++; - } else { - $sql = " UPDATE ".MAIN_DB_PREFIX."facturedet"; - $sql .= " SET fk_code_ventilation = ".$monCompte; - $sql .= " WHERE rowid = ".$monId; + if ($monCompte <= 0) + { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; + $ko++; + } else { + $sql = " UPDATE ".MAIN_DB_PREFIX."facturedet"; + $sql .= " SET fk_code_ventilation = ".$monCompte; + $sql .= " WHERE rowid = ".$monId; - $accountventilated = new AccountingAccount($db); - $accountventilated->fetch($monCompte, ''); + $accountventilated = new AccountingAccount($db); + $accountventilated->fetch($monCompte, ''); - dol_syslog("accountancy/customer/list.php sql=".$sql, LOG_DEBUG); - if ($db->query($sql)) { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; - $ok++; - } else { - $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; - $ko++; - } - } + dol_syslog("accountancy/customer/list.php sql=".$sql, LOG_DEBUG); + if ($db->query($sql)) { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; + $ok++; + } else { + $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; + $ko++; + } + } - $cpt++; - } - $msg .= '
'; - $msg .= '
'.$langs->trans("EndProcessing").'
'; - } + $cpt++; + } + $msg .= '
'; + $msg .= '
'.$langs->trans("EndProcessing").'
'; + } } @@ -199,8 +199,8 @@ if (empty($chartaccountcode)) { print $langs->trans("ErrorChartOfAccountSystemNotSelected"); // End of page - llxFooter(); - $db->close(); + llxFooter(); + $db->close(); exit; } @@ -236,28 +236,28 @@ if ($search_societe) { $sql .= natural_search('s.nom', $search_societe); } if ($search_lineid) { - $sql .= natural_search("l.rowid", $search_lineid, 1); + $sql .= natural_search("l.rowid", $search_lineid, 1); } if (strlen(trim($search_invoice))) { - $sql .= natural_search("f.ref", $search_invoice); + $sql .= natural_search("f.ref", $search_invoice); } if (strlen(trim($search_ref))) { - $sql .= natural_search("p.ref", $search_ref); + $sql .= natural_search("p.ref", $search_ref); } if (strlen(trim($search_label))) { - $sql .= natural_search("p.label", $search_label); + $sql .= natural_search("p.label", $search_label); } if (strlen(trim($search_desc))) { - $sql .= natural_search("l.description", $search_desc); + $sql .= natural_search("l.description", $search_desc); } if (strlen(trim($search_amount))) { - $sql .= natural_search("l.total_ht", $search_amount, 1); + $sql .= natural_search("l.total_ht", $search_amount, 1); } if (strlen(trim($search_account))) { - $sql .= natural_search("aa.account_number", $search_account); + $sql .= natural_search("aa.account_number", $search_account); } if (strlen(trim($search_vat))) { - $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); + $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); } $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year); if (strlen(trim($search_country))) { @@ -295,13 +295,13 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql .= $db->plimit($limit + 1, $offset); @@ -336,9 +336,9 @@ if ($result) { if ($search_tvaintra) $param .= "&search_tvaintra=".urlencode($search_tvaintra); $arrayofmassactions = array( - 'ventil'=>$langs->trans("Ventilate") - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + 'ventil'=>$langs->trans("Ventilate") + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->mymodule->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); @@ -376,8 +376,8 @@ if ($result) { print ''; print ''; if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { - print ''; - } + print ''; + } print ''; $formother->select_year($search_year, 'search_year', 1, 20, 5); print ''; @@ -425,7 +425,7 @@ if ($result) { $isSellerInEEC = isInEEC($mysoc); - $accountingaccount_codetotid_cache = array(); + $accountingaccount_codetotid_cache = array(); while ($i < min($num_lines, $limit)) { $objp = $db->fetch_object($result); @@ -464,29 +464,29 @@ if ($result) { $code_sell_p_notset = ''; $objp->aarowid_suggest = ''; // Will be set later - $isBuyerInEEC = isInEEC($objp); + $isBuyerInEEC = isInEEC($objp); - // Search suggested default account for product/service - $suggestedaccountingaccountbydefaultfor = ''; - if ($objp->type_l == 1) { - if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = ''; - } else { - if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with a VAT + // Search suggested default account for product/service + $suggestedaccountingaccountbydefaultfor = ''; + if ($objp->type_l == 1) { + if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = ''; + } else { + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with a VAT $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); $suggestedaccountingaccountbydefaultfor = 'eecwithvat'; - } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eecwithoutvatnumber'; } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = 'eec'; - } else { // Foreign sale - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = 'export'; - } - } + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eec'; + } else { // Foreign sale + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'export'; + } + } } elseif ($objp->type_l == 0) { if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : ''); @@ -512,28 +512,28 @@ if ($result) { // Search suggested account for product/service (similar code exists in page index.php to make automatic binding) $suggestedaccountingaccountfor = ''; if (($objp->country_code == $mysoc->country_code) || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) - $objp->code_sell_p = $objp->code_sell; - $objp->aarowid_suggest = $objp->aarowid; - $suggestedaccountingaccountfor = ''; - } else { - if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with VAT + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = $objp->aarowid; + $suggestedaccountingaccountfor = ''; + } else { + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with VAT $objp->code_sell_p = $objp->code_sell; $objp->aarowid_suggest = $objp->aarowid; $suggestedaccountingaccountfor = 'eecwithvat'; - } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number - $objp->code_sell_p = $objp->code_sell; - $objp->aarowid_suggest = $objp->aarowid; // There is a doubt for this case. Is it an error on vat or we just forgot to fill vat number ? - $suggestedaccountingaccountfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = $objp->aarowid; // There is a doubt for this case. Is it an error on vat or we just forgot to fill vat number ? + $suggestedaccountingaccountfor = 'eecwithoutvatnumber'; } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale - $objp->code_sell_p = $objp->code_sell_intra; - $objp->aarowid_suggest = $objp->aarowid_intra; - $suggestedaccountingaccountfor = 'eec'; - } else { // Foreign sale - $objp->code_sell_p = $objp->code_sell_export; - $objp->aarowid_suggest = $objp->aarowid_export; - $suggestedaccountingaccountfor = 'export'; - } - } + $objp->code_sell_p = $objp->code_sell_intra; + $objp->aarowid_suggest = $objp->aarowid_intra; + $suggestedaccountingaccountfor = 'eec'; + } else { // Foreign sale + $objp->code_sell_p = $objp->code_sell_export; + $objp->aarowid_suggest = $objp->aarowid_export; + $suggestedaccountingaccountfor = 'export'; + } + } if (!empty($objp->code_sell_p)) { // Value was defined previously @@ -585,32 +585,32 @@ if ($result) { print ''.$thirdpartystatic->getNomUrl(1, 'customer').''; // Country - print ''; - $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; - print $labelcountry; - print ''; + print ''; + $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; + print $labelcountry; + print ''; print ''.$objp->tva_intra.''; // Found accounts print ''; - $s = ''.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; - $shelp = ''; - if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC"); - elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport"); - $s .= ($objp->code_sell_l > 0 ? length_accountg($objp->code_sell_l) : ''.$langs->trans("NotDefined").''); - print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); - if ($objp->product_id > 0) + $s = ''.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; + $shelp = ''; + if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC"); + elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport"); + $s .= ($objp->code_sell_l > 0 ? length_accountg($objp->code_sell_l) : ''.$langs->trans("NotDefined").''); + print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); + if ($objp->product_id > 0) { - print '
'; - $s = ''.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; - $shelp = ''; - if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC"); - elseif ($suggestedaccountingaccountfor == 'eecwithvat') $shelp = $langs->trans("SaleEECWithVAT"); - elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') $shelp = $langs->trans("SaleEECWithoutVATNumber"); - elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport"); - $s .= (empty($objp->code_sell_p) ? ''.$langs->trans("NotDefined").'' : length_accountg($objp->code_sell_p)); - print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); + print '
'; + $s = ''.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; + $shelp = ''; + if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC"); + elseif ($suggestedaccountingaccountfor == 'eecwithvat') $shelp = $langs->trans("SaleEECWithVAT"); + elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') $shelp = $langs->trans("SaleEECWithoutVATNumber"); + elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport"); + $s .= (empty($objp->code_sell_p) ? ''.$langs->trans("NotDefined").'' : length_accountg($objp->code_sell_p)); + print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); } print ''; diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php index 6135a213115..4fdc29b2c0f 100644 --- a/htdocs/accountancy/expensereport/lines.php +++ b/htdocs/accountancy/expensereport/lines.php @@ -264,7 +264,7 @@ if ($result) { print ''; print ''; print ''; - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''; } print ''; @@ -287,7 +287,7 @@ if ($result) { print_liste_field_titre("Employees", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("LineId", $_SERVER["PHP_SELF"], "erd.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("ExpenseReport", $_SERVER["PHP_SELF"], "er.ref", "", $param, '', $sortfield, $sortorder); - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print_liste_field_titre("DateValidation", $_SERVER["PHP_SELF"], "er.date_valid", "", $param, '', $sortfield, $sortorder, 'center '); } print_liste_field_titre("DateOfLine", $_SERVER["PHP_SELF"], "erd.date, erd.rowid", "", $param, '', $sortfield, $sortorder, 'center '); @@ -341,7 +341,7 @@ if ($result) { print ''.$expensereportstatic->getNomUrl(1).''; // Date validation - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''.dol_print_date($db->jdate($objp->date_valid), 'day').''; } diff --git a/htdocs/accountancy/expensereport/list.php b/htdocs/accountancy/expensereport/list.php index 0a5bef0c57e..76d13b99805 100644 --- a/htdocs/accountancy/expensereport/list.php +++ b/htdocs/accountancy/expensereport/list.php @@ -303,7 +303,7 @@ if ($result) { print ''; print ''; print ''; - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''; } print ''; @@ -327,7 +327,7 @@ if ($result) { print_liste_field_titre("Employee", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("LineId", $_SERVER["PHP_SELF"], "erd.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("ExpenseReport", $_SERVER["PHP_SELF"], "er.ref", "", $param, '', $sortfield, $sortorder); - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print_liste_field_titre("DateValidation", $_SERVER["PHP_SELF"], "er.date_valid", "", $param, '', $sortfield, $sortorder, 'center '); } print_liste_field_titre("DateOfLine", $_SERVER["PHP_SELF"], "erd.date, erd.rowid", "", $param, '', $sortfield, $sortorder, 'center '); @@ -381,7 +381,7 @@ if ($result) { print ''.$expensereport_static->getNomUrl(1).''; // Date validation - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''.dol_print_date($db->jdate($objp->date_valid), 'day').''; } diff --git a/htdocs/accountancy/supplier/list.php b/htdocs/accountancy/supplier/list.php index 53c987e0189..9e0b64160e1 100644 --- a/htdocs/accountancy/supplier/list.php +++ b/htdocs/accountancy/supplier/list.php @@ -144,48 +144,48 @@ if (empty($reshook)) if ($massaction == 'ventil') { - $msg = ''; + $msg = ''; - //print '
' . $langs->trans("Processing") . '...
'; - if (!empty($mesCasesCochees)) { - $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; - $msg .= '
'; - $cpt = 0; - $ok = 0; - $ko = 0; + //print '
' . $langs->trans("Processing") . '...
'; + if (!empty($mesCasesCochees)) { + $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; + $msg .= '
'; + $cpt = 0; + $ok = 0; + $ko = 0; - foreach ($mesCasesCochees as $maLigneCochee) { - $maLigneCourante = explode("_", $maLigneCochee); - $monId = $maLigneCourante[0]; - $monCompte = GETPOST('codeventil'.$monId); + foreach ($mesCasesCochees as $maLigneCochee) { + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monCompte = GETPOST('codeventil'.$monId); - if ($monCompte <= 0) - { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; - $ko++; - } else { - $sql = " UPDATE ".MAIN_DB_PREFIX."facture_fourn_det"; - $sql .= " SET fk_code_ventilation = ".$monCompte; - $sql .= " WHERE rowid = ".$monId; + if ($monCompte <= 0) + { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; + $ko++; + } else { + $sql = " UPDATE ".MAIN_DB_PREFIX."facture_fourn_det"; + $sql .= " SET fk_code_ventilation = ".$monCompte; + $sql .= " WHERE rowid = ".$monId; - $accountventilated = new AccountingAccount($db); - $accountventilated->fetch($monCompte, ''); + $accountventilated = new AccountingAccount($db); + $accountventilated->fetch($monCompte, ''); - dol_syslog('accountancy/supplier/list.php:: sql='.$sql, LOG_DEBUG); - if ($db->query($sql)) { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; - $ok++; - } else { - $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; - $ko++; - } - } + dol_syslog('accountancy/supplier/list.php:: sql='.$sql, LOG_DEBUG); + if ($db->query($sql)) { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; + $ok++; + } else { + $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; + $ko++; + } + } - $cpt++; - } - $msg .= '
'; - $msg .= '
'.$langs->trans("EndProcessing").'
'; - } + $cpt++; + } + $msg .= '
'; + $msg .= '
'.$langs->trans("EndProcessing").'
'; + } } @@ -203,8 +203,8 @@ if (empty($chartaccountcode)) { print $langs->trans("ErrorChartOfAccountSystemNotSelected"); // End of page - llxFooter(); - $db->close(); + llxFooter(); + $db->close(); exit; } @@ -240,28 +240,28 @@ if ($search_societe) { $sql .= natural_search('s.nom', $search_societe); } if ($search_lineid) { - $sql .= natural_search("l.rowid", $search_lineid, 1); + $sql .= natural_search("l.rowid", $search_lineid, 1); } if (strlen(trim($search_invoice))) { - $sql .= natural_search("f.ref", $search_invoice); + $sql .= natural_search("f.ref", $search_invoice); } if (strlen(trim($search_label))) { $sql .= natural_search("f.libelle", $search_label); } if (strlen(trim($search_ref))) { - $sql .= natural_search("p.ref", $search_ref); + $sql .= natural_search("p.ref", $search_ref); } if (strlen(trim($search_desc))) { - $sql .= natural_search("l.description", $search_desc); + $sql .= natural_search("l.description", $search_desc); } if (strlen(trim($search_amount))) { - $sql .= natural_search("l.total_ht", $search_amount, 1); + $sql .= natural_search("l.total_ht", $search_amount, 1); } if (strlen(trim($search_account))) { - $sql .= natural_search("aa.account_number", $search_account); + $sql .= natural_search("aa.account_number", $search_account); } if (strlen(trim($search_vat))) { - $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); + $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); } $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year); if (strlen(trim($search_country))) { @@ -299,13 +299,13 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql .= $db->plimit($limit + 1, $offset); @@ -337,9 +337,9 @@ if ($result) { if ($search_tvaintra) $param .= "&search_tvaintra=".urlencode($search_tvaintra); $arrayofmassactions = array( - 'ventil'=>$langs->trans("Ventilate") - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + 'ventil'=>$langs->trans("Ventilate") + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->mymodule->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); @@ -572,12 +572,12 @@ if ($result) { print ''.$thirdpartystatic->getNomUrl(1, 'supplier').''; // Country - print ''; - $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; - print $labelcountry; - print ''; + print ''; + $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; + print $labelcountry; + print ''; - // VAT Num + // VAT Num print ''.$objp->tva_intra.''; // Found accounts diff --git a/htdocs/admin/bank.php b/htdocs/admin/bank.php index 9b66b8e5c7f..b43daca20d9 100644 --- a/htdocs/admin/bank.php +++ b/htdocs/admin/bank.php @@ -51,147 +51,147 @@ $type = 'bankaccount'; // Order display of bank account if ($action == 'setbankorder') { - if (dolibarr_set_const($db, "BANK_SHOW_ORDER_OPTION", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_SHOW_ORDER_OPTION", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } // Auto report last num releve on conciliate if ($action == 'setreportlastnumreleve') { - if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 1, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 1, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } elseif ($action == 'unsetreportlastnumreleve') { - if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 0, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 0, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } // Colorize movements if ($action == 'setbankcolorizemovement') { - if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 1, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 1, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } elseif ($action == 'unsetbankcolorizemovement') { - if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 0, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 0, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } if ($actionsave) { - $db->begin(); + $db->begin(); - $i = 1; $errorsaved = 0; - $error = 0; + $i = 1; $errorsaved = 0; + $error = 0; - // Save colors - while ($i <= 2) - { - $color = GETPOST('BANK_COLORIZE_MOVEMENT_COLOR'.$i, 'alpha'); - if ($color == '-1') $color = ''; + // Save colors + while ($i <= 2) + { + $color = GETPOST('BANK_COLORIZE_MOVEMENT_COLOR'.$i, 'alpha'); + if ($color == '-1') $color = ''; - $res = dolibarr_set_const($db, 'BANK_COLORIZE_MOVEMENT_COLOR'.$i, $color, 'chaine', 0, '', $conf->entity); - if (!$res > 0) $error++; - $i++; - } + $res = dolibarr_set_const($db, 'BANK_COLORIZE_MOVEMENT_COLOR'.$i, $color, 'chaine', 0, '', $conf->entity); + if (!$res > 0) $error++; + $i++; + } - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - $db->rollback(); - if (empty($errorsaved)) setEventMessages($langs->trans("Error"), null, 'errors'); - } + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + $db->rollback(); + if (empty($errorsaved)) setEventMessages($langs->trans("Error"), null, 'errors'); + } } if ($action == 'specimen') { - $modele = GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); - if ($modele == 'sepamandate') { - $object = new CompanyBankAccount($db); - } else { - $object = new Account($db); - } - $object->initAsSpecimen(); + if ($modele == 'sepamandate') { + $object = new CompanyBankAccount($db); + } else { + $object = new Account($db); + } + $object->initAsSpecimen(); - // Search template files - $file = ''; - $classname = ''; - $filefound = 0; - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - $file = dol_buildpath($reldir."core/modules/bank/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) { - $filefound = 1; - $classname = "pdf_".$modele; - break; - } - } + // Search template files + $file = ''; + $classname = ''; + $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $file = dol_buildpath($reldir."core/modules/bank/doc/pdf_".$modele.".modules.php", 0); + if (file_exists($file)) { + $filefound = 1; + $classname = "pdf_".$modele; + break; + } + } - if ($filefound) { - require_once $file; + if ($filefound) { + require_once $file; - $module = new $classname($db); + $module = new $classname($db); - if ($module->write_file($object, $langs) > 0) { - header("Location: ".DOL_URL_ROOT."/document.php?modulepart=bank&file=SPECIMEN.pdf"); - return; - } else { - setEventMessages($module->error, null, 'errors'); - dol_syslog($module->error, LOG_ERR); - } - } else { - setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); - dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); - } + if ($module->write_file($object, $langs) > 0) { + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=bank&file=SPECIMEN.pdf"); + return; + } else { + setEventMessages($module->error, null, 'errors'); + dol_syslog($module->error, LOG_ERR); + } + } else { + setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); + dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); + } } // Activate a model if ($action == 'set') { - $ret = addDocumentModel($value, $type, $label, $scandir); + $ret = addDocumentModel($value, $type, $label, $scandir); } elseif ($action == 'del') { - $ret = delDocumentModel($value, $type); - if ($ret > 0) { - if ($conf->global->BANKADDON_PDF == "$value") - dolibarr_del_const($db, 'BANKADDON_PDF', $conf->entity); - } + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + if ($conf->global->BANKADDON_PDF == "$value") + dolibarr_del_const($db, 'BANKADDON_PDF', $conf->entity); + } } // Set default model elseif ($action == 'setdoc') { - if (dolibarr_set_const($db, "BANKADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { - // The constant that was read before the new set - // We therefore requires a variable to have a coherent view - $conf->global->BANKADDON_PDF = $value; - } + if (dolibarr_set_const($db, "BANKADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { + // The constant that was read before the new set + // We therefore requires a variable to have a coherent view + $conf->global->BANKADDON_PDF = $value; + } - // On active le modele - $ret = delDocumentModel($value, $type); - if ($ret > 0) { - $ret = addDocumentModel($value, $type, $label, $scandir); - } + // On active le modele + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + $ret = addDocumentModel($value, $type, $label, $scandir); + } } diff --git a/htdocs/admin/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index 94a3d698c2a..3044aa3ab6f 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -670,12 +670,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Clone print '
'.$langs->trans("ToClone").'
'; - // Collect now - if (count($object->actions) > 0) { + // Collect now + if (count($object->actions) > 0) { print '
'.$langs->trans("CollectNow").'
'; - } else { - print '
'.$langs->trans("CollectNow").'
'; - } + } else { + print '
'.$langs->trans("CollectNow").'
'; + } print '
'.$langs->trans('Delete').'
'; } diff --git a/htdocs/admin/menus/edit.php b/htdocs/admin/menus/edit.php index b0514dfc975..04c1b79a5bc 100644 --- a/htdocs/admin/menus/edit.php +++ b/htdocs/admin/menus/edit.php @@ -40,8 +40,8 @@ $dirsmartphone = array(); $dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); foreach ($dirmenus as $dirmenu) { - $dirstandard[] = $dirmenu.'standard'; - $dirsmartphone[] = $dirmenu.'smartphone'; + $dirstandard[] = $dirmenu.'standard'; + $dirsmartphone[] = $dirmenu.'smartphone'; } $action = GETPOST('action', 'aZ09'); @@ -66,192 +66,192 @@ if (GETPOST("menu_handler")) $menu_handler = GETPOST("menu_handler"); if ($action == 'update') { - if (!$cancel) - { - $leftmenu = ''; $mainmenu = ''; - if (GETPOST('menuIdParent', 'alpha') && !is_numeric(GETPOST('menuIdParent', 'alpha'))) - { - $tmp = explode('&', GETPOST('menuIdParent', 'alpha')); - foreach ($tmp as $s) - { - if (preg_match('/fk_mainmenu=/', $s)) - { - $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); - } - if (preg_match('/fk_leftmenu=/', $s)) - { - $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); - } - } - } + if (!$cancel) + { + $leftmenu = ''; $mainmenu = ''; + if (GETPOST('menuIdParent', 'alpha') && !is_numeric(GETPOST('menuIdParent', 'alpha'))) + { + $tmp = explode('&', GETPOST('menuIdParent', 'alpha')); + foreach ($tmp as $s) + { + if (preg_match('/fk_mainmenu=/', $s)) + { + $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); + } + if (preg_match('/fk_leftmenu=/', $s)) + { + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); + } + } + } - $menu = new Menubase($db); - $result = $menu->fetch(GETPOST('menuId', 'int')); - if ($result > 0) - { - $menu->title = GETPOST('titre', 'alpha'); - $menu->leftmenu = GETPOST('leftmenu', 'aZ09'); - $menu->url = GETPOST('url', 'alpha'); - $menu->langs = GETPOST('langs', 'alpha'); - $menu->position = GETPOST('position', 'int'); - $menu->enabled = GETPOST('enabled', 'alpha'); - $menu->perms = GETPOST('perms', 'alpha'); - $menu->target = GETPOST('target', 'alpha'); - $menu->user = GETPOST('user', 'alpha'); - $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); - if (is_numeric(GETPOST('menuIdParent', 'alpha'))) - { - $menu->fk_menu = GETPOST('menuIdParent', 'alpha'); - } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; - else $menu->fk_menu = -1; - $menu->fk_mainmenu = $mainmenu; - $menu->fk_leftmenu = $leftmenu; - } + $menu = new Menubase($db); + $result = $menu->fetch(GETPOST('menuId', 'int')); + if ($result > 0) + { + $menu->title = GETPOST('titre', 'alpha'); + $menu->leftmenu = GETPOST('leftmenu', 'aZ09'); + $menu->url = GETPOST('url', 'alpha'); + $menu->langs = GETPOST('langs', 'alpha'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alpha'); + $menu->perms = GETPOST('perms', 'alpha'); + $menu->target = GETPOST('target', 'alpha'); + $menu->user = GETPOST('user', 'alpha'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); + if (is_numeric(GETPOST('menuIdParent', 'alpha'))) + { + $menu->fk_menu = GETPOST('menuIdParent', 'alpha'); + } else { + if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; + } - $result = $menu->update($user); - if ($result > 0) - { - setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); - } else { - setEventMessages($menu->error, $menu->errors, 'errors'); - } - } else { - setEventMessages($menu->error, $menu->errors, 'errors'); - } - $action = "edit"; + $result = $menu->update($user); + if ($result > 0) + { + setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); + } else { + setEventMessages($menu->error, $menu->errors, 'errors'); + } + } else { + setEventMessages($menu->error, $menu->errors, 'errors'); + } + $action = "edit"; - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } else { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } else { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } } if ($action == 'add') { - if ($cancel) - { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } + if ($cancel) + { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } - $leftmenu = ''; $mainmenu = ''; - if (GETPOST('menuId', 'alpha', 3) && !is_numeric(GETPOST('menuId', 'alpha', 3))) - { - $tmp = explode('&', GETPOST('menuId', 'alpha', 3)); - foreach ($tmp as $s) - { - if (preg_match('/fk_mainmenu=/', $s)) - { + $leftmenu = ''; $mainmenu = ''; + if (GETPOST('menuId', 'alpha', 3) && !is_numeric(GETPOST('menuId', 'alpha', 3))) + { + $tmp = explode('&', GETPOST('menuId', 'alpha', 3)); + foreach ($tmp as $s) + { + if (preg_match('/fk_mainmenu=/', $s)) + { $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); - } - if (preg_match('/fk_leftmenu=/', $s)) - { - $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); - } - } - } + } + if (preg_match('/fk_leftmenu=/', $s)) + { + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); + } + } + } - $langs->load("errors"); + $langs->load("errors"); - $error = 0; - if (!$error && !$_POST['menu_handler']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MenuHandler")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['type']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['url']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['titre']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && $_POST['menuId'] && $_POST['type'] == 'top') - { - setEventMessages($langs->trans("ErrorTopMenuMustHaveAParentWithId0"), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['menuId'] && $_POST['type'] == 'left') - { - setEventMessages($langs->trans("ErrorLeftMenuMustHaveAParentId"), null, 'errors'); - $action = 'create'; - $error++; - } + $error = 0; + if (!$error && !$_POST['menu_handler']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MenuHandler")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['type']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['url']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['titre']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && $_POST['menuId'] && $_POST['type'] == 'top') + { + setEventMessages($langs->trans("ErrorTopMenuMustHaveAParentWithId0"), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['menuId'] && $_POST['type'] == 'left') + { + setEventMessages($langs->trans("ErrorLeftMenuMustHaveAParentId"), null, 'errors'); + $action = 'create'; + $error++; + } - if (!$error) - { - $menu = new Menubase($db); - $menu->menu_handler = preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); - $menu->type = GETPOST('type', 'alpha'); - $menu->title = GETPOST('titre', 'alpha'); - $menu->url = GETPOST('url', 'alpha'); - $menu->langs = GETPOST('langs', 'alpha'); - $menu->position = GETPOST('position', 'int'); - $menu->enabled = GETPOST('enabled', 'alpha'); - $menu->perms = GETPOST('perms', 'alpha'); - $menu->target = GETPOST('target', 'alpha'); - $menu->user = GETPOST('user', 'alpha'); - $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); - if (is_numeric(GETPOST('menuId', 'alpha', 3))) - { - $menu->fk_menu = GETPOST('menuId', 'alpha', 3); - } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; - else $menu->fk_menu = -1; - $menu->fk_mainmenu = $mainmenu; - $menu->fk_leftmenu = $leftmenu; - } + if (!$error) + { + $menu = new Menubase($db); + $menu->menu_handler = preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); + $menu->type = GETPOST('type', 'alpha'); + $menu->title = GETPOST('titre', 'alpha'); + $menu->url = GETPOST('url', 'alpha'); + $menu->langs = GETPOST('langs', 'alpha'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alpha'); + $menu->perms = GETPOST('perms', 'alpha'); + $menu->target = GETPOST('target', 'alpha'); + $menu->user = GETPOST('user', 'alpha'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); + if (is_numeric(GETPOST('menuId', 'alpha', 3))) + { + $menu->fk_menu = GETPOST('menuId', 'alpha', 3); + } else { + if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; + } - $result = $menu->create($user); - if ($result > 0) - { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".GETPOST('menu_handler', 'aZ09')); - exit; - } else { - $action = 'create'; - setEventMessages($menu->error, $menu->errors, 'errors'); - } - } + $result = $menu->create($user); + if ($result > 0) + { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".GETPOST('menu_handler', 'aZ09')); + exit; + } else { + $action = 'create'; + setEventMessages($menu->error, $menu->errors, 'errors'); + } + } } // delete if ($action == 'confirm_delete' && $_POST["confirm"] == 'yes') { - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); - $result = $db->query($sql); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); + $result = $db->query($sql); - if ($result == 0) - { - $this->db->commit(); + if ($result == 0) + { + $this->db->commit(); - llxHeader(); - setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); - llxFooter(); - exit; - } else { - $this->db->rollback(); + llxHeader(); + setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); + llxFooter(); + exit; + } else { + $this->db->rollback(); - $reload = 0; - $_GET["action"] = ''; - } + $reload = 0; + $_GET["action"] = ''; + } } @@ -268,7 +268,7 @@ llxHeader('', $langs->trans("Menu")); if ($action == 'create') { - print ''; - print load_fiche_titre($langs->trans("NewMenu"), '', 'title_setup'); + print load_fiche_titre($langs->trans("NewMenu"), '', 'title_setup'); - print '
'; - print ''; + print ''; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - // Id - $parent_rowid = GETPOST('menuId', 'int'); - if (GETPOST('menuId', 'int')) - { - $sql = "SELECT m.rowid, m.mainmenu, m.leftmenu, m.level, m.langs FROM ".MAIN_DB_PREFIX."menu as m WHERE m.rowid = ".GETPOST('menuId', 'int'); - $res = $db->query($sql); - if ($res) - { - while ($menu = $db->fetch_array($res)) - { - $parent_rowid = $menu['rowid']; - $parent_mainmenu = $menu['mainmenu']; - $parent_leftmenu = $menu['leftmenu']; - $parent_langs = $menu['langs']; - $parent_level = $menu['level']; - } - } - } + // Id + $parent_rowid = GETPOST('menuId', 'int'); + if (GETPOST('menuId', 'int')) + { + $sql = "SELECT m.rowid, m.mainmenu, m.leftmenu, m.level, m.langs FROM ".MAIN_DB_PREFIX."menu as m WHERE m.rowid = ".GETPOST('menuId', 'int'); + $res = $db->query($sql); + if ($res) + { + while ($menu = $db->fetch_array($res)) + { + $parent_rowid = $menu['rowid']; + $parent_mainmenu = $menu['mainmenu']; + $parent_leftmenu = $menu['leftmenu']; + $parent_langs = $menu['langs']; + $parent_level = $menu['level']; + } + } + } - // Handler - print ''; - print ''; - print ''; + // Handler + print ''; + print ''; + print ''; - // User - print ''; - print ''; - print ''; + // User + print ''; + print ''; + print ''; - // Type - print ''; + // Type + print ''; - // Mainmenu code - print ''; + // Mainmenu code + print ''; print ''; - print ''; + print ''; - // MenuId Parent - print ''; - if ($parent_rowid) - { - print ''; - } else { - print ''; - } - print ''; + // MenuId Parent + print ''; + if ($parent_rowid) + { + print ''; + } else { + print ''; + } + print ''; - // Title - print ''; + // Title + print ''; - // URL - print ''; + // URL + print ''; - // Langs - print ''; + // Langs + print ''; - // Position - print ''; + // Position + print ''; - // Target - print ''; + // Target + print ''; - // Enabled - print ''; + // Enabled + print ''; - // Perms - print ''; + // Perms + print ''; - print '
'.$langs->trans('MenuHandler').''; - $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler) ? '' : '_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); - print ''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuHandler').''; + $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler) ? '' : '_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); + print ''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('Type').''; - if ($parent_rowid) - { - print $langs->trans('Left'); - print ''; - } else { - print ''; - } - print ''.$langs->trans('DetailType').'
'.$langs->trans('Type').''; + if ($parent_rowid) + { + print $langs->trans('Left'); + print ''; + } else { + print ''; + } + print ''.$langs->trans('DetailType').'
'.$langs->trans('MainMenuCode').'
'.$langs->trans('MainMenuCode').''; - print $langs->trans("Example").': mytopmenukey'; - print '
'; + print $langs->trans("Example").': mytopmenukey'; + print '
'.$langs->trans('MenuIdParent').''.$parent_rowid.''.$langs->trans('DetailMenuIdParent'); - print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; - print '
'.$langs->trans('MenuIdParent').''.$parent_rowid.''.$langs->trans('DetailMenuIdParent'); + print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; + print '
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
'; + print '
'; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; - print ''; + print ''; } elseif ($action == 'edit') { - print load_fiche_titre($langs->trans("ModifMenu"), '', 'title_setup'); - print '
'; + print load_fiche_titre($langs->trans("ModifMenu"), '', 'title_setup'); + print '
'; - print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - $menu = new Menubase($db); - $result = $menu->fetch(GETPOST('menuId', 'int')); - //var_dump($menu); + $menu = new Menubase($db); + $result = $menu->fetch(GETPOST('menuId', 'int')); + //var_dump($menu); - // Id - print ''; + // Id + print ''; - // Module - print ''; + // Module + print ''; - // Handler - if ($menu->menu_handler == 'all') $handler = $langs->trans('AllMenus'); - else $handler = $menu->menu_handler; - print ''; + // Handler + if ($menu->menu_handler == 'all') $handler = $langs->trans('AllMenus'); + else $handler = $menu->menu_handler; + print ''; - // User - print ''; + // User + print ''; - // Type - print ''; + // Type + print ''; - // Mainmenu code - if ($menu->type == 'top') - { - print ''; - /*if ($parent_rowid) + // Mainmenu code + if ($menu->type == 'top') + { + print ''; + /*if ($parent_rowid) { print ''; } else {*/ - print ''; - //} - print ''; - } + print ''; + //} + print ''; + } - // MenuId Parent - print ''; - $valtouse = $menu->fk_menu; - if ($menu->fk_mainmenu) $valtouse = 'fk_mainmenu='.$menu->fk_mainmenu; - if ($menu->fk_leftmenu) $valtouse .= '&fk_leftmenu='.$menu->fk_leftmenu; - print ''; - print ''; + // MenuId Parent + print ''; + $valtouse = $menu->fk_menu; + if ($menu->fk_mainmenu) $valtouse = 'fk_mainmenu='.$menu->fk_mainmenu; + if ($menu->fk_leftmenu) $valtouse .= '&fk_leftmenu='.$menu->fk_leftmenu; + print ''; + print ''; - // Niveau - //print ''; + // Niveau + //print ''; - // Title - print ''; + // Title + print ''; - // Url - print ''; + // Url + print ''; - // Langs - print ''; + // Langs + print ''; - // Position - print ''; + // Position + print ''; - // Target - print ''; + // Target + print ''; - // Enabled - print ''; + // Enabled + print ''; - // Perms - print ''; + // Perms + print ''; - print '
'.$langs->trans('Id').''.$menu->id.''.$langs->trans('DetailId').'
'.$langs->trans('Id').''.$menu->id.''.$langs->trans('DetailId').'
'.$langs->trans('MenuModule').''.$menu->module.''.$langs->trans('DetailMenuModule').'
'.$langs->trans('MenuModule').''.$menu->module.''.$langs->trans('DetailMenuModule').'
'.$langs->trans('MenuHandler').''.$handler.''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuHandler').''.$handler.''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('Type').''.$langs->trans(ucfirst($menu->type)).''.$langs->trans('DetailType').'
'.$langs->trans('Type').''.$langs->trans(ucfirst($menu->type)).''.$langs->trans('DetailType').'
'.$langs->trans('MainMenuCode').'
'.$langs->trans('MainMenuCode').''.$parent_rowid.'mainmenu).'">'; - print $langs->trans("Example").': mytopmenukey'; - print '
mainmenu).'">'; + print $langs->trans("Example").': mytopmenukey'; + print '
'.$langs->trans('MenuIdParent'); - print ''.$langs->trans('DetailMenuIdParent'); - print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; - print '
'.$langs->trans('MenuIdParent'); + print ''.$langs->trans('DetailMenuIdParent'); + print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; + print '
'.$langs->trans('Level').''.$menu->level.''.$langs->trans('DetailLevel').'
'.$langs->trans('Level').''.$menu->level.''.$langs->trans('DetailLevel').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled'); - if (!empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; - print '
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled'); + if (!empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; + print '
'.$langs->trans('Rights').''.$langs->trans('DetailRight'); - if (!empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; - print '
'.$langs->trans('Rights').''.$langs->trans('DetailRight'); + if (!empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; + print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - // Bouton - print '
'; + // Bouton + print '
'; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; - print ''; + print ''; - print '
'; + print '
'; } // End of page diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 5514172182e..908044433e7 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -498,7 +498,7 @@ class ActionComm extends CommonObject $sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", "; $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", "; $sql .= " '".$this->db->escape($this->note_private)."', "; - $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned + $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", "; $sql .= ($userownerid > 0 ? $userownerid : "null").", "; $sql .= ($userdoneid > 0 ? $userdoneid : "null").", "; @@ -632,173 +632,173 @@ class ActionComm extends CommonObject //$this->fetch_userassigned(); $this->fetchResources(); - $this->id = 0; + $this->id = 0; - // Create clone + // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($fuser); - if ($result < 0) $error++; + if ($result < 0) $error++; - if (!$error) - { - // Hook of thirdparty module - if (is_object($hookmanager)) - { - $parameters = array('objFrom'=>$objFrom); - $action = ''; - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; - } + if (!$error) + { + // Hook of thirdparty module + if (is_object($hookmanager)) + { + $parameters = array('objFrom'=>$objFrom); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } - // Call trigger - $result = $this->call_trigger('ACTION_CLONE', $fuser); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result = $this->call_trigger('ACTION_CLONE', $fuser); + if ($result < 0) { $error++; } + // End call triggers + } - unset($this->context['createfromclone']); + unset($this->context['createfromclone']); - // End - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + // End + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Load object from database - * - * @param int $id Id of action to get - * @param string $ref Ref of action to get - * @param string $ref_ext Ref ext to get + /** + * Load object from database + * + * @param int $id Id of action to get + * @param string $ref Ref of action to get + * @param string $ref_ext Ref ext to get * @param string $email_msgid Email msgid - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '') - { - global $langs; + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '') + { + global $langs; - $sql = "SELECT a.id,"; - $sql .= " a.id as ref,"; - $sql .= " a.entity,"; - $sql .= " a.ref_ext,"; - $sql .= " a.datep,"; - $sql .= " a.datep2,"; - $sql .= " a.durationp,"; // deprecated - $sql .= " a.datec,"; - $sql .= " a.tms as datem,"; - $sql .= " a.code, a.label, a.note,"; - $sql .= " a.fk_soc,"; - $sql .= " a.fk_project,"; - $sql .= " a.fk_user_author, a.fk_user_mod,"; - $sql .= " a.fk_user_action, a.fk_user_done,"; - $sql .= " a.fk_contact, a.percent as percentage,"; - $sql .= " a.fk_element as elementid, a.elementtype,"; - $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; - $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,"; - $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; - $sql .= " s.nom as socname,"; - $sql .= " u.firstname, u.lastname as lastname"; - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; - $sql .= " WHERE "; - if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id - elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'"; - elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'"; - else $sql .= " a.id = ".((int) $id); + $sql = "SELECT a.id,"; + $sql .= " a.id as ref,"; + $sql .= " a.entity,"; + $sql .= " a.ref_ext,"; + $sql .= " a.datep,"; + $sql .= " a.datep2,"; + $sql .= " a.durationp,"; // deprecated + $sql .= " a.datec,"; + $sql .= " a.tms as datem,"; + $sql .= " a.code, a.label, a.note,"; + $sql .= " a.fk_soc,"; + $sql .= " a.fk_project,"; + $sql .= " a.fk_user_author, a.fk_user_mod,"; + $sql .= " a.fk_user_action, a.fk_user_done,"; + $sql .= " a.fk_contact, a.percent as percentage,"; + $sql .= " a.fk_element as elementid, a.elementtype,"; + $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; + $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,"; + $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; + $sql .= " s.nom as socname,"; + $sql .= " u.firstname, u.lastname as lastname"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; + $sql .= " WHERE "; + if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id + elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'"; + elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'"; + else $sql .= " a.id = ".((int) $id); - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->id; + $this->id = $obj->id; $this->entity = $obj->entity; - $this->ref = $obj->ref; - $this->ref_ext = $obj->ref_ext; + $this->ref = $obj->ref; + $this->ref_ext = $obj->ref_ext; - // Properties of parent table llx_c_actioncomm - $this->type_id = $obj->type_id; - $this->type_code = $obj->type_code; - $this->type_color = $obj->type_color; - $this->type_picto = $obj->type_picto; - $transcode = $langs->trans("Action".$obj->type_code); - $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label); - $transcode = $langs->trans("Action".$obj->type_code.'Short'); - $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : ''); + // Properties of parent table llx_c_actioncomm + $this->type_id = $obj->type_id; + $this->type_code = $obj->type_code; + $this->type_color = $obj->type_color; + $this->type_picto = $obj->type_picto; + $transcode = $langs->trans("Action".$obj->type_code); + $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label); + $transcode = $langs->trans("Action".$obj->type_code.'Short'); + $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : ''); $this->code = $obj->code; - $this->label = $obj->label; - $this->datep = $this->db->jdate($obj->datep); - $this->datef = $this->db->jdate($obj->datep2); + $this->label = $obj->label; + $this->datep = $this->db->jdate($obj->datep); + $this->datef = $this->db->jdate($obj->datep2); - $this->datec = $this->db->jdate($obj->datec); - $this->datem = $this->db->jdate($obj->datem); + $this->datec = $this->db->jdate($obj->datec); + $this->datem = $this->db->jdate($obj->datem); - $this->note = $obj->note; // deprecated - $this->note_private = $obj->note; - $this->percentage = $obj->percentage; + $this->note = $obj->note; // deprecated + $this->note_private = $obj->note; + $this->percentage = $obj->percentage; - $this->authorid = $obj->fk_user_author; - $this->usermodid = $obj->fk_user_mod; + $this->authorid = $obj->fk_user_author; + $this->usermodid = $obj->fk_user_mod; - if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning - $this->author->id = $obj->fk_user_author; // deprecated - $this->author->firstname = $obj->firstname; // deprecated - $this->author->lastname = $obj->lastname; // deprecated - if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning - $this->usermod->id = $obj->fk_user_mod; // deprecated + if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning + $this->author->id = $obj->fk_user_author; // deprecated + $this->author->firstname = $obj->firstname; // deprecated + $this->author->lastname = $obj->lastname; // deprecated + if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning + $this->usermod->id = $obj->fk_user_mod; // deprecated - $this->userownerid = $obj->fk_user_action; - $this->userdoneid = $obj->fk_user_done; - $this->priority = $obj->priority; - $this->fulldayevent = $obj->fulldayevent; - $this->location = $obj->location; - $this->transparency = $obj->transparency; + $this->userownerid = $obj->fk_user_action; + $this->userdoneid = $obj->fk_user_done; + $this->priority = $obj->priority; + $this->fulldayevent = $obj->fulldayevent; + $this->location = $obj->location; + $this->transparency = $obj->transparency; - $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working - $this->contact_id = $obj->fk_contact; // To have fetch_contact method working - $this->fk_project = $obj->fk_project; // To have fetch_projet method working + $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working + $this->contact_id = $obj->fk_contact; // To have fetch_contact method working + $this->fk_project = $obj->fk_project; // To have fetch_projet method working - //$this->societe->id = $obj->fk_soc; // deprecated - //$this->contact->id = $obj->fk_contact; // deprecated + //$this->societe->id = $obj->fk_soc; // deprecated + //$this->contact->id = $obj->fk_contact; // deprecated - $this->fk_element = $obj->elementid; - $this->elementid = $obj->elementid; - $this->elementtype = $obj->elementtype; + $this->fk_element = $obj->elementid; + $this->elementid = $obj->elementid; + $this->elementtype = $obj->elementtype; - $this->fetchResources(); - } - $this->db->free($resql); - } else { - $this->error = $this->db->lasterror(); - return -1; - } + $this->fetchResources(); + } + $this->db->free($resql); + } else { + $this->error = $this->db->lasterror(); + return -1; + } - return $num; - } + return $num; + } - /** - * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event - * - * @return int <0 if KO, >0 if OK - */ - public function fetchResources() - { - $this->userassigned = array(); - $this->socpeopleassigned = array(); + /** + * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event + * + * @return int <0 if KO, >0 if OK + */ + public function fetchResources() + { + $this->userassigned = array(); + $this->socpeopleassigned = array(); - $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; + $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources'; $sql .= ' WHERE fk_actioncomm = '.$this->id; $sql .= " AND element_type IN ('user', 'socpeople')"; @@ -1937,168 +1937,168 @@ class ActionComm extends CommonObject return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } - /** - * Is the action delayed? - * - * @return bool - */ - public function hasDelay() - { - global $conf; + /** + * Is the action delayed? + * + * @return bool + */ + public function hasDelay() + { + global $conf; - $now = dol_now(); + $now = dol_now(); - return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay)); - } + return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay)); + } - /** - * Send reminders by emails - * CAN BE A CRON TASK - * - * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) - */ - public function sendEmailsReminder() - { - global $conf, $langs, $user; + /** + * Send reminders by emails + * CAN BE A CRON TASK + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function sendEmailsReminder() + { + global $conf, $langs, $user; - $error = 0; - $this->output = ''; + $error = 0; + $this->output = ''; $this->error = ''; $nbMailSend = 0; $errorsMsg = array(); - if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible. + if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible. { $langs->load("agenda"); $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda")); return 0; } if (empty($conf->global->AGENDA_REMINDER_EMAIL)) - { - $langs->load("agenda"); - $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda")); - return 0; - } + { + $langs->load("agenda"); + $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda")); + return 0; + } - $now = dol_now(); + $now = dol_now(); - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $this->db->begin(); + $this->db->begin(); - //Select all action comm reminder - $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; + //Select all action comm reminder + $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; $sql .= " WHERE typeremind = 'email' AND status = 0"; $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'"; $sql .= $this->db->order("dateremind", "ASC"); - $resql = $this->db->query($sql); + $resql = $this->db->query($sql); - if ($resql) { - $formmail = new FormMail($this->db); - $actionCommReminder = new ActionCommReminder($this->db); + if ($resql) { + $formmail = new FormMail($this->db); + $actionCommReminder = new ActionCommReminder($this->db); while ($obj = $this->db->fetch_object($resql)){ - $res = $actionCommReminder->fetch($obj->id); - if ($res < 0) { - $error++; - $errorsMsg[] = "Failed to load invoice ActionComm Reminder"; - } + $res = $actionCommReminder->fetch($obj->id); + if ($res < 0) { + $error++; + $errorsMsg[] = "Failed to load invoice ActionComm Reminder"; + } - if (!$error) - { - //Select email template - $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1); + if (!$error) + { + //Select email template + $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1); - // Load event - $res = $this->fetch($actionCommReminder->fk_actioncomm); - if ($res > 0) - { - // PREPARE EMAIL + // Load event + $res = $this->fetch($actionCommReminder->fk_actioncomm); + if ($res > 0) + { + // PREPARE EMAIL - // Make substitution in email content - $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this); + // Make substitution in email content + $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this); - complete_substitutions_array($substitutionarray, $langs, $this); + complete_substitutions_array($substitutionarray, $langs, $this); - // Content - $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray); + // Content + $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray); - //Topic - $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder')); + //Topic + $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder')); - // Recipient - $recipient = new User($this->db); - $res = $recipient->fetch($actionCommReminder->fk_user); - if ($res > 0 && !empty($recipient->email)) $to = $recipient->email; - else { - $errorsMsg[] = "Failed to load recipient"; - $error++; - } + // Recipient + $recipient = new User($this->db); + $res = $recipient->fetch($actionCommReminder->fk_user); + if ($res > 0 && !empty($recipient->email)) $to = $recipient->email; + else { + $errorsMsg[] = "Failed to load recipient"; + $error++; + } - // Sender - $from = $conf->global->MAIN_MAIL_EMAIL_FROM; - if (empty($from)) { - $errorsMsg[] = "Failed to load recipient"; - $error++; - } + // Sender + $from = $conf->global->MAIN_MAIL_EMAIL_FROM; + if (empty($from)) { + $errorsMsg[] = "Failed to load recipient"; + $error++; + } - // Errors Recipient - $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO; + // Errors Recipient + $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO; - // Mail Creation - $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', ''); + // Mail Creation + $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', ''); - // Sending Mail - if ($cMailFile->sendfile()) - { - $actionCommReminder->status = $actionCommReminder::STATUS_DONE; - $res = $actionCommReminder->update($user); - if ($res < 0) - { - $errorsMsg[] = "Failed to update status of ActionComm Reminder"; - $error++; - break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first. - } else { - $nbMailSend++; - } - } else { - $errorsMsg[] = $cMailFile->error.' : '.$to; - $error++; - } - } else { - $error++; - } - } - } - } else { - $error++; - } + // Sending Mail + if ($cMailFile->sendfile()) + { + $actionCommReminder->status = $actionCommReminder::STATUS_DONE; + $res = $actionCommReminder->update($user); + if ($res < 0) + { + $errorsMsg[] = "Failed to update status of ActionComm Reminder"; + $error++; + break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first. + } else { + $nbMailSend++; + } + } else { + $errorsMsg[] = $cMailFile->error.' : '.$to; + $error++; + } + } else { + $error++; + } + } + } + } else { + $error++; + } - if (!$error) - { - // Delete also very old past events (we do not keep more than 1 month record in past) - $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; + if (!$error) + { + // Delete also very old past events (we do not keep more than 1 month record in past) + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'"; - $resql = $this->db->query($sql); + $resql = $this->db->query($sql); - if (!$resql) { - $errorsMsg[] = 'Failed to delete old reminders'; - //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind. - } - } + if (!$resql) { + $errorsMsg[] = 'Failed to delete old reminders'; + //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind. + } + } - if (!$error) { - $this->output = 'Nb of emails sent : '.$nbMailSend; - $this->db->commit(); - return 0; - } - else { - $this->db->rollback(); - $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error; - return $error; - } - } + if (!$error) { + $this->output = 'Nb of emails sent : '.$nbMailSend; + $this->db->commit(); + return 0; + } + else { + $this->db->rollback(); + $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error; + return $error; + } + } /** * Udpate the percent value of a event with the given id diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 64c24c9c8e8..0c6ca3c1acc 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -150,7 +150,7 @@ if (GETPOST("viewlist", 'alpha') || $action == 'show_list') $param .= '&'.$key.'='.urlencode($val); } } - if (! preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list'; + if (!preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list'; //print $param; header("Location: ".DOL_URL_ROOT.'/comm/action/list.php?'.$param); exit; @@ -636,518 +636,518 @@ dol_syslog("comm/action/index.php", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); - $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import) - $i = 0; - while ($i < $num && $i < $MAXONSAMEPAGE) - { - $obj = $db->fetch_object($resql); + $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import) + $i = 0; + while ($i < $num && $i < $MAXONSAMEPAGE) + { + $obj = $db->fetch_object($resql); - // Discard auto action if option is on - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') - { - $i++; - continue; - } + // Discard auto action if option is on + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') + { + $i++; + continue; + } - // Create a new object action - $event = new ActionComm($db); + // Create a new object action + $event = new ActionComm($db); - $event->id = $obj->id; - $event->ref = $event->id; + $event->id = $obj->id; + $event->ref = $event->id; - $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin - $event->datef = $db->jdate($obj->datep2); + $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin + $event->datef = $db->jdate($obj->datep2); //var_dump($obj->datep); - //var_dump($event->datep); + //var_dump($event->datep); - $event->type_code = $obj->type_code; - $event->type_label = $obj->type_label; - $event->type_color = $obj->type_color; + $event->type_code = $obj->type_code; + $event->type_label = $obj->type_label; + $event->type_color = $obj->type_color; - $event->libelle = $obj->label; // deprecated - $event->label = $obj->label; - $event->percentage = $obj->percent; - $event->authorid = $obj->fk_user_author; // user id of creator - $event->userownerid = $obj->fk_user_action; // user id of owner - $event->fetch_userassigned(); // This load $event->userassigned - $event->priority = $obj->priority; - $event->fulldayevent = $obj->fulldayevent; - $event->location = $obj->location; - $event->transparency = $obj->transparency; - $event->fk_element = $obj->fk_element; - $event->elementtype = $obj->elementtype; + $event->libelle = $obj->label; // deprecated + $event->label = $obj->label; + $event->percentage = $obj->percent; + $event->authorid = $obj->fk_user_author; // user id of creator + $event->userownerid = $obj->fk_user_action; // user id of owner + $event->fetch_userassigned(); // This load $event->userassigned + $event->priority = $obj->priority; + $event->fulldayevent = $obj->fulldayevent; + $event->location = $obj->location; + $event->transparency = $obj->transparency; + $event->fk_element = $obj->fk_element; + $event->elementtype = $obj->elementtype; - $event->fk_project = $obj->fk_project; + $event->fk_project = $obj->fk_project; - $event->thirdparty_id = $obj->fk_soc; - $event->contact_id = $obj->fk_contact; + $event->thirdparty_id = $obj->fk_soc; + $event->contact_id = $obj->fk_contact; - // Defined date_start_in_calendar and date_end_in_calendar property - // They are date start and end of action but modified to not be outside calendar view. - $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; - // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { - $event->ponctuel = 1; - } + // Defined date_start_in_calendar and date_end_in_calendar property + // They are date start and end of action but modified to not be outside calendar view. + $event->date_start_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; + else $event->date_end_in_calendar = $event->datep; + // Define ponctual property + if ($event->date_start_in_calendar == $event->date_end_in_calendar) + { + $event->ponctuel = 1; + } - // Check values - if ($event->date_end_in_calendar < $firstdaytoshow || - $event->date_start_in_calendar >= $lastdaytoshow) - { - // This record is out of visible range - } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + // Check values + if ($event->date_end_in_calendar < $firstdaytoshow || + $event->date_start_in_calendar >= $lastdaytoshow) + { + // This record is out of visible range + } else { + if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; + if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); - // Add an entry in actionarray for each day - $daycursor = $event->date_start_in_calendar; - $annee = date('Y', $daycursor); - $mois = date('m', $daycursor); - $jour = date('d', $daycursor); + // Add an entry in actionarray for each day + $daycursor = $event->date_start_in_calendar; + $annee = date('Y', $daycursor); + $mois = date('m', $daycursor); + $jour = date('d', $daycursor); - // Loop on each day covered by action to prepare an index to show on calendar - $loop = true; $j = 0; - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; + // Loop on each day covered by action to prepare an index to show on calendar + $loop = true; $j = 0; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + do { + //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; - $eventarray[$daykey][] = $event; - $j++; + $eventarray[$daykey][] = $event; + $j++; - $daykey += 60 * 60 * 24; - if ($daykey > $event->date_end_in_calendar) $loop = false; - } while ($loop); + $daykey += 60 * 60 * 24; + if ($daykey > $event->date_end_in_calendar) $loop = false; + } while ($loop); - //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); - //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array
'; - } - $i++; - } + //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); + //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array
'; + } + $i++; + } } else { - dol_print_error($db); + dol_print_error($db); } // Complete $eventarray with birthdates if ($showbirthday) { - // Add events in array - $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; - $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; - $sql .= " AND sp.entity IN (".getEntity('socpeople').")"; - if ($action == 'show_day') - { - $sql .= ' AND MONTH(birthday) = '.$month; - $sql .= ' AND DAY(birthday) = '.$day; - } else { - $sql .= ' AND MONTH(birthday) = '.$month; - } - $sql .= ' ORDER BY birthday'; + // Add events in array + $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; + $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; + $sql .= " AND sp.entity IN (".getEntity('socpeople').")"; + if ($action == 'show_day') + { + $sql .= ' AND MONTH(birthday) = '.$month; + $sql .= ' AND DAY(birthday) = '.$day; + } else { + $sql .= ' AND MONTH(birthday) = '.$month; + } + $sql .= ' ORDER BY birthday'; - dol_syslog("comm/action/index.php", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - $event = new ActionComm($db); + dol_syslog("comm/action/index.php", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $event = new ActionComm($db); - $event->id = $obj->rowid; // We put contact id in action id for birthdays events - $event->ref = $event->id; + $event->id = $obj->rowid; // We put contact id in action id for birthdays events + $event->ref = $event->id; - $datebirth = dol_stringtotime($obj->birthday, 1); - //print 'ee'.$obj->birthday.'-'.$datebirth; - $datearray = dol_getdate($datebirth, true); - $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output - $event->datef = $event->datep; - $event->type_code = 'BIRTHDAY'; - $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); - $event->percentage = 100; - $event->fulldayevent = 1; + $datebirth = dol_stringtotime($obj->birthday, 1); + //print 'ee'.$obj->birthday.'-'.$datebirth; + $datearray = dol_getdate($datebirth, true); + $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output + $event->datef = $event->datep; + $event->type_code = 'BIRTHDAY'; + $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); + $event->percentage = 100; + $event->fulldayevent = 1; - $event->date_start_in_calendar = $event->datep; - $event->date_end_in_calendar = $event->datef; - $event->ponctuel = 0; + $event->date_start_in_calendar = $event->datep; + $event->date_end_in_calendar = $event->datef; + $event->ponctuel = 0; - // Add an entry in actionarray for each day - $daycursor = $event->date_start_in_calendar; - $annee = date('Y', $daycursor); - $mois = date('m', $daycursor); - $jour = date('d', $daycursor); + // Add an entry in actionarray for each day + $daycursor = $event->date_start_in_calendar; + $annee = date('Y', $daycursor); + $mois = date('m', $daycursor); + $jour = date('d', $daycursor); - $loop = true; - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - $eventarray[$daykey][] = $event; - $daykey += 60 * 60 * 24; - if ($daykey > $event->date_end_in_calendar) $loop = false; - } while ($loop); - $i++; - } - } else { - dol_print_error($db); - } + $loop = true; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + do { + $eventarray[$daykey][] = $event; + $daykey += 60 * 60 * 24; + if ($daykey > $event->date_end_in_calendar) $loop = false; + } while ($loop); + $i++; + } + } else { + dol_print_error($db); + } } if ($conf->global->AGENDA_SHOW_HOLIDAYS) { - $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status"; - $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE u.rowid = x.fk_user"; - $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user) - $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved) + $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status"; + $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE u.rowid = x.fk_user"; + $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user) + $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved) - if ($action == 'show_day') - { - // Request only leaves for the current selected day - $sql .= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin"; - } elseif ($action == 'show_week') - { - // TODO: Add filter to reduce database request - } elseif ($action == 'show_month') - { - // TODO: Add filter to reduce database request - } + if ($action == 'show_day') + { + // Request only leaves for the current selected day + $sql .= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin"; + } elseif ($action == 'show_week') + { + // TODO: Add filter to reduce database request + } elseif ($action == 'show_month') + { + // TODO: Add filter to reduce database request + } - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); + while ($i < $num) + { + $obj = $db->fetch_object($resql); - $dateStartArray = dol_getdate(dol_stringtotime($obj->date_start, 1), true); - $dateEndArray = dol_getdate(dol_stringtotime($obj->date_end, 1), true); + $dateStartArray = dol_getdate(dol_stringtotime($obj->date_start, 1), true); + $dateEndArray = dol_getdate(dol_stringtotime($obj->date_end, 1), true); - $event = new ActionComm($db); + $event = new ActionComm($db); - // Need the id of the leave object for link to it - $event->id = $obj->rowid; - $event->ref = $event->id; + // Need the id of the leave object for link to it + $event->id = $obj->rowid; + $event->ref = $event->id; - $event->type_code = 'HOLIDAY'; - $event->datep = dol_mktime(0, 0, 0, $dateStartArray['mon'], $dateStartArray['mday'], $dateStartArray['year'], true); - $event->datef = dol_mktime(0, 0, 0, $dateEndArray['mon'], $dateEndArray['mday'], $dateEndArray['year'], true); - $event->date_start_in_calendar = $event->datep; - $event->date_end_in_calendar = $event->datef; + $event->type_code = 'HOLIDAY'; + $event->datep = dol_mktime(0, 0, 0, $dateStartArray['mon'], $dateStartArray['mday'], $dateStartArray['year'], true); + $event->datef = dol_mktime(0, 0, 0, $dateEndArray['mon'], $dateEndArray['mday'], $dateEndArray['year'], true); + $event->date_start_in_calendar = $event->datep; + $event->date_end_in_calendar = $event->datef; - if ($obj->status == 3) - { - // Show no symbol for leave with state "leave approved" - $event->percentage = -1; - } elseif ($obj->status == 2) - { - // Show TO-DO symbol for leave with state "leave wait for approval" - $event->percentage = 0; - } + if ($obj->status == 3) + { + // Show no symbol for leave with state "leave approved" + $event->percentage = -1; + } elseif ($obj->status == 2) + { + // Show TO-DO symbol for leave with state "leave wait for approval" + $event->percentage = 0; + } - if ($obj->halfday == 1) - { - $event->label = $obj->lastname.' ('.$langs->trans("Morning").')'; - } elseif ($obj->halfday == -1) - { - $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')'; - } else { - $event->label = $obj->lastname; - } + if ($obj->halfday == 1) + { + $event->label = $obj->lastname.' ('.$langs->trans("Morning").')'; + } elseif ($obj->halfday == -1) + { + $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')'; + } else { + $event->label = $obj->lastname; + } - $annee = date('Y', $event->date_start_in_calendar); - $mois = date('m', $event->date_start_in_calendar); - $jour = date('d', $event->date_start_in_calendar); - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + $annee = date('Y', $event->date_start_in_calendar); + $mois = date('m', $event->date_start_in_calendar); + $jour = date('d', $event->date_start_in_calendar); + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - $eventarray[$daykey][] = $event; + do { + $eventarray[$daykey][] = $event; - $daykey += 60 * 60 * 24; - } while ($daykey <= $event->date_end_in_calendar); + $daykey += 60 * 60 * 24; + } while ($daykey <= $event->date_end_in_calendar); - $i++; - } - } + $i++; + } + } } // Complete $eventarray with external import Ical if (count($listofextcals)) { - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; - foreach ($listofextcals as $extcal) - { - $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics - $namecal = $extcal['name']; - $offsettz = $extcal['offsettz']; - $colorcal = $extcal['color']; - $buggedfile = $extcal['buggedfile']; - //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile; - $ical = new ICal(); - $ical->parse($url); + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; + foreach ($listofextcals as $extcal) + { + $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics + $namecal = $extcal['name']; + $offsettz = $extcal['offsettz']; + $colorcal = $extcal['color']; + $buggedfile = $extcal['buggedfile']; + //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile; + $ical = new ICal(); + $ical->parse($url); - // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ... - //var_dump($ical->cal); exit; - $icalevents = array(); - if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] - if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] + // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ... + //var_dump($ical->cal); exit; + $icalevents = array(); + if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] + if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] - if (count($icalevents) > 0) - { - // Duplicate all repeatable events into new entries - $moreicalevents = array(); - foreach ($icalevents as $icalevent) - { - if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event - { - //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; - //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); - if ($icalevent['DTSTART;VALUE=DATE']) //fullday event - { - $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); - $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day - } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) - { - $datecurstart = $icalevent['DTSTART']['unixtime']; - $datecurend = $icalevent['DTEND']['unixtime']; - if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) - { - //var_dump($ical->cal); - $tmpcurstart = $datecurstart; - $tmpcurend = $datecurend; - $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; - $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; - //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']); - // Edit datecurstart and datecurend - if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; - if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; - } - // datecurstart and datecurend are now GMT date - //var_dump($datecurstart); var_dump($datecurend); exit; - } else { - // Not a recongized record - dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR); - continue; - } - //print 'xx'.$datecurstart;exit; + if (count($icalevents) > 0) + { + // Duplicate all repeatable events into new entries + $moreicalevents = array(); + foreach ($icalevents as $icalevent) + { + if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event + { + //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; + //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); + if ($icalevent['DTSTART;VALUE=DATE']) //fullday event + { + $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); + $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day + } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) + { + $datecurstart = $icalevent['DTSTART']['unixtime']; + $datecurend = $icalevent['DTEND']['unixtime']; + if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) + { + //var_dump($ical->cal); + $tmpcurstart = $datecurstart; + $tmpcurend = $datecurend; + $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; + $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; + //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']); + // Edit datecurstart and datecurend + if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + } + // datecurstart and datecurend are now GMT date + //var_dump($datecurstart); var_dump($datecurend); exit; + } else { + // Not a recongized record + dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR); + continue; + } + //print 'xx'.$datecurstart;exit; - $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']); - $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); - $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT']; - if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show - if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show + $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']); + $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); + $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT']; + if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show + if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show - $numofevent = 0; - while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) - { - if ($datecurend >= $firstdaytoshow) // We add event - { - $newevent = $icalevent; - unset($newevent['RRULE']); - if ($icalevent['DTSTART;VALUE=DATE']) - { - $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d'); - $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d'); - } else { - $newevent['DTSTART'] = $datecurstart; - $newevent['DTEND'] = $datecurend; - } - $moreicalevents[] = $newevent; - } - // Jump on next occurence - $numofevent++; - $savdatecurstart = $datecurstart; - if ($icalevent['RRULE']['FREQ'] == 'DAILY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'd'); - } - if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); - } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'm'); - } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'y'); - } - // Test to avoid infinite loop ($datecurstart must increase) - if ($savdatecurstart >= $datecurstart) - { - dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR); - $datecurstart += 3600 * 24 * 7; - $datecurend += 3600 * 24 * 7; - } - } - } - } - $icalevents = array_merge($icalevents, $moreicalevents); + $numofevent = 0; + while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) + { + if ($datecurend >= $firstdaytoshow) // We add event + { + $newevent = $icalevent; + unset($newevent['RRULE']); + if ($icalevent['DTSTART;VALUE=DATE']) + { + $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d'); + $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d'); + } else { + $newevent['DTSTART'] = $datecurstart; + $newevent['DTEND'] = $datecurend; + } + $moreicalevents[] = $newevent; + } + // Jump on next occurence + $numofevent++; + $savdatecurstart = $datecurstart; + if ($icalevent['RRULE']['FREQ'] == 'DAILY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'd'); + } + if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); + } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'm'); + } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'y'); + } + // Test to avoid infinite loop ($datecurstart must increase) + if ($savdatecurstart >= $datecurstart) + { + dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR); + $datecurstart += 3600 * 24 * 7; + $datecurend += 3600 * 24 * 7; + } + } + } + } + $icalevents = array_merge($icalevents, $moreicalevents); - // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray - foreach ($icalevents as $icalevent) - { - //var_dump($icalevent); + // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray + foreach ($icalevents as $icalevent) + { + //var_dump($icalevent); - //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).'
';exit; - if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. + //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).'
';exit; + if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. - // Create a new object action - $event = new ActionComm($db); - $addevent = false; - if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event - { - // For full day events, date are also GMT but they wont but converted using tz during output - $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); - $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day - //print 'x'.$datestart.'-'.$dateend;exit; - //print dol_print_date($dateend,'dayhour','gmt'); - $event->fulldayevent = 1; - $addevent = true; - } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) - { - $datestart = $icalevent['DTSTART']; - $dateend = $icalevent['DTEND']; + // Create a new object action + $event = new ActionComm($db); + $addevent = false; + if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event + { + // For full day events, date are also GMT but they wont but converted using tz during output + $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); + $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day + //print 'x'.$datestart.'-'.$dateend;exit; + //print dol_print_date($dateend,'dayhour','gmt'); + $event->fulldayevent = 1; + $addevent = true; + } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) + { + $datestart = $icalevent['DTSTART']; + $dateend = $icalevent['DTEND']; - $datestart += +($offsettz * 3600); - $dateend += +($offsettz * 3600); + $datestart += +($offsettz * 3600); + $dateend += +($offsettz * 3600); - $addevent = true; - //var_dump($offsettz); - //var_dump(dol_print_date($datestart, 'dayhour', 'gmt')); - } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind) - { - $datestart = $icalevent['DTSTART']['unixtime']; - $dateend = $icalevent['DTEND']['unixtime']; + $addevent = true; + //var_dump($offsettz); + //var_dump(dol_print_date($datestart, 'dayhour', 'gmt')); + } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind) + { + $datestart = $icalevent['DTSTART']['unixtime']; + $dateend = $icalevent['DTEND']['unixtime']; - $datestart += +($offsettz * 3600); - $dateend += +($offsettz * 3600); + $datestart += +($offsettz * 3600); + $dateend += +($offsettz * 3600); - // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight' - if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 - { - // TODO - } - // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind) - if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer - { - $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID'])); - $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID'])); - $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs); - $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze); + // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight' + if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 + { + // TODO + } + // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind) + if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer + { + $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID'])); + $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID'])); + $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs); + $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze); $tmps = -1 * $localtzs->getOffset($localdts); $tmpe = -1 * $localtze->getOffset($localdte); $datestart += $tmps; $dateend += $tmpe; //var_dump($datestart); - } - $addevent = true; - } + } + $addevent = true; + } - if ($addevent) - { - $event->id = $icalevent['UID']; - $event->ref = $event->id; + if ($addevent) + { + $event->id = $icalevent['UID']; + $event->ref = $event->id; - $userId = $userstatic->findUserIdByEmail($namecal); - if (!empty($userId) && $userId > 0) - { - $event->userassigned[$userId] = $userId; - $event->percentage = -1; - } - else { - $event->type_code = "ICALEVENT"; - } + $userId = $userstatic->findUserIdByEmail($namecal); + if (!empty($userId) && $userId > 0) + { + $event->userassigned[$userId] = $userId; + $event->percentage = -1; + } + else { + $event->type_code = "ICALEVENT"; + } - $event->icalname = $namecal; - $event->icalcolor = $colorcal; - $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. - $event->datep = $datestart + $usertime; - $event->datef = $dateend + $usertime; + $event->icalname = $namecal; + $event->icalcolor = $colorcal; + $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. + $event->datep = $datestart + $usertime; + $event->datef = $dateend + $usertime; - if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; - elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); - else $event->label = $langs->trans("ExtSiteNoLabel"); + if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; + elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); + else $event->label = $langs->trans("ExtSiteNoLabel"); - // Priority (see https://www.kanzaki.com/docs/ical/priority.html) - // LOW = 0 to 4 - // MEDIUM = 5 - // HIGH = 6 to 9 - if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY']; + // Priority (see https://www.kanzaki.com/docs/ical/priority.html) + // LOW = 0 to 4 + // MEDIUM = 5 + // HIGH = 6 to 9 + if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY']; - // Transparency (see https://www.kanzaki.com/docs/ical/transp.html) - if ($icalevent['TRANSP']) - { - if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free - if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy + // Transparency (see https://www.kanzaki.com/docs/ical/transp.html) + if ($icalevent['TRANSP']) + { + if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free + if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy - // TODO: MS outlook states - // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free - // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:OPAQUE => Work another place - // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE => With reservations - // X-MICROSOFT-CDO-BUSYSTATUS:BUSY + TRANSP:OPAQUE => Busy - // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site - } + // TODO: MS outlook states + // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free + // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:OPAQUE => Work another place + // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE => With reservations + // X-MICROSOFT-CDO-BUSYSTATUS:BUSY + TRANSP:OPAQUE => Busy + // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site + } - if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION']; + if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION']; - $event->date_start_in_calendar = $event->datep; + $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; + else $event->date_end_in_calendar = $event->datep; - // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { - $event->ponctuel = 1; - //print 'x'.$datestart.'-'.$dateend;exit; - } + // Define ponctual property + if ($event->date_start_in_calendar == $event->date_end_in_calendar) + { + $event->ponctuel = 1; + //print 'x'.$datestart.'-'.$dateend;exit; + } - // Add event into $eventarray if date range are ok. - if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) - { - //print 'x'.$datestart.'-'.$dateend;exit; - //print 'x'.$datestart.'-'.$dateend;exit; - //print 'x'.$datestart.'-'.$dateend;exit; - // This record is out of visible range - } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + // Add event into $eventarray if date range are ok. + if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) + { + //print 'x'.$datestart.'-'.$dateend;exit; + //print 'x'.$datestart.'-'.$dateend;exit; + //print 'x'.$datestart.'-'.$dateend;exit; + // This record is out of visible range + } else { + if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; + if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); - // Add an entry in actionarray for each day - $daycursor = $event->date_start_in_calendar; - $annee = date('Y', $daycursor); - $mois = date('m', $daycursor); - $jour = date('d', $daycursor); + // Add an entry in actionarray for each day + $daycursor = $event->date_start_in_calendar; + $annee = date('Y', $daycursor); + $mois = date('m', $daycursor); + $jour = date('d', $daycursor); - // Loop on each day covered by action to prepare an index to show on calendar - $loop = true; $j = 0; - // daykey must be date that represent day box in calendar so must be a user time - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0); - do { - //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; - $eventarray[$daykey][] = $event; - $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day - if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false; - } while ($loop); - } - } - } - } - } + // Loop on each day covered by action to prepare an index to show on calendar + $loop = true; $j = 0; + // daykey must be date that represent day box in calendar so must be a user time + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0); + do { + //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; + $eventarray[$daykey][] = $event; + $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day + if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false; + } while ($loop); + } + } + } + } + } } @@ -1192,48 +1192,48 @@ print $s; if (empty($action) || $action == 'show_month') // View by month { - $newparam = $param; // newparam is for birthday links - $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done - $newparam = preg_replace('/action=show_month&?/i', '', $newparam); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam .= '&viewcal=1'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewcal=1'; - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - print ''; - print ' '; + print '
'; + print '
'; + print ' '; // Column title of weeks numbers echo ' '; - $i = 0; - while ($i < 7) - { - print ' '."\n"; - $i++; - } - echo ' '."\n"; + $i = 0; + while ($i < 7) + { + print ' '."\n"; + $i++; + } + echo ' '."\n"; - $todayarray = dol_getdate($now, 'fast'); - $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); + $todayarray = dol_getdate($now, 'fast'); + $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); - // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) - //var_dump($eventarray); - for ($iter_week = 0; $iter_week < 6; $iter_week++) { - echo " \n"; + // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) + //var_dump($eventarray); + for ($iter_week = 0; $iter_week < 6; $iter_week++) { + echo " \n"; // Get date of the current day, format 'yyyy-mm-dd' if ($tmpday <= 0) // If number of the current day is in previous month { @@ -1252,130 +1252,130 @@ if (empty($action) || $action == 'show_month') // View by month // Show the week number, and define column width echo ' '; - for ($iter_day = 0; $iter_day < 7; $iter_day++) { - if ($tmpday <= 0) { - /* Show days before the beginning of the current month (previous month) */ - $style = 'cal_other_month cal_past'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; - echo ' \n"; - } elseif ($tmpday <= $max_day_in_month) { - /* Show days of the current month */ - $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); - $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_current_month_right'; - $today = 0; - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; - if ($today) $style = 'cal_today'; - if ($curtime < $todaytms) $style .= ' cal_past'; + for ($iter_day = 0; $iter_day < 7; $iter_day++) { + if ($tmpday <= 0) { + /* Show days before the beginning of the current month (previous month) */ + $style = 'cal_other_month cal_past'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; + echo ' \n"; + } elseif ($tmpday <= $max_day_in_month) { + /* Show days of the current month */ + $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); + $style = 'cal_current_month'; + if ($iter_day == 6) $style .= ' cal_current_month_right'; + $today = 0; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; + if ($today) $style = 'cal_today'; + if ($curtime < $todaytms) $style .= ' cal_past'; //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style); - echo ' \n"; - } else { - /* Show days after the current month (next month) */ - $style = 'cal_other_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; - echo ' \n"; - } - $tmpday++; - } - echo " \n"; - } - print "
#'; - $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); - if (!empty($conf->dol_optimize_smallscreen)) - { - $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin'); - print $langs->trans($labelshort[$numdayinweek]); - } else print $langs->trans("Day".$numdayinweek); - print '
'; + $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); + if (!empty($conf->dol_optimize_smallscreen)) + { + $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin'); + print $langs->trans($labelshort[$numdayinweek]); + } else print $langs->trans("Day".$numdayinweek); + print '
'.$numweek0.''; - show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo " '; + show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); + echo " '; - show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo " '; - show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo "
\n"; + echo ' '; + show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); + echo " \n"; + } else { + /* Show days after the current month (next month) */ + $style = 'cal_other_month'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; + echo ' '; + show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); + echo "\n"; + } + $tmpday++; + } + echo " \n"; + } + print "\n"; print '
'; print ''; print ''; print ''; } elseif ($action == 'show_week') { - // View by week - $newparam = $param; // newparam is for birthday links - $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done - $newparam = preg_replace('/action=show_month&?/i', '', $newparam); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam .= '&viewweek=1'; + // View by week + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewweek=1'; - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - print ''; - print ' '; - $i = 0; - while ($i < 7) { - echo ' \n"; - $i++; - } - echo " \n"; + print '
'; + print '
'.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))."
'; + print ' '; + $i = 0; + while ($i < 7) { + echo ' \n"; + $i++; + } + echo " \n"; - echo " \n"; + echo " \n"; - for ($iter_day = 0; $iter_day < 7; $iter_day++) { - // Show days of the current week + for ($iter_day = 0; $iter_day < 7; $iter_day++) { + // Show days of the current week $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); $tmparray = dol_getdate($curtime, true); $tmpday = $tmparray['mday']; $tmpmonth = $tmparray['mon']; $tmpyear = $tmparray['year']; - $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; - $today = 0; - $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; - if ($today) $style = 'cal_today'; + $style = 'cal_current_month'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; + $today = 0; + $todayarray = dol_getdate($now, 'fast'); + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; + if ($today) $style = 'cal_today'; - echo ' \n"; - } - echo " \n"; + echo ' \n"; + } + echo " \n"; - print "
'.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))."
'; - show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); - echo "
'; + show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); + echo "
\n"; + print "\n"; print '
'; - echo ''; - echo ''; - echo ''; + echo ''; + echo ''; + echo ''; } else // View by day { - $newparam = $param; // newparam is for birthday links - $newparam = preg_replace('/action=show_month&?/i', '', $newparam); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam); - $newparam .= '&viewday=1'; - // Code to show just one day - $style = 'cal_current_month cal_current_month_oneday'; - $today = 0; - $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; - //if ($today) $style='cal_today'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam); + $newparam .= '&viewday=1'; + // Code to show just one day + $style = 'cal_current_month cal_current_month_oneday'; + $today = 0; + $todayarray = dol_getdate($now, 'fast'); + if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; + //if ($today) $style='cal_today'; - $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); - $arraytimestamp = dol_getdate($timestamp); + $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); + $arraytimestamp = dol_getdate($timestamp); - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - echo ''; + print '
'; + echo '
'; - echo ' '; - echo ' \n"; - echo " \n"; + echo ' '; + echo ' \n"; + echo " \n"; - /* + /* echo '
'; echo '
'; echo '
'; @@ -1460,401 +1460,401 @@ $db->close(); */ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint = 0, $maxnbofchar = 16, $newparam = '', $showinfo = 0, $minheight = 60, $nonew = 0) { - global $user, $conf, $langs; - global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form - global $theme_datacolor; - global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; + global $user, $conf, $langs; + global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form + global $theme_datacolor; + global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; - $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); - print "\n"; + print "\n"; - // Line with title of day - $curtime = dol_mktime(0, 0, 0, $month, $day, $year); - print '
'."\n"; + // Line with title of day + $curtime = dol_mktime(0, 0, 0, $month, $day, $year); + print '
'."\n"; - if ($nonew <= 0) - { - print '
'; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) - { - $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; + if ($nonew <= 0) + { + print '
'; + if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) + { + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; - //$param='month='.$monthshown.'&year='.$year; - $hourminsec = '100000'; - print ''; - print img_picto($langs->trans("NewAction"), 'edit_add.png'); - print ''; - } - print '
'."\n"; - } + //$param='month='.$monthshown.'&year='.$year; + $hourminsec = '100000'; + print ''; + print img_picto($langs->trans("NewAction"), 'edit_add.png'); + print ''; + } + print '
'."\n"; + } - if ($nonew < 0) - { - print '
'; - return; - } + if ($nonew < 0) + { + print '
'; + return; + } - // Line with td contains all div of each events - print '
'; - print '
'; + // Line with td contains all div of each events + print '
'; + print '
'; - //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); - $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); - $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); + $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); + $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); - $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 - $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ... + $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 + $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ... //var_dump($colorindexused); - foreach ($eventarray as $daykey => $notused) - { - $annee = date('Y', $daykey); - $mois = date('m', $daykey); - $jour = date('d', $daykey); - if ($day == $jour && $month == $mois && $year == $annee) - { - foreach ($eventarray[$daykey] as $index => $event) - { - if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) - { - $keysofuserassigned = array_keys($event->userassigned); - $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); + foreach ($eventarray as $daykey => $notused) + { + $annee = date('Y', $daykey); + $mois = date('m', $daykey); + $jour = date('d', $daykey); + if ($day == $jour && $month == $mois && $year == $annee) + { + foreach ($eventarray[$daykey] as $index => $event) + { + if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) + { + $keysofuserassigned = array_keys($event->userassigned); + $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); - // Define $color (Hex string like '0088FF') and $cssclass of event - $color = -1; $cssclass = ''; $colorindex = -1; - if (in_array($user->id, $keysofuserassigned)) - { - $cssclass = 'family_mytasks'; + // Define $color (Hex string like '0088FF') and $cssclass of event + $color = -1; $cssclass = ''; $colorindex = -1; + if (in_array($user->id, $keysofuserassigned)) + { + $cssclass = 'family_mytasks'; - if (empty($cacheusers[$event->userownerid])) - { - $newuser = new User($db); - $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid] = $newuser; - } - //var_dump($cacheusers[$event->userownerid]->color); + if (empty($cacheusers[$event->userownerid])) + { + $newuser = new User($db); + $newuser->fetch($event->userownerid); + $cacheusers[$event->userownerid] = $newuser; + } + //var_dump($cacheusers[$event->userownerid]->color); - // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file - { - $numical++; - if (!empty($event->icalname)) { - if (!isset($numicals[dol_string_nospecial($event->icalname)])) { - $numicals[dol_string_nospecial($event->icalname)] = 0; - } - $numicals[dol_string_nospecial($event->icalname)]++; - } + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; + } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file + { + $numical++; + if (!empty($event->icalname)) { + if (!isset($numicals[dol_string_nospecial($event->icalname)])) { + $numicals[dol_string_nospecial($event->icalname)] = 0; + } + $numicals[dol_string_nospecial($event->icalname)]++; + } - $color = ($event->icalcolor ? $event->icalcolor : -1); - $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - } elseif ($event->type_code == 'BIRTHDAY') - { - $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); - } else { - $numother++; - $color = ($event->icalcolor ? $event->icalcolor : -1); - $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); + } elseif ($event->type_code == 'BIRTHDAY') + { + $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + } else { + $numother++; + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - if (empty($cacheusers[$event->userownerid])) - { - $newuser = new User($db); - $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid] = $newuser; - } - //var_dump($cacheusers[$event->userownerid]->color); + if (empty($cacheusers[$event->userownerid])) + { + $newuser = new User($db); + $newuser->fetch($event->userownerid); + $cacheusers[$event->userownerid] = $newuser; + } + //var_dump($cacheusers[$event->userownerid]->color); - // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - } + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; + } - if ($color < 0) // Color was not set on user card. Set color according to color index. - { - // Define color index if not yet defined - $idusertouse = ($event->userownerid ? $event->userownerid : 0); - if (isset($colorindexused[$idusertouse])) - { - $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user - } else { - $colorindex = $nextindextouse; - $colorindexused[$idusertouse] = $colorindex; - if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color - } - //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
'; - // Define color - $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); - } - $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd; + if ($color < 0) // Color was not set on user card. Set color according to color index. + { + // Define color index if not yet defined + $idusertouse = ($event->userownerid ? $event->userownerid : 0); + if (isset($colorindexused[$idusertouse])) + { + $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user + } else { + $colorindex = $nextindextouse; + $colorindexused[$idusertouse] = $colorindex; + if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color + } + //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
'; + // Define color + $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + } + $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd; - // Defined style to disable drag and drop feature - if ($event->type_code == 'AC_OTH_AUTO') - { - $cssclass .= " unmovable"; - } elseif ($event->type_code == 'ICALEVENT') - { - $cssclass .= " unmovable"; - } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) { - $tmpyearend = date('Y', $event->date_end_in_calendar); - $tmpmonthend = date('m', $event->date_end_in_calendar); - $tmpdayend = date('d', $event->date_end_in_calendar); - if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) - { - $cssclass .= " unmovable"; - } - } else { - if ($user->rights->agenda->allactions->create || - (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) - { - $cssclass .= " movable cursormove"; - } else { - $cssclass .= " unmovable"; - } - } + // Defined style to disable drag and drop feature + if ($event->type_code == 'AC_OTH_AUTO') + { + $cssclass .= " unmovable"; + } elseif ($event->type_code == 'ICALEVENT') + { + $cssclass .= " unmovable"; + } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) { + $tmpyearend = date('Y', $event->date_end_in_calendar); + $tmpmonthend = date('m', $event->date_end_in_calendar); + $tmpdayend = date('d', $event->date_end_in_calendar); + if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) + { + $cssclass .= " unmovable"; + } + } else { + if ($user->rights->agenda->allactions->create || + (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) + { + $cssclass .= " movable cursormove"; + } else { + $cssclass .= " unmovable"; + } + } - $h = ''; $nowrapontd = 1; - if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } - if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } + $h = ''; $nowrapontd = 1; + if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } + if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } - // Show rect of event - print "\n"; - print ''."\n"; - print '
'; + // Show rect of event + print "\n"; + print ''."\n"; + print '
'; - //var_dump($event->userassigned); - //var_dump($event->transparency); - print '
'.$langs->trans("Day".$arraytimestamp['wday'])."
'.$langs->trans("Day".$arraytimestamp['wday'])."
'; - print ''; - print ''; + // Status - Percent + $withstatus = 0; + if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') + { + $withstatus = 1; + if ($event->percentage >= 0) $withstatus = 2; + } + print '
'; + //var_dump($event->userassigned); + //var_dump($event->transparency); + print ''; + print ''; + print ''; - // Status - Percent - $withstatus = 0; - if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') - { - $withstatus = 1; - if ($event->percentage >= 0) $withstatus = 2; - } - print '
'; - $daterange = ''; + $daterange = ''; - if ($event->type_code == 'BIRTHDAY') // It's a birthday - { - print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact'); - } elseif ($event->type_code == 'HOLIDAY') - { - print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'holiday', 'user'); - } elseif ($event->type_code != 'BIRTHDAY' && $event->type_code != 'HOLIDAY') - { - // Picto - if (empty($event->fulldayevent)) - { - //print $event->getNomUrl(2).' '; - } + if ($event->type_code == 'BIRTHDAY') // It's a birthday + { + print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact'); + } elseif ($event->type_code == 'HOLIDAY') + { + print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'holiday', 'user'); + } elseif ($event->type_code != 'BIRTHDAY' && $event->type_code != 'HOLIDAY') + { + // Picto + if (empty($event->fulldayevent)) + { + //print $event->getNomUrl(2).' '; + } - // Date - if (empty($event->fulldayevent)) - { - // Show hours (start ... end) - $tmpyearstart = date('Y', $event->date_start_in_calendar); - $tmpmonthstart = date('m', $event->date_start_in_calendar); - $tmpdaystart = date('d', $event->date_start_in_calendar); - $tmpyearend = date('Y', $event->date_end_in_calendar); - $tmpmonthend = date('m', $event->date_end_in_calendar); - $tmpdayend = date('d', $event->date_end_in_calendar); - // Hour start - if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) - { - $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) - $daterange .= '-'; - //else - //print '...'; - } - } - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) - { - $daterange .= '...'; - } - } - // Hour end - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) - $daterange .= dol_print_date($event->date_end_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user - } - } else { - if ($showinfo) - { - print $langs->trans("EventOnFullDay")."
\n"; - } - } + // Date + if (empty($event->fulldayevent)) + { + // Show hours (start ... end) + $tmpyearstart = date('Y', $event->date_start_in_calendar); + $tmpmonthstart = date('m', $event->date_start_in_calendar); + $tmpdaystart = date('d', $event->date_start_in_calendar); + $tmpyearend = date('Y', $event->date_end_in_calendar); + $tmpmonthend = date('m', $event->date_end_in_calendar); + $tmpdayend = date('d', $event->date_end_in_calendar); + // Hour start + if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) + { + $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) + { + if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) + $daterange .= '-'; + //else + //print '...'; + } + } + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) + { + if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) + { + $daterange .= '...'; + } + } + // Hour end + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) + { + if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) + $daterange .= dol_print_date($event->date_end_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + } + } else { + if ($showinfo) + { + print $langs->trans("EventOnFullDay")."
\n"; + } + } - // Show title - $titletoshow = $daterange; - $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle); + // Show title + $titletoshow = $daterange; + $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle); - if ($event->type_code != 'ICALEVENT') { - $savlabel = $event->label ? $event->label : $event->libelle; - $event->label = $titletoshow; - $event->libelle = $titletoshow; - // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user. - $titletoshow = $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0); - $event->label = $savlabel; - $event->libelle = $savlabel; - } + if ($event->type_code != 'ICALEVENT') { + $savlabel = $event->label ? $event->label : $event->libelle; + $event->label = $titletoshow; + $event->libelle = $titletoshow; + // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user. + $titletoshow = $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0); + $event->label = $savlabel; + $event->libelle = $savlabel; + } - // Loop on each assigned user - $listofusertoshow = ''; - $posuserassigned = 0; - foreach ($event->userassigned as $tmpid => $tmpdata) - { - if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; - $posuserassigned++; - if (empty($cacheusers[$tmpid])) - { - $newuser = new User($db); - $newuser->fetch($tmpid); - $cacheusers[$tmpid] = $newuser; - } + // Loop on each assigned user + $listofusertoshow = ''; + $posuserassigned = 0; + foreach ($event->userassigned as $tmpid => $tmpdata) + { + if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; + $posuserassigned++; + if (empty($cacheusers[$tmpid])) + { + $newuser = new User($db); + $newuser->fetch($tmpid); + $cacheusers[$tmpid] = $newuser; + } - $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); - } + $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); + } - print $titletoshow; - print $listofusertoshow; + print $titletoshow; + print $listofusertoshow; - if ($event->type_code == 'ICALEVENT') print '
('.dol_trunc($event->icalname, $maxnbofchar).')'; + if ($event->type_code == 'ICALEVENT') print '
('.dol_trunc($event->icalname, $maxnbofchar).')'; - $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0)); - $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0)); + $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0)); + $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0)); - // If action related to company / contact - $linerelatedto = ''; - if ($thirdparty_id > 0) - { - if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) - { - $thirdparty = new Societe($db); - $thirdparty->fetch($thirdparty_id); - $cachethirdparties[$thirdparty_id] = $thirdparty; - } else $thirdparty = $cachethirdparties[$thirdparty_id]; - if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); - } - if (!empty($contact_id) && $contact_id > 0) - { - if (!is_object($cachecontacts[$contact_id])) - { - $contact = new Contact($db); - $contact->fetch($contact_id); - $cachecontacts[$contact_id] = $contact; - } else $contact = $cachecontacts[$contact_id]; - if ($linerelatedto) $linerelatedto .= ' '; - if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0); - } - if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if ($linerelatedto) $linerelatedto .= '
'; - $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); - } - if ($linerelatedto) print '
'.$linerelatedto; - } + // If action related to company / contact + $linerelatedto = ''; + if ($thirdparty_id > 0) + { + if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) + { + $thirdparty = new Societe($db); + $thirdparty->fetch($thirdparty_id); + $cachethirdparties[$thirdparty_id] = $thirdparty; + } else $thirdparty = $cachethirdparties[$thirdparty_id]; + if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); + } + if (!empty($contact_id) && $contact_id > 0) + { + if (!is_object($cachecontacts[$contact_id])) + { + $contact = new Contact($db); + $contact->fetch($contact_id); + $cachecontacts[$contact_id] = $contact; + } else $contact = $cachecontacts[$contact_id]; + if ($linerelatedto) $linerelatedto .= ' '; + if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0); + } + if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + if ($linerelatedto) $linerelatedto .= '
'; + $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); + } + if ($linerelatedto) print '
'.$linerelatedto; + } - // Show location - if ($showinfo) - { - if ($event->location) - { - print '
'; - print $langs->trans("Location").': '.$event->location; - } - } + // Show location + if ($showinfo) + { + if ($event->location) + { + print '
'; + print $langs->trans("Location").': '.$event->location; + } + } - print '
'; - if ($withstatus) print $event->getLibStatut(3, 1); - else print ' '; - print '
'; - print ''."\n"; - $i++; - } else { - print ''.img_picto("all", "1downarrow_selected.png").' ...'; - print ' +'.(count($eventarray[$daykey]) - $maxprint); - print ''; - break; - //$ok=false; // To avoid to show twice the link - } - } + print '
'; + if ($withstatus) print $event->getLibStatut(3, 1); + else print ' '; + print '
'; + print '
'."\n"; + $i++; + } else { + print ''.img_picto("all", "1downarrow_selected.png").' ...'; + print ' +'.(count($eventarray[$daykey]) - $maxprint); + print ''; + break; + //$ok=false; // To avoid to show twice the link + } + } - break; - } - } - if (!$i) print ' '; + break; + } + } + if (!$i) print ' '; - if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $i > $maxprint && $maxprint) - { - print '
'.img_picto("all", "1downarrow_selected.png").' +'.$langs->trans("More").'...
'; - //print ' +'.(count($eventarray[$daykey])-$maxprint); - print ''."\n"; - } + print ''."\n"; + } - print '
'; // td tr + print ''; // td tr - print ''; // table - print "\n"; + print ''; // table + print "\n"; } diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index db59fd5f942..7bce96633fc 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -1291,21 +1291,21 @@ if ($resql) foreach ($toselect as $checked) { if ($tmpproposal->fetch($checked)) { if ($tmpproposal->statut == 0) { - if ($tmpproposal->valid($user)){ - setEventMessage($tmpproposal->ref . " " . $langs->trans('PassedInOpenStatus'), 'mesgs'); + if ($tmpproposal->valid($user)) { + setEventMessage($tmpproposal->ref." ".$langs->trans('PassedInOpenStatus'), 'mesgs'); } else { setEventMessage($langs->trans('CantBeValidated'), 'errors'); $error++; } } else { - setEventMessage($tmpproposal->ref . " " . $langs->trans('IsNotADraft'), 'errors'); + setEventMessage($tmpproposal->ref." ".$langs->trans('IsNotADraft'), 'errors'); $error++; } } dol_print_error($db); $error++; } - if ($error){ + if ($error) { $db->rollback(); } else { $db->commit(); @@ -1323,13 +1323,13 @@ if ($resql) if ($tmpproposal->statut == 1) { $tmpproposal->statut = 2; if ($tmpproposal->update($user)) { - setEventMessage($tmpproposal->ref . " " . $langs->trans('Signed'), 'mesgs'); + setEventMessage($tmpproposal->ref." ".$langs->trans('Signed'), 'mesgs'); } else { dol_print_error($db); $error++; } } else { - setEventMessage($tmpproposal->ref . " " . $langs->trans('CantBeSign'), 'errors'); + setEventMessage($tmpproposal->ref." ".$langs->trans('CantBeSign'), 'errors'); $error++; } } else { @@ -1337,7 +1337,7 @@ if ($resql) $error++; } } - if ($error){ + if ($error) { $db->rollback(); } else { $db->commit(); diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index e4d432b234a..75f9457b45f 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -29,229 +29,229 @@ require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; class Orders extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'socid', - 'date' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid', + 'date' + ); - /** - * @var Commande $commande {@type Commande} - */ - public $commande; + /** + * @var Commande $commande {@type Commande} + */ + public $commande; - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->commande = new Commande($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->commande = new Commande($this->db); + } - /** - * Get properties of an order object by id - * - * Return an array with order informations - * - * @param int $id ID of order - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information + /** + * Get properties of an order object by id * - * @throws RestException - */ - public function get($id, $contact_list = 1) - { - return $this->_fetch($id, '', '', $contact_list); - } + * Return an array with order informations + * + * @param int $id ID of order + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id, $contact_list = 1) + { + return $this->_fetch($id, '', '', $contact_list); + } - /** - * Get properties of an order object by ref - * - * Return an array with order informations - * - * @param string $ref Ref of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref/{ref} - * - * @throws RestException - */ - public function getByRef($ref, $contact_list = 1) - { - return $this->_fetch('', $ref, '', $contact_list); - } + /** + * Get properties of an order object by ref + * + * Return an array with order informations + * + * @param string $ref Ref of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException + */ + public function getByRef($ref, $contact_list = 1) + { + return $this->_fetch('', $ref, '', $contact_list); + } - /** - * Get properties of an order object by ref_ext - * - * Return an array with order informations - * - * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref_ext/{ref_ext} - * - * @throws RestException - */ - public function getByRefExt($ref_ext, $contact_list = 1) - { - return $this->_fetch('', '', $ref_ext, $contact_list); - } + /** + * Get properties of an order object by ref_ext + * + * Return an array with order informations + * + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref_ext/{ref_ext} + * + * @throws RestException + */ + public function getByRefExt($ref_ext, $contact_list = 1) + { + return $this->_fetch('', '', $ref_ext, $contact_list); + } - /** - * Get properties of an order object - * - * Return an array with order informations - * - * @param int $id ID of order + /** + * Get properties of an order object + * + * Return an array with order informations + * + * @param int $id ID of order * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @throws RestException - */ - private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) - { - if (!DolibarrApiAccess::$user->rights->commande->lire) { - throw new RestException(401); - } + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) + { + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } - $result = $this->commande->fetch($id, $ref, $ref_ext); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id, $ref, $ref_ext); + if (!$result) { + throw new RestException(404, 'Order not found'); + } - if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - // Add external contacts ids - $this->commande->contacts_ids = $this->commande->liste_contact(-1, 'external', $contact_list); - $this->commande->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->commande); - } + // Add external contacts ids + $this->commande->contacts_ids = $this->commande->liste_contact(-1, 'external', $contact_list); + $this->commande->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->commande); + } - /** - * List orders - * - * Get a list of orders - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} - * @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 404 Not found - * @throws RestException 503 Error - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') - { - global $db, $conf; + /** + * List orders + * + * Get a list of orders + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} + * @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 404 Not found + * @throws RestException 503 Error + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - // case of external user, $thirdparty_ids param is ignored and replaced by user's socid - $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; - // If the internal user must only see his customers, force searching by him - $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + // If the internal user must only see his customers, force searching by him + $search_sale = 0; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; - $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - $sql .= " FROM ".MAIN_DB_PREFIX."commande as t"; + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql .= " FROM ".MAIN_DB_PREFIX."commande as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $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 t.entity IN ('.getEntity('commande').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - // Insert sale filter - if ($search_sale > 0) - { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Add sql filters - 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 .= ' WHERE t.entity IN ('.getEntity('commande').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + 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 .= $db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; + $sql .= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); - } + $sql .= $db->plimit($limit + 1, $offset); + } - dol_syslog("API Rest request"); - $result = $db->query($sql); + dol_syslog("API Rest request"); + $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - $i = 0; - while ($i < $min) - { - $obj = $db->fetch_object($result); - $commande_static = new Commande($db); - if ($commande_static->fetch($obj->rowid)) { - // Add external contacts ids - $commande_static->contacts_ids = $commande_static->liste_contact(-1, 'external', 1); - $obj_ret[] = $this->_cleanObjectDatas($commande_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve commande list : '.$db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No order found'); - } + if ($result) + { + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + $i = 0; + while ($i < $min) + { + $obj = $db->fetch_object($result); + $commande_static = new Commande($db); + if ($commande_static->fetch($obj->rowid)) { + // Add external contacts ids + $commande_static->contacts_ids = $commande_static->liste_contact(-1, 'external', 1); + $obj_ret[] = $this->_cleanObjectDatas($commande_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve commande list : '.$db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No order found'); + } return $obj_ret; - } + } - /** - * Create a sale order - * - * Exemple: { "socid": 2, "date": 1595196000, "type": 0, "lines": [{ "fk_product": 2, "qty": 1 }] } - * - * @param array $request_data Request data - * @return int ID of order - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { + /** + * Create a sale order + * + * Exemple: { "socid": 2, "date": 1595196000, "type": 0, "lines": [{ "fk_product": 2, "qty": 1 }] } + * + * @param array $request_data Request data + * @return int ID of order + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401, "Insuffisant rights"); - } - // Check mandatory fields - $result = $this->_validate($request_data); + } + // Check mandatory fields + $result = $this->_validate($request_data); - foreach ($request_data as $field => $value) { - $this->commande->$field = $value; - } - /*if (isset($request_data["lines"])) { + foreach ($request_data as $field => $value) { + $this->commande->$field = $value; + } + /*if (isset($request_data["lines"])) { $lines = array(); foreach ($request_data["lines"] as $line) { array_push($lines, (object) $line); @@ -259,241 +259,241 @@ class Orders extends DolibarrApi $this->commande->lines = $lines; }*/ - if ($this->commande->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors)); - } + if ($this->commande->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors)); + } - return $this->commande->id; - } + return $this->commande->id; + } - /** - * Get lines of an order - * - * @param int $id Id of order - * - * @url GET {id}/lines - * - * @return int - */ - public function getLines($id) - { - if (!DolibarrApiAccess::$user->rights->commande->lire) { + /** + * Get lines of an order + * + * @param int $id Id of order + * + * @url GET {id}/lines + * + * @return int + */ + public function getLines($id) + { + if (!DolibarrApiAccess::$user->rights->commande->lire) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->commande->getLinesArray(); - $result = array(); - foreach ($this->commande->lines as $line) { - array_push($result, $this->_cleanObjectDatas($line)); - } - return $result; - } + } + $this->commande->getLinesArray(); + $result = array(); + foreach ($this->commande->lines as $line) { + array_push($result, $this->_cleanObjectDatas($line)); + } + return $result; + } - /** - * Add a line to given order - * - * @param int $id Id of order to update - * @param array $request_data OrderLine data - * - * @url POST {id}/lines - * - * @return int - */ - public function postLine($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { + /** + * Add a line to given order + * + * @param int $id Id of order to update + * @param array $request_data OrderLine data + * + * @url POST {id}/lines + * + * @return int + */ + public function postLine($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + } $request_data = (object) $request_data; - $updateRes = $this->commande->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $request_data->fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $request_data->origin, - $request_data->origin_id, - $request_data->multicurrency_subprice, - $request_data->ref_ext - ); + $updateRes = $this->commande->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $request_data->fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice, + $request_data->ref_ext + ); - if ($updateRes > 0) { - return $updateRes; - } else { - throw new RestException(400, $this->commande->error); - } - } + if ($updateRes > 0) { + return $updateRes; + } else { + throw new RestException(400, $this->commande->error); + } + } - /** - * Update a line to given order - * - * @param int $id Id of order to update - * @param int $lineid Id of line to update - * @param array $request_data OrderLine data - * - * @url PUT {id}/lines/{lineid} - * - * @return array|bool - */ - public function putLine($id, $lineid, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { + /** + * Update a line to given order + * + * @param int $id Id of order to update + * @param int $lineid Id of line to update + * @param array $request_data OrderLine data + * + * @url PUT {id}/lines/{lineid} + * + * @return array|bool + */ + public function putLine($id, $lineid, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + } $request_data = (object) $request_data; - $updateRes = $this->commande->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->fk_parent_line, - 0, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->special_code, - $request_data->array_options, - $request_data->fk_unit, - $request_data->multicurrency_subprice, + $updateRes = $this->commande->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->fk_parent_line, 0, - $request_data->ref_ext - ); + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->fk_unit, + $request_data->multicurrency_subprice, + 0, + $request_data->ref_ext + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - } + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } - /** - * Delete a line to given order - * - * - * @param int $id Id of order to update - * @param int $lineid Id of line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return int - * - * @throws RestException 401 - * @throws RestException 404 - */ - public function deleteLine($id, $lineid) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { + /** + * Delete a line to given order + * + * + * @param int $id Id of order to update + * @param int $lineid Id of line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return int + * + * @throws RestException 401 + * @throws RestException 404 + */ + public function deleteLine($id, $lineid) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + } - // TODO Check the lineid $lineid is a line of ojbect + // TODO Check the lineid $lineid is a line of ojbect - $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user, $lineid); - if ($updateRes > 0) { - return $this->get($id); - } else { - throw new RestException(405, $this->commande->error); - } - } + $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user, $lineid); + if ($updateRes > 0) { + return $this->get($id); + } else { + throw new RestException(405, $this->commande->error); + } + } - /** - * Get contacts of given order - * - * Return an array with contact informations - * - * @param int $id ID of order + /** + * Get contacts of given order + * + * Return an array with contact informations + * + * @param int $id ID of order * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER) - * - * @url GET {id}/contacts - * - * @return array data without useless information - * - * @throws RestException - */ - public function getContacts($id, $type = '') - { - if (! DolibarrApiAccess::$user->rights->commande->lire) { - throw new RestException(401); - } + * + * @url GET {id}/contacts + * + * @return array data without useless information + * + * @throws RestException + */ + public function getContacts($id, $type = '') + { + if (! DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } - $result = $this->commande->fetch($id); - if ( ! $result ) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if ( ! $result ) { + throw new RestException(404, 'Order not found'); + } - if ( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if ( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $contacts = $this->commande->liste_contact(-1, 'external', 0, $type); + $contacts = $this->commande->liste_contact(-1, 'external', 0, $type); - return $this->_cleanObjectDatas($contacts); - } + return $this->_cleanObjectDatas($contacts); + } - /** + /** * Add a contact type of given order * * @param int $id Id of order to update @@ -504,43 +504,43 @@ class Orders extends DolibarrApi * * @return int * - * @throws RestException 401 - * @throws RestException 404 + * @throws RestException 401 + * @throws RestException 404 */ - public function postContact($id, $contactid, $type) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { + public function postContact($id, $contactid, $type) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->commande->add_contact($contactid, $type, 'external'); + $result = $this->commande->add_contact($contactid, $type, 'external'); - if ($result < 0) { - throw new RestException(500, 'Error when added the contact'); - } + if ($result < 0) { + throw new RestException(500, 'Error when added the contact'); + } - if ($result == 0) { - throw new RestException(304, 'contact already added'); - } + if ($result == 0) { + throw new RestException(304, 'contact already added'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Contact linked to the order' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contact linked to the order' + ) + ); + } - /** + /** * Unlink a contact type of given order * * @param int $id Id of order to update @@ -550,143 +550,143 @@ class Orders extends DolibarrApi * * @return int * - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ - public function deleteContact($id, $rowid) - { - if (! DolibarrApiAccess::$user->rights->commande->creer) { + public function deleteContact($id, $rowid) + { + if (! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (! $result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (! $result) { + throw new RestException(404, 'Order not found'); + } if (! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->commande->delete_linked_contact($rowid); + $result = $this->commande->delete_linked_contact($rowid); - if (!$result) { - throw new RestException(500, 'Error when deleted the contact'); - } + if (!$result) { + throw new RestException(500, 'Error when deleted the contact'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Contact unlinked from order' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contact unlinked from order' + ) + ); + } - /** - * Update order general fields (won't touch lines of order) - * - * @param int $id Id of order to update - * @param array $request_data Datas - * - * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { + /** + * Update order general fields (won't touch lines of order) + * + * @param int $id Id of order to update + * @param array $request_data Datas + * + * @return int + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - $this->commande->$field = $value; - } + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + $this->commande->$field = $value; + } // Update availability if (!empty($this->commande->availability_id)) { - if ($this->commande->availability($this->commande->availability_id) < 0) + if ($this->commande->availability($this->commande->availability_id) < 0) throw new RestException(400, 'Error while updating availability'); } - if ($this->commande->update(DolibarrApiAccess::$user) > 0) - { - return $this->get($id); - } else { - throw new RestException(500, $this->commande->error); - } - } + if ($this->commande->update(DolibarrApiAccess::$user) > 0) + { + return $this->get($id); + } else { + throw new RestException(500, $this->commande->error); + } + } - /** - * Delete order - * - * @param int $id Order ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->commande->supprimer) { + /** + * Delete order + * + * @param int $id Order ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->commande->supprimer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if (!$this->commande->delete(DolibarrApiAccess::$user)) { - throw new RestException(500, 'Error when deleting order : '.$this->commande->error); - } + if (!$this->commande->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when deleting order : '.$this->commande->error); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Order deleted' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Order deleted' + ) + ); + } - /** - * Validate an order - * + /** + * Validate an order + * * If you get a bad value for param notrigger check, provide this in body - * { - * "idwarehouse": 0, - * "notrigger": 0 - * } - * - * @param int $id Order ID - * @param int $idwarehouse Warehouse ID - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * - * @url POST {id}/validate - * + * { + * "idwarehouse": 0, + * "notrigger": 0 + * } + * + * @param int $id Order ID + * @param int $idwarehouse Warehouse ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - * - * @return array - */ - public function validate($id, $idwarehouse = 0, $notrigger = 0) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + * + * @return array + */ + public function validate($id, $idwarehouse = 0, $notrigger = 0) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); @@ -694,288 +694,288 @@ class Orders extends DolibarrApi $result = $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger); if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already validated'); + throw new RestException(304, 'Error nothing done. May be object is already validated'); } if ($result < 0) { - throw new RestException(500, 'Error when validating Order: '.$this->commande->error); + throw new RestException(500, 'Error when validating Order: '.$this->commande->error); + } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } - if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->commande->fetchObjectLinked(); + $this->commande->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->commande); - } + return $this->_cleanObjectDatas($this->commande); + } - /** - * Tag the order as validated (opened) - * - * Function used when order is reopend after being closed. - * - * @param int $id Id of the order - * - * @url POST {id}/reopen - * - * @return int - * - * @throws RestException 304 - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function reopen($id) - { + /** + * Tag the order as validated (opened) + * + * Function used when order is reopend after being closed. + * + * @param int $id Id of the order + * + * @url POST {id}/reopen + * + * @return int + * + * @throws RestException 304 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function reopen($id) + { - if (!DolibarrApiAccess::$user->rights->commande->creer) { - throw new RestException(401); - } - if (empty($id)) { - throw new RestException(400, 'Order ID is mandatory'); - } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + if (!DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + if (empty($id)) { + throw new RestException(400, 'Order ID is mandatory'); + } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } - $result = $this->commande->set_reopen(DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(405, $this->commande->error); - } elseif ($result == 0) { - throw new RestException(304); - } + $result = $this->commande->set_reopen(DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(405, $this->commande->error); + } elseif ($result == 0) { + throw new RestException(304); + } - return $result; - } + return $result; + } - /** - * Classify the order as invoiced. Could be also called setbilled - * - * @param int $id Id of the order - * - * @url POST {id}/setinvoiced - * - * @return int - * - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function setinvoiced($id) - { + /** + * Classify the order as invoiced. Could be also called setbilled + * + * @param int $id Id of the order + * + * @url POST {id}/setinvoiced + * + * @return int + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function setinvoiced($id) + { - if (!DolibarrApiAccess::$user->rights->commande->creer) { - throw new RestException(401); - } - if (empty($id)) { - throw new RestException(400, 'Order ID is mandatory'); - } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + if (!DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + if (empty($id)) { + throw new RestException(400, 'Order ID is mandatory'); + } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } - $result = $this->commande->classifyBilled(DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(400, $this->commande->error); - } - - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } - - if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $this->commande->fetchObjectLinked(); - - return $this->_cleanObjectDatas($this->commande); - } - - /** - * Close an order (Classify it as "Delivered") - * - * @param int $id Order ID - * @param int $notrigger Disabled triggers - * - * @url POST {id}/close - * - * @return int - */ - public function close($id, $notrigger = 0) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { - throw new RestException(401); - } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } - - if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger); - if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already closed'); - } - if ($result < 0) { - throw new RestException(500, 'Error when closing Order: '.$this->commande->error); - } - - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } - - if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $this->commande->fetchObjectLinked(); - - return $this->_cleanObjectDatas($this->commande); - } - - /** - * Set an order to draft - * - * @param int $id Order ID - * @param int $idwarehouse Warehouse ID to use for stock change (Used only if option STOCK_CALCULATE_ON_VALIDATE_ORDER is on) - * - * @url POST {id}/settodraft - * - * @return array - */ - public function settodraft($id, $idwarehouse = -1) - { - if (!DolibarrApiAccess::$user->rights->commande->creer) { - throw new RestException(401); - } - $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } - - if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->commande->setDraft(DolibarrApiAccess::$user, $idwarehouse); - if ($result == 0) { - throw new RestException(304, 'Nothing done. May be object is already closed'); - } - if ($result < 0) { - throw new RestException(500, 'Error when closing Order: '.$this->commande->error); - } + $result = $this->commande->classifyBilled(DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(400, $this->commande->error); + } $result = $this->commande->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + if (!$result) { + throw new RestException(404, 'Order not found'); + } - if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->commande->fetchObjectLinked(); + $this->commande->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->commande); - } + return $this->_cleanObjectDatas($this->commande); + } + + /** + * Close an order (Classify it as "Delivered") + * + * @param int $id Order ID + * @param int $notrigger Disabled triggers + * + * @url POST {id}/close + * + * @return int + */ + public function close($id, $notrigger = 0) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } + + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Order: '.$this->commande->error); + } + + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } + + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $this->commande->fetchObjectLinked(); + + return $this->_cleanObjectDatas($this->commande); + } + + /** + * Set an order to draft + * + * @param int $id Order ID + * @param int $idwarehouse Warehouse ID to use for stock change (Used only if option STOCK_CALCULATE_ON_VALIDATE_ORDER is on) + * + * @url POST {id}/settodraft + * + * @return array + */ + public function settodraft($id, $idwarehouse = -1) + { + if (!DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } + + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->commande->setDraft(DolibarrApiAccess::$user, $idwarehouse); + if ($result == 0) { + throw new RestException(304, 'Nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Order: '.$this->commande->error); + } + + $result = $this->commande->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); + } + + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $this->commande->fetchObjectLinked(); + + return $this->_cleanObjectDatas($this->commande); + } - /** - * Create an order using an existing proposal. - * - * - * @param int $proposalid Id of the proposal - * - * @url POST /createfromproposal/{proposalid} - * - * @return int - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function createOrderFromProposal($proposalid) - { + /** + * Create an order using an existing proposal. + * + * + * @param int $proposalid Id of the proposal + * + * @url POST /createfromproposal/{proposalid} + * + * @return int + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function createOrderFromProposal($proposalid) + { - require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - if (!DolibarrApiAccess::$user->rights->propal->lire) { - throw new RestException(401); - } - if (!DolibarrApiAccess::$user->rights->commande->creer) { - throw new RestException(401); - } - if (empty($proposalid)) { - throw new RestException(400, 'Proposal ID is mandatory'); - } + if (!DolibarrApiAccess::$user->rights->propal->lire) { + throw new RestException(401); + } + if (!DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + if (empty($proposalid)) { + throw new RestException(400, 'Proposal ID is mandatory'); + } - $propal = new Propal($this->db); - $result = $propal->fetch($proposalid); - if (!$result) { - throw new RestException(404, 'Proposal not found'); - } + $propal = new Propal($this->db); + $result = $propal->fetch($proposalid); + if (!$result) { + throw new RestException(404, 'Proposal not found'); + } - $result = $this->commande->createFromProposal($propal, DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(405, $this->commande->error); - } - $this->commande->fetchObjectLinked(); + $result = $this->commande->createFromProposal($propal, DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(405, $this->commande->error); + } + $this->commande->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->commande); - } + return $this->_cleanObjectDatas($this->commande); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param object $object Object to clean - * @return array Array of cleaned object properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $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 + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - 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); + 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 with data to verify - * @return array - * @throws RestException - */ - private function _validate($data) - { - $commande = array(); - foreach (Orders::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, $field." field missing"); - $commande[$field] = $data[$field]; - } - return $commande; - } + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + private function _validate($data) + { + $commande = array(); + foreach (Orders::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, $field." field missing"); + $commande[$field] = $data[$field]; + } + return $commande; + } } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 73dd2cee9fb..7119e85b473 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -99,13 +99,13 @@ class Commande extends CommonOrder */ public $ref_client; - /** + /** * @var string Internal ref for order * @deprecated */ public $ref_int; - /** + /** * @var int Contact ID */ public $contactid; @@ -121,15 +121,15 @@ class Commande extends CommonOrder */ public $billed; - /** - * @var int Draft Status of the order - */ - public $brouillon; - public $cond_reglement_code; + /** + * @var int Draft Status of the order + */ + public $brouillon; + public $cond_reglement_code; /** - * @var int bank account ID - */ + * @var int bank account ID + */ public $fk_account; /** @@ -168,12 +168,12 @@ class Commande extends CommonOrder public $demand_reason_id; // Source reason. Why we receive order (after a phone campaign, ...) public $demand_reason_code; /** - * @var int Date of order + * @var int Date of order */ public $date; /** - * @var int Date of order + * @var int Date of order * @deprecated * @see $date */ @@ -182,8 +182,8 @@ class Commande extends CommonOrder public $date_livraison; // Date expected of shipment (date starting shipment, not the reception that occurs some days after) /** - * @var int ID - */ + * @var int ID + */ public $fk_remise_except; public $remise_percent; @@ -197,13 +197,13 @@ class Commande extends CommonOrder public $linked_objects = array(); /** - * @var int User author ID - */ + * @var int User author ID + */ public $user_author_id; - /** - * @var int User validator ID - */ + /** + * @var int User validator ID + */ public $user_valid; /** @@ -213,8 +213,8 @@ class Commande extends CommonOrder // Multicurrency /** - * @var int Currency ID - */ + * @var int Currency ID + */ public $fk_multicurrency; public $multicurrency_code; @@ -223,9 +223,9 @@ class Commande extends CommonOrder public $multicurrency_total_tva; public $multicurrency_total_ttc; - /** - * @var Commande clone of order object - */ + /** + * @var Commande clone of order object + */ public $oldcopy; //! key of module source when order generated from a dedicated module ('cashdesk', 'takepos', ...) @@ -394,11 +394,11 @@ class Commande extends CommonOrder $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { - dol_print_error('', "Failed to include file ".$file); - return ''; - } + if ($mybool === false) + { + dol_print_error('', "Failed to include file ".$file); + return ''; + } $obj = new $classname(); $numref = $obj->getNextValue($soc, $this); @@ -568,7 +568,7 @@ class Commande extends CommonOrder { $this->ref = $num; $this->statut = self::STATUS_VALIDATED; - $this->brouillon = 0; + $this->brouillon = 0; } if (!$error) @@ -589,9 +589,9 @@ class Commande extends CommonOrder * @param int $idwarehouse Warehouse ID to use for stock change (Used only if option STOCK_CALCULATE_ON_VALIDATE_ORDER is on) * @return int <0 if KO, >0 if OK */ - public function setDraft($user, $idwarehouse = -1) - { - //phpcs:enable + public function setDraft($user, $idwarehouse = -1) + { + //phpcs:enable global $conf, $langs; $error = 0; @@ -619,12 +619,12 @@ class Commande extends CommonOrder if ($this->db->query($sql)) { - if (!$error) - { - $this->oldcopy = clone $this; - } + if (!$error) + { + $this->oldcopy = clone $this; + } - // If stock is decremented on validate order, we must reincrement it + // If stock is decremented on validate order, we must reincrement it if (!empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { $result = 0; @@ -665,7 +665,7 @@ class Commande extends CommonOrder $this->db->rollback(); return -1; } - } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -678,7 +678,7 @@ class Commande extends CommonOrder */ public function set_reopen($user) { - // phpcs:enable + // phpcs:enable $error = 0; if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED) @@ -958,7 +958,7 @@ class Commande extends CommonOrder $sql .= ", ".(int) $this->fk_incoterms; $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; $sql .= ", ".setEntity($this); - $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null"); + $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null"); $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null"); $sql .= ", ".(int) $this->fk_multicurrency; $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; @@ -1009,7 +1009,7 @@ class Commande extends CommonOrder $line->ref_ext = ''; } - $result = $this->addline( + $result = $this->addline( $line->desc, $line->subprice, $line->qty, @@ -1033,10 +1033,10 @@ class Commande extends CommonOrder $line->label, $line->array_options, $line->fk_unit, - $origintype, - $originid, + $origintype, + $originid, 0, - $line->ref_ext + $line->ref_ext ); if ($result < 0) { @@ -1357,8 +1357,8 @@ class Commande extends CommonOrder if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) { - $this->note_private = $object->note_private; - $this->note_public = $object->note_public; + $this->note_private = $object->note_private; + $this->note_public = $object->note_public; } $this->origin = $object->element; @@ -1502,7 +1502,7 @@ class Commande extends CommonOrder return -1; } - $this->db->begin(); + $this->db->begin(); $product_type = $type; if (!empty($fk_product)) @@ -1681,7 +1681,7 @@ class Commande extends CommonOrder */ public function add_product($idproduct, $qty, $remise_percent = 0.0, $date_start = '', $date_end = '') { - // phpcs:enable + // phpcs:enable global $conf, $mysoc; if (!$qty) $qty = 1; @@ -1780,7 +1780,7 @@ class Commande extends CommonOrder $sql .= ', c.fk_incoterms, c.location_incoterms'; $sql .= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc"; $sql .= ", c.module_source, c.pos_source"; - $sql .= ", i.libelle as label_incoterms"; + $sql .= ", i.libelle as label_incoterms"; $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql .= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc'; $sql .= ', ca.code as availability_code, ca.label as availability_label'; @@ -1917,7 +1917,7 @@ class Commande extends CommonOrder */ public function insert_discount($idremise) { - // phpcs:enable + // phpcs:enable global $langs; include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1992,7 +1992,7 @@ class Commande extends CommonOrder public function fetch_lines($only_product = 0, $loadalsotranslation = 0) { global $langs, $conf; - // phpcs:enable + // phpcs:enable $this->lines = array(); $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx, l.ref_ext,'; @@ -2086,13 +2086,13 @@ class Commande extends CommonOrder $line->fetch_optionals(); // multilangs - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { - $line = new Product($this->db); - $line->fetch($objp->fk_product); - $line->getMultiLangs(); - } + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { + $line = new Product($this->db); + $line->fetch($objp->fk_product); + $line->getMultiLangs(); + } - $this->lines[$i] = $line; + $this->lines[$i] = $line; $i++; } @@ -2224,7 +2224,7 @@ class Commande extends CommonOrder */ public function nb_expedition() { - // phpcs:enable + // phpcs:enable $sql = 'SELECT count(*)'; $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e'; $sql .= ', '.MAIN_DB_PREFIX.'element_element as el'; @@ -2251,7 +2251,7 @@ class Commande extends CommonOrder */ public function stock_array($filtre_statut = self::STATUS_CANCELED) { - // phpcs:enable + // phpcs:enable $this->stocks = array(); // Tableau des id de produit de la commande @@ -2359,7 +2359,7 @@ class Commande extends CommonOrder */ public function set_remise($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable $remise = trim($remise) ?trim($remise) : 0; if ($user->rights->commande->creer) @@ -2425,7 +2425,7 @@ class Commande extends CommonOrder */ public function set_remise_absolue($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable $remise = trim($remise) ?trim($remise) : 0; if ($user->rights->commande->creer) @@ -2491,7 +2491,7 @@ class Commande extends CommonOrder */ public function set_date($user, $date, $notrigger = 0) { - // phpcs:enable + // phpcs:enable if ($user->rights->commande->creer) { $error = 0; @@ -2553,7 +2553,7 @@ class Commande extends CommonOrder */ public function set_date_livraison($user, $date_livraison, $notrigger = 0) { - // phpcs:enable + // phpcs:enable if ($user->rights->commande->creer) { $error = 0; @@ -2620,7 +2620,7 @@ class Commande extends CommonOrder */ public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC') { - // phpcs:enable + // phpcs:enable global $user; $ga = array(); @@ -2750,7 +2750,7 @@ class Commande extends CommonOrder */ public function demand_reason($demand_reason_id, $notrigger = 0) { - // phpcs:enable + // phpcs:enable global $user; dol_syslog('Commande::demand_reason('.$demand_reason_id.')'); @@ -2819,7 +2819,7 @@ class Commande extends CommonOrder */ public function set_ref_client($user, $ref_client, $notrigger = 0) { - // phpcs:enable + // phpcs:enable if ($user->rights->commande->creer) { $error = 0; @@ -3321,9 +3321,9 @@ class Commande extends CommonOrder if (!$error) { // Delete extrafields of order details - $main = MAIN_DB_PREFIX.'commandedet'; - $ef = $main."_extrafields"; - $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_commande = ".$this->id.")"; + $main = MAIN_DB_PREFIX.'commandedet'; + $ef = $main."_extrafields"; + $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_commande = ".$this->id.")"; if (!$this->db->query($sql)) { $error++; @@ -3432,7 +3432,7 @@ class Commande extends CommonOrder */ public function load_board($user) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $clause = " WHERE"; @@ -3521,45 +3521,45 @@ class Commande extends CommonOrder */ public function LibStatut($status, $billed, $mode, $donotshowbilled = 0) { - // phpcs:enable + // phpcs:enable global $langs, $conf; $billedtext = ''; if (empty($donotshowbilled)) $billedtext .= ($billed ? ' - '.$langs->trans("Billed") : ''); if ($status == self::STATUS_CANCELED) { - $labelStatus = $langs->trans('StatusOrderCanceled'); - $labelStatusShort = $langs->trans('StatusOrderCanceledShort'); - $statusType = 'status9'; + $labelStatus = $langs->trans('StatusOrderCanceled'); + $labelStatusShort = $langs->trans('StatusOrderCanceledShort'); + $statusType = 'status9'; } elseif ($status == self::STATUS_DRAFT) { - $labelStatus = $langs->trans('StatusOrderDraft'); - $labelStatusShort = $langs->trans('StatusOrderDraftShort'); - $statusType = 'status0'; + $labelStatus = $langs->trans('StatusOrderDraft'); + $labelStatusShort = $langs->trans('StatusOrderDraftShort'); + $statusType = 'status0'; } elseif ($status == self::STATUS_VALIDATED) { - $labelStatus = $langs->trans('StatusOrderValidated').$billedtext; - $labelStatusShort = $langs->trans('StatusOrderValidatedShort').$billedtext; - $statusType = 'status1'; + $labelStatus = $langs->trans('StatusOrderValidated').$billedtext; + $labelStatusShort = $langs->trans('StatusOrderValidatedShort').$billedtext; + $statusType = 'status1'; } elseif ($status == self::STATUS_SHIPMENTONPROCESS) { - $labelStatus = $langs->trans('StatusOrderSentShort').$billedtext; - $labelStatusShort = $langs->trans('StatusOrderSentShort').$billedtext; - $statusType = 'status4'; + $labelStatus = $langs->trans('StatusOrderSentShort').$billedtext; + $labelStatusShort = $langs->trans('StatusOrderSentShort').$billedtext; + $statusType = 'status4'; } elseif ($status == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) { - $labelStatus = $langs->trans('StatusOrderToBill'); - $labelStatusShort = $langs->trans('StatusOrderToBillShort'); - $statusType = 'status4'; + $labelStatus = $langs->trans('StatusOrderToBill'); + $labelStatusShort = $langs->trans('StatusOrderToBillShort'); + $statusType = 'status4'; } elseif ($status == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) { - $labelStatus = $langs->trans('StatusOrderProcessed').$billedtext; - $labelStatusShort = $langs->trans('StatusOrderProcessed').$billedtext; - $statusType = 'status6'; + $labelStatus = $langs->trans('StatusOrderProcessed').$billedtext; + $labelStatusShort = $langs->trans('StatusOrderProcessed').$billedtext; + $statusType = 'status6'; } elseif ($status == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) { - $labelStatus = $langs->trans('StatusOrderDelivered'); - $labelStatusShort = $langs->trans('StatusOrderDelivered'); - $statusType = 'status6'; + $labelStatus = $langs->trans('StatusOrderDelivered'); + $labelStatusShort = $langs->trans('StatusOrderDelivered'); + $statusType = 'status6'; } else { - $labelStatus = $langs->trans('Unknown'); - $labelStatusShort = ''; - $statusType = ''; - $mode = 0; + $labelStatus = $langs->trans('Unknown'); + $labelStatusShort = ''; + $statusType = ''; + $mode = 0; } return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); @@ -3825,7 +3825,7 @@ class Commande extends CommonOrder */ public function load_state_board() { - // phpcs:enable + // phpcs:enable global $user; $this->nb = array(); @@ -4024,10 +4024,10 @@ class OrderLine extends CommonOrderLine * * @param DoliDB $db handler d'acces base de donnee */ - public function __construct($db) - { - $this->db = $db; - } + public function __construct($db) + { + $this->db = $db; + } /** * Load line order @@ -4125,32 +4125,32 @@ class OrderLine extends CommonOrderLine $error = 0; - // check if order line is not in a shipment line before deleting - $sqlCheckShipmentLine = "SELECT"; - $sqlCheckShipmentLine .= " ed.rowid"; - $sqlCheckShipmentLine .= " FROM ".MAIN_DB_PREFIX."expeditiondet ed"; - $sqlCheckShipmentLine .= " WHERE ed.fk_origin_line = ".$this->rowid; + // check if order line is not in a shipment line before deleting + $sqlCheckShipmentLine = "SELECT"; + $sqlCheckShipmentLine .= " ed.rowid"; + $sqlCheckShipmentLine .= " FROM ".MAIN_DB_PREFIX."expeditiondet ed"; + $sqlCheckShipmentLine .= " WHERE ed.fk_origin_line = ".$this->rowid; - $resqlCheckShipmentLine = $this->db->query($sqlCheckShipmentLine); - if (!$resqlCheckShipmentLine) { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - } else { - $langs->load('errors'); - $num = $this->db->num_rows($resqlCheckShipmentLine); - if ($num > 0) { - $error++; - $objCheckShipmentLine = $this->db->fetch_object($resqlCheckShipmentLine); - $this->error = $langs->trans('ErrorRecordAlreadyExists').' : '.$langs->trans('ShipmentLine').' '.$objCheckShipmentLine->rowid; - $this->errors[] = $this->error; - } - $this->db->free($resqlCheckShipmentLine); - } - if ($error) { - dol_syslog(__METHOD__.'Error ; '.$this->error, LOG_ERR); - return -1; - } + $resqlCheckShipmentLine = $this->db->query($sqlCheckShipmentLine); + if (!$resqlCheckShipmentLine) { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } else { + $langs->load('errors'); + $num = $this->db->num_rows($resqlCheckShipmentLine); + if ($num > 0) { + $error++; + $objCheckShipmentLine = $this->db->fetch_object($resqlCheckShipmentLine); + $this->error = $langs->trans('ErrorRecordAlreadyExists').' : '.$langs->trans('ShipmentLine').' '.$objCheckShipmentLine->rowid; + $this->errors[] = $this->error; + } + $this->db->free($resqlCheckShipmentLine); + } + if ($error) { + dol_syslog(__METHOD__.'Error ; '.$this->error, LOG_ERR); + return -1; + } $this->db->begin(); @@ -4482,7 +4482,7 @@ class OrderLine extends CommonOrderLine */ public function update_total() { - // phpcs:enable + // phpcs:enable $this->db->begin(); // Clean parameters diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 20f705a8ed9..9db3c8fcd96 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -100,13 +100,13 @@ class Facture extends CommonInvoice public $author; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_valid; public $date; // Date invoice @@ -153,8 +153,8 @@ class Facture extends CommonInvoice public $mode_reglement_code; // Code in llx_c_paiement /** - * @var int ID Field to store bank id to use when payment mode is withdraw - */ + * @var int ID Field to store bank id to use when payment mode is withdraw + */ public $fk_bank; /** @@ -175,8 +175,8 @@ class Facture extends CommonInvoice // Multicurrency /** - * @var int ID - */ + * @var int ID + */ public $fk_multicurrency; public $multicurrency_code; @@ -323,30 +323,30 @@ class Facture extends CommonInvoice ); // END MODULEBUILDER PROPERTIES - /** - * 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 (should not be used. a proforma is an order) - */ - const TYPE_PROFORMA = 4; + /** + * Proforma invoice (should not be used. a proforma is an order) + */ + const TYPE_PROFORMA = 4; /** * Situation invoice @@ -407,7 +407,7 @@ class Facture extends CommonInvoice * @param int $forceduedate If set, do not recalculate due date from payment condition but force it with value * @return int <0 if KO, >0 if OK */ - public function create(User $user, $notrigger = 0, $forceduedate = 0) + public function create(User $user, $notrigger = 0, $forceduedate = 0) { global $langs, $conf, $mysoc, $hookmanager; $error = 0; @@ -461,7 +461,7 @@ class Facture extends CommonInvoice // Create invoice from a template invoice if ($this->fac_rec > 0) { - $this->fk_fac_rec_source = $this->fac_rec; + $this->fk_fac_rec_source = $this->fac_rec; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; $_facrec = new FactureRec($this->db); @@ -503,9 +503,9 @@ class Facture extends CommonInvoice $this->ref_client = trim($this->ref_client); $this->note_public = trim($this->note_public); $this->note_private = trim($this->note_private); - $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref)); + $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref)); - $this->array_options = $_facrec->array_options; + $this->array_options = $_facrec->array_options; //if (! $this->remise) $this->remise = 0; if (!$this->mode_reglement_id) $this->mode_reglement_id = 0; @@ -520,12 +520,12 @@ class Facture extends CommonInvoice // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice if ($_facrec->frequency > 0) { - dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); - if (empty($_facrec->date_when)) $_facrec->date_when = $now; - $next_date = $_facrec->getNextDate(); // Calculate next date - $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); - //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. - $result = $_facrec->setNextDate($next_date, 1); + dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); + if (empty($_facrec->date_when)) $_facrec->date_when = $now; + $next_date = $_facrec->getNextDate(); // Calculate next date + $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); + //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. + $result = $_facrec->setNextDate($next_date, 1); } // Define lang of customer @@ -536,8 +536,8 @@ class Facture extends CommonInvoice if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang = $this->default_lang; // for thirdparty if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); } // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) @@ -567,16 +567,16 @@ class Facture extends CommonInvoice } // Define due date if not already defined - if (empty($forceduedate)) { - $duedate = $this->calculate_date_lim_reglement(); - /*if ($duedate < 0) { Regression, a date can be negative if before 1970. + if (empty($forceduedate)) { + $duedate = $this->calculate_date_lim_reglement(); + /*if ($duedate < 0) { Regression, a date can be negative if before 1970. dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR); return -1; }*/ - $this->date_lim_reglement = $duedate; - } else { - $this->date_lim_reglement = $forceduedate; - } + $this->date_lim_reglement = $duedate; + } else { + $this->date_lim_reglement = $forceduedate; + } // Insert into database $socid = $this->socid; @@ -595,17 +595,17 @@ class Facture extends CommonInvoice $sql .= ", note_private"; $sql .= ", note_public"; $sql .= ", ref_client, ref_int"; - $sql .= ", fk_account"; + $sql .= ", fk_account"; $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet"; $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf"; $sql .= ", situation_cycle_ref, situation_counter, situation_final"; $sql .= ", fk_incoterms, location_incoterms"; - $sql .= ", fk_multicurrency"; - $sql .= ", multicurrency_code"; - $sql .= ", multicurrency_tx"; - $sql .= ", retained_warranty"; - $sql .= ", retained_warranty_date_limit"; - $sql .= ", retained_warranty_fk_cond_reglement"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ", retained_warranty"; + $sql .= ", retained_warranty_date_limit"; + $sql .= ", retained_warranty_fk_cond_reglement"; $sql .= ")"; $sql .= " VALUES ("; $sql .= "'(PROV)'"; @@ -636,7 +636,7 @@ class Facture extends CommonInvoice $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null"); $sql .= ", ".($this->situation_final ? $this->situation_final : 0); $sql .= ", ".(int) $this->fk_incoterms; - $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; $sql .= ", ".(int) $this->fk_multicurrency; $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql .= ", ".(double) $this->multicurrency_tx; @@ -667,27 +667,27 @@ class Facture 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++; + } + } } } @@ -698,20 +698,20 @@ class Facture extends CommonInvoice $originidforcontact = $this->origin_id; if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order { - require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; - $exp = new Expedition($this->db); - $exp->fetch($this->origin_id); - $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); - if (count($exp->linkedObjectsIds['commande']) > 0) - { - foreach ($exp->linkedObjectsIds['commande'] as $key => $value) - { - $originforcontact = 'commande'; - if (is_object($value)) $originidforcontact = $value->id; - else $originidforcontact = $value; - break; // We take first one - } - } + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; + $exp = new Expedition($this->db); + $exp->fetch($this->origin_id); + $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); + if (count($exp->linkedObjectsIds['commande']) > 0) + { + foreach ($exp->linkedObjectsIds['commande'] as $key => $value) + { + $originforcontact = 'commande'; + if (is_object($value)) $originidforcontact = $value->id; + else $originidforcontact = $value; + break; // We take first one + } + } } $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; @@ -720,11 +720,11 @@ class Facture extends CommonInvoice $resqlcontact = $this->db->query($sqlcontact); if ($resqlcontact) { - while ($objcontact = $this->db->fetch_object($resqlcontact)) - { - //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; - $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object - } + while ($objcontact = $this->db->fetch_object($resqlcontact)) + { + //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; + $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object + } } else dol_print_error($resqlcontact); } @@ -764,12 +764,12 @@ class Facture extends CommonInvoice $newinvoiceline->fk_parent_line = $fk_parent_line; if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) { - $discount = new DiscountAbsolute($this->db); - $discount->fetch($newinvoiceline->fk_remise_except); + $discount = new DiscountAbsolute($this->db); + $discount->fetch($newinvoiceline->fk_remise_except); - $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx); - $newinvoiceline->fk_remise_except = $discountId; - } + $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx); + $newinvoiceline->fk_remise_except = $discountId; + } $result = $newinvoiceline->insert(); @@ -793,13 +793,13 @@ class Facture extends CommonInvoice foreach ($this->lines as $i => $val) { - $line = $this->lines[$i]; + $line = $this->lines[$i]; - // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array - //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) $line = (object) $line; + // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array + //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. + if (!is_object($line)) $line = (object) $line; - if ($result >= 0) + if ($result >= 0) { // Reset fk_parent_line for no child products and special product if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { @@ -823,7 +823,7 @@ class Facture extends CommonInvoice $line->ref_ext = ''; } - $result = $this->addline( + $result = $this->addline( $line->desc, $line->subprice, $line->qty, @@ -842,8 +842,8 @@ class Facture extends CommonInvoice $line->product_type, $line->rang, $line->special_code, - $origintype, - $originid, + $origintype, + $originid, $fk_parent_line, $line->fk_fournprice, $line->pa_ht, @@ -902,26 +902,26 @@ class Facture extends CommonInvoice $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice; // If buyprice not defined from template invoice, we try to guess the best value if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) - { - require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; - $producttmp = new ProductFournisseur($this->db); - $producttmp->fetch($_facrec->lines[$i]->fk_product); + { + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; + $producttmp = new ProductFournisseur($this->db); + $producttmp->fetch($_facrec->lines[$i]->fk_product); - // If margin module defined on costprice, we try the costprice - // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price - // else we get the best supplier price - if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price; - elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp; - else { - if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) - { - if ($producttmp->product_fourn_price_id > 0) - { - $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU'); - } - } - } - } + // If margin module defined on costprice, we try the costprice + // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price + // else we get the best supplier price + if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price; + elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp; + else { + if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) + { + if ($producttmp->product_fourn_price_id > 0) + { + $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU'); + } + } + } + } $result_insert = $this->addline( $_facrec->lines[$i]->desc, @@ -945,7 +945,7 @@ class Facture extends CommonInvoice '', 0, 0, - $fk_product_fournisseur_price, + $fk_product_fournisseur_price, $buyprice, $_facrec->lines[$i]->label, empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options, @@ -974,17 +974,17 @@ class Facture extends CommonInvoice // Actions on extra fields if (!$error) { - $result = $this->insertExtraFields(); - if ($result < 0) $error++; + $result = $this->insertExtraFields(); + if ($result < 0) $error++; } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILL_CREATE', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('BILL_CREATE', $user); + if ($result < 0) $error++; + // End call triggers + } if (!$error) { @@ -1019,7 +1019,7 @@ class Facture extends CommonInvoice * @param int $invertdetail Reverse sign of amounts for lines * @return int <0 if KO, >0 if OK */ - public function createFromCurrent(User $user, $invertdetail = 0) + public function createFromCurrent(User $user, $invertdetail = 0) { global $conf; @@ -1030,13 +1030,13 @@ class Facture extends CommonInvoice // fetch optionals attributes and labels $this->fetch_optionals(); - if (!empty($this->array_options)) { - $facture->array_options = $this->array_options; - } + if (!empty($this->array_options)) { + $facture->array_options = $this->array_options; + } - foreach ($this->lines as &$line) { - $line->fetch_optionals(); //fetch extrafields - } + foreach ($this->lines as &$line) { + $line->fetch_optionals(); //fetch extrafields + } $facture->fk_facture_source = $this->fk_facture_source; $facture->type = $this->type; @@ -1062,9 +1062,9 @@ class Facture extends CommonInvoice $facture->situation_cycle_ref = $this->situation_cycle_ref; $facture->situation_final = $this->situation_final; - $facture->retained_warranty = $this->retained_warranty; - $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement; - $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit; + $facture->retained_warranty = $this->retained_warranty; + $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement; + $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit; // Loop on each line of new invoice @@ -1112,7 +1112,7 @@ class Facture extends CommonInvoice /** * Load an object from its id and create a new one in database * - * @param User $user User that clone + * @param User $user User that clone * @param int $fromid Id of object to clone * @return int New id of clone */ @@ -1135,11 +1135,11 @@ class Facture extends CommonInvoice if ($objsoc->fetch($this->socid) > 0) { - $object->socid = $objsoc->id; - $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $object->fk_project = ''; - $object->fk_delivery_address = ''; + $object->socid = $objsoc->id; + $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $object->fk_project = ''; + $object->fk_delivery_address = ''; } // TODO Change product price if multi-prices @@ -1168,14 +1168,14 @@ class Facture extends CommonInvoice // Loop on each line of new invoice foreach ($object->lines as $i => $line) { - if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts + if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts { - unset($object->lines[$i]); - unset($object->products[$i]); // Tant que products encore utilise + unset($object->lines[$i]); + unset($object->products[$i]); // Tant que products encore utilise } // Bloc to update dates of service (month by month only if previously filled at 1d near start or end of month) // If it's a service with start and end dates - if (!empty($line->date_start) && !empty($line->date_end) ) { + if (!empty($line->date_start) && !empty($line->date_end)) { // Get the dates $start = dol_getdate($line->date_start); $end = dol_getdate($line->date_end); @@ -1207,13 +1207,13 @@ class Facture extends CommonInvoice if ($result < 0) $error++; else { // copy internal contacts - if ($object->copy_linked_contact($this, 'internal') < 0) + if ($object->copy_linked_contact($this, 'internal') < 0) $error++; // copy external contacts if same company elseif ($this->socid == $object->socid) { - if ($object->copy_linked_contact($this, 'external') < 0) + if ($object->copy_linked_contact($this, 'external') < 0) $error++; } } @@ -1250,7 +1250,7 @@ class Facture extends CommonInvoice * @param User $user Object user * @return int <0 if KO, 0 if nothing done, 1 if OK */ - public function createFromOrder($object, User $user) + public function createFromOrder($object, User $user) { global $conf, $hookmanager; @@ -1303,7 +1303,7 @@ class Facture extends CommonInvoice $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht); $line->pa_ht = $marginInfos[0]; - // get extrafields from original line + // get extrafields from original line $object->lines[$i]->fetch_optionals(); foreach ($object->lines[$i]->array_options as $options_key => $value) $line->array_options[$options_key] = $value; @@ -1325,17 +1325,17 @@ class Facture extends CommonInvoice if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) { - $this->note_private = $object->note_private; - $this->note_public = $object->note_public; + $this->note_private = $object->note_private; + $this->note_public = $object->note_public; } - $this->module_source = $object->module_source; + $this->module_source = $object->module_source; $this->pos_source = $object->pos_source; $this->origin = $object->element; $this->origin_id = $object->id; - // get extrafields from original line + // get extrafields from original line $object->fetch_optionals(); foreach ($object->array_options as $options_key => $value) $this->array_options[$options_key] = $value; @@ -1374,13 +1374,13 @@ class Facture 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 $addlinktonotes 1=Add link to notes - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...) + * @param int $notooltip 1=Disable tooltip + * @param int $addlinktonotes 1=Add link to notes + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...) * @return string String with URL */ - public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '') + public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '') { global $langs, $conf, $user, $mysoc; @@ -1391,8 +1391,8 @@ class Facture extends CommonInvoice if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id; else $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id; - if (!$user->rights->facture->lire) - $option = 'nolink'; + if (!$user->rights->facture->lire) + $option = 'nolink'; if ($option !== 'nolink') { @@ -1408,56 +1408,56 @@ class Facture extends CommonInvoice if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice - $label = ''; + $label = ''; - if ($user->rights->facture->lire) { - $label = ''.$langs->trans("Invoice").''; - if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("ReplacementInvoice").''; - if ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; - if ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; - if ($this->type == self::TYPE_SITUATION) $label = ''.$langs->transnoentitiesnoconv("InvoiceSituation").''; - if (!empty($this->ref)) - $label .= '
'.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->ref_client)) - $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; - if (!empty($this->date)) - $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); - if (!empty($this->total_ht)) - $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_tva)) - $label .= '
'.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000' - $label .= '
'.$langs->transcountry('AmountLT1', $mysoc->country_code).': '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) - $label .= '
'.$langs->transcountry('AmountLT2', $mysoc->country_code).': '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) - $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($moretitle) $label .= ' - '.$moretitle; - if (isset($this->statut) && isset($this->alreadypaid)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); - } - } + if ($user->rights->facture->lire) { + $label = ''.$langs->trans("Invoice").''; + if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("ReplacementInvoice").''; + if ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; + if ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; + if ($this->type == self::TYPE_SITUATION) $label = ''.$langs->transnoentitiesnoconv("InvoiceSituation").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_client)) + $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; + if (!empty($this->date)) + $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); + if (!empty($this->total_ht)) + $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_tva)) + $label .= '
'.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000' + $label .= '
'.$langs->transcountry('AmountLT1', $mysoc->country_code).': '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) + $label .= '
'.$langs->transcountry('AmountLT2', $mysoc->country_code).': '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_ttc)) + $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if ($moretitle) $label .= ' - '.$moretitle; + if (isset($this->statut) && isset($this->alreadypaid)) { + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); + } + } $linkclose = ($target ? ' target="'.$target.'"' : ''); if (empty($notooltip) && $user->rights->facture->lire) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("Invoice"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("Invoice"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; } - $linkstart = ''; + $linkstart = ''; $linkend = ''; - if ($option == 'nolink') { - $linkstart = ''; - $linkend = ''; - } + if ($option == 'nolink') { + $linkstart = ''; + $linkend = ''; + } $result .= $linkstart; if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); @@ -1466,19 +1466,19 @@ class Facture extends CommonInvoice if ($addlinktonotes) { - $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { - //$notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); - $notetoshow = $langs->trans("ViewPrivateNote").':
'.$txttoshow; - $result .= ' '; - $result .= ''; - $result .= img_picto('', 'note'); - $result .= ''; - //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); - //$result.=''; - $result .= ''; - } + $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); + if ($txttoshow) + { + //$notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); + $notetoshow = $langs->trans("ViewPrivateNote").':
'.$txttoshow; + $result .= ' '; + $result .= ''; + $result .= img_picto('', 'note'); + $result .= ''; + //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); + //$result.=''; + $result .= ''; + } } return $result; @@ -1516,10 +1516,10 @@ class Facture extends CommonInvoice $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 .= ', f.fk_incoterms, f.location_incoterms'; - $sql .= ', f.module_source, f.pos_source'; - $sql .= ", i.libelle as label_incoterms"; - $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement"; + $sql .= ', f.fk_incoterms, f.location_incoterms'; + $sql .= ', f.module_source, f.pos_source'; + $sql .= ", i.libelle as label_incoterms"; + $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement"; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; @@ -1651,7 +1651,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load all detailed lines into this->lines * @@ -1663,7 +1663,7 @@ class Facture extends CommonInvoice public function fetch_lines($only_product = 0, $loadalsotranslation = 0) { global $langs, $conf; - // phpcs:enable + // phpcs:enable $this->lines = array(); $sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; @@ -1708,7 +1708,7 @@ class Facture extends CommonInvoice $line->subprice = $objp->subprice; $line->ref_ext = $objp->ref_ext; // line external ref - $line->vat_src_code = $objp->vat_src_code; + $line->vat_src_code = $objp->vat_src_code; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; $line->localtax2_tx = $objp->localtax2_tx; @@ -1751,14 +1751,14 @@ class Facture extends CommonInvoice $line->multicurrency_total_tva = $objp->multicurrency_total_tva; $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $line->fetch_optionals(); + $line->fetch_optionals(); // multilangs - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { - $line = new Product($this->db); - $line->fetch($objp->fk_product); - $line->getMultiLangs(); - } + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { + $line = new Product($this->db); + $line->fetch($objp->fk_product); + $line->getMultiLangs(); + } $this->lines[$i] = $line; @@ -1778,7 +1778,7 @@ class Facture extends CommonInvoice * * @return void */ - public function fetchPreviousNextSituationInvoice() + public function fetchPreviousNextSituationInvoice() { global $conf; @@ -1800,13 +1800,13 @@ class Facture extends CommonInvoice $invoice = new Facture($this->db); if ($invoice->fetch($objp->rowid) > 0) { - if ($objp->situation_counter < $this->situation_counter - || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes - ) + if ($objp->situation_counter < $this->situation_counter + || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes + ) { - $this->tab_previous_situation_invoice[] = $invoice; + $this->tab_previous_situation_invoice[] = $invoice; } else { - $this->tab_next_situation_invoice[] = $invoice; + $this->tab_next_situation_invoice[] = $invoice; } } } @@ -1820,7 +1820,7 @@ class Facture extends CommonInvoice * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - public function update(User $user, $notrigger = 0) + public function update(User $user, $notrigger = 0) { global $conf; @@ -1930,16 +1930,16 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) * * @param int $idremise Id of absolute discount * @return int >0 if OK, <0 if KO */ - public function insert_discount($idremise) + public function insert_discount($idremise) { - // phpcs:enable + // phpcs:enable global $langs; include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1975,12 +1975,12 @@ class Facture extends CommonInvoice // Get buy/cost price of invoice that is source of discount if ($remise->fk_facture_source > 0) { - $srcinvoice = new Facture($this->db); - $srcinvoice->fetch($remise->fk_facture_source); - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject - $formmargin = new FormMargin($this->db); - $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); - $facligne->pa_ht = $arraytmp['pa_total']; + $srcinvoice = new Facture($this->db); + $srcinvoice->fetch($remise->fk_facture_source); + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject + $formmargin = new FormMargin($this->db); + $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); + $facligne->pa_ht = $arraytmp['pa_total']; } $facligne->total_ht = -$remise->amount_ht; @@ -2025,7 +2025,7 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set customer ref * @@ -2033,10 +2033,10 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function set_ref_client($ref_client, $notrigger = 0) + public function set_ref_client($ref_client, $notrigger = 0) { - // phpcs:enable - global $user; + // phpcs:enable + global $user; $error = 0; @@ -2094,7 +2094,7 @@ class Facture extends CommonInvoice * @param int $idwarehouse Id warehouse to use for stock change. * @return int <0 if KO, 0=Refused, >0 if OK */ - public function delete($user, $notrigger = 0, $idwarehouse = -1) + public function delete($user, $notrigger = 0, $idwarehouse = -1) { global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -2114,10 +2114,10 @@ class Facture extends CommonInvoice if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('BILL_DELETE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_DELETE', $user); + if ($result < 0) $error++; + // End call triggers } // Removed extrafields @@ -2189,7 +2189,7 @@ class Facture extends CommonInvoice } } - // Invoice line extrafileds + // Invoice line extrafileds $main = MAIN_DB_PREFIX.'facturedet'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)"; @@ -2255,7 +2255,7 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1 * or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0 @@ -2265,9 +2265,9 @@ class Facture extends CommonInvoice * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) * @return int <0 if KO, >0 if OK */ - public function set_paid($user, $close_code = '', $close_note = '') + public function set_paid($user, $close_code = '', $close_note = '') { - // phpcs:enable + // phpcs:enable $error = 0; if ($this->paye != 1) @@ -2290,10 +2290,10 @@ class Facture extends CommonInvoice $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_PAYED', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_PAYED', $user); + if ($result < 0) $error++; + // End call triggers } else { $error++; $this->error = $this->db->lasterror(); @@ -2313,7 +2313,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED * Fonction utilisee quand un paiement prelevement est refuse, @@ -2322,9 +2322,9 @@ class Facture extends CommonInvoice * @param User $user Object user that change status * @return int <0 if KO, >0 if OK */ - public function set_unpaid($user) + public function set_unpaid($user) { - // phpcs:enable + // phpcs:enable $error = 0; $this->db->begin(); @@ -2339,10 +2339,10 @@ class Facture extends CommonInvoice $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_UNPAYED', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_UNPAYED', $user); + if ($result < 0) $error++; + // End call triggers } else { $error++; $this->error = $this->db->error(); @@ -2360,7 +2360,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because @@ -2371,9 +2371,9 @@ class Facture extends CommonInvoice * @param string $close_note Comment * @return int <0 if KO, >0 if OK */ - public function set_canceled($user, $close_code = '', $close_note = '') + public function set_canceled($user, $close_code = '', $close_note = '') { - // phpcs:enable + // phpcs:enable dol_syslog(get_class($this)."::set_canceled rowid=".$this->id, LOG_DEBUG); @@ -2397,14 +2397,14 @@ class Facture extends CommonInvoice $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_CANCEL', $user); - if ($result < 0) - { + // Call trigger + $result = $this->call_trigger('BILL_CANCEL', $user); + if ($result < 0) + { $this->db->rollback(); return -1; } - // End call triggers + // End call triggers $this->db->commit(); return 1; @@ -2430,9 +2430,9 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @param int $batch_rule 0=do not decrement batch, else batch rule to use * 1=take in batches ordered by sellby and eatby dates - * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK + * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK */ - public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) + public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) { global $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -2463,12 +2463,12 @@ class Facture extends CommonInvoice } if (count($this->lines) <= 0) { - $langs->load("errors"); + $langs->load("errors"); $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); return -1; } if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) { $this->error = 'Permission denied'; dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR); @@ -2680,10 +2680,10 @@ class Facture extends CommonInvoice // Trigger calls if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('BILL_VALIDATE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_VALIDATE', $user); + if ($result < 0) $error++; + // End call triggers } if (!$error) @@ -2711,16 +2711,16 @@ class Facture extends CommonInvoice if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { - $dirsource = $fileentry['name']; - $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource = $fileentry['path'].'/'.$dirsource; - $dirdest = $fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) + { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -2744,20 +2744,20 @@ class Facture extends CommonInvoice $this->date_validation = $now; $i = 0; - if (!empty($conf->global->INVOICE_USE_SITUATION)) - { - $final = true; - $nboflines = count($this->lines); - while (($i < $nboflines) && $final) { - $final = ($this->lines[$i]->situation_percent == 100); - $i++; - } + if (!empty($conf->global->INVOICE_USE_SITUATION)) + { + $final = true; + $nboflines = count($this->lines); + while (($i < $nboflines) && $final) { + $final = ($this->lines[$i]->situation_percent == 100); + $i++; + } - if (empty($final)) $this->situation_final = 0; - else $this->situation_final = 1; + if (empty($final)) $this->situation_final = 0; + else $this->situation_final = 1; - $this->setFinal($user); - } + $this->setFinal($user); + } } } else { $error++; @@ -2779,7 +2779,7 @@ class Facture extends CommonInvoice * @param Translate $langs Translate object * @return bool false if KO, true if OK */ - public function updatePriceNextInvoice(&$langs) + public function updatePriceNextInvoice(&$langs) { foreach ($this->tab_next_situation_invoice as $next_invoice) { @@ -2823,7 +2823,7 @@ class Facture extends CommonInvoice */ public function setDraft($user, $idwarehouse = -1) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $error = 0; @@ -2945,38 +2945,38 @@ class Facture extends CommonInvoice * @param string $ref_ext External reference of the line * @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, - $date_start = '', - $date_end = '', - $ventil = 0, - $info_bits = 0, - $fk_remise_except = '', - $price_base_type = 'HT', - $pu_ttc = 0, - $type = self::TYPE_STANDARD, - $rang = -1, - $special_code = 0, - $origin = '', - $origin_id = 0, - $fk_parent_line = 0, - $fk_fournprice = null, - $pa_ht = 0, - $label = '', - $array_options = 0, - $situation_percent = 100, - $fk_prev_id = 0, - $fk_unit = null, - $pu_ht_devise = 0, - $ref_ext = '' - ) { + public function addline( + $desc, + $pu_ht, + $qty, + $txtva, + $txlocaltax1 = 0, + $txlocaltax2 = 0, + $fk_product = 0, + $remise_percent = 0, + $date_start = '', + $date_end = '', + $ventil = 0, + $info_bits = 0, + $fk_remise_except = '', + $price_base_type = 'HT', + $pu_ttc = 0, + $type = self::TYPE_STANDARD, + $rang = -1, + $special_code = 0, + $origin = '', + $origin_id = 0, + $fk_parent_line = 0, + $fk_fournprice = null, + $pa_ht = 0, + $label = '', + $array_options = 0, + $situation_percent = 100, + $fk_prev_id = 0, + $fk_unit = null, + $pu_ht_devise = 0, + $ref_ext = '' + ) { // Deprecation warning if ($label) { dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING); @@ -3043,8 +3043,8 @@ class Facture extends CommonInvoice $product_type = $product->type; if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); + $langs->load("errors"); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); $this->db->rollback(); return -3; } @@ -3077,8 +3077,8 @@ class Facture extends CommonInvoice // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; // Rank to use @@ -3142,8 +3142,8 @@ class Facture extends CommonInvoice $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; if (is_array($array_options) && count($array_options) > 0) { $this->line->array_options = $array_options; @@ -3200,7 +3200,7 @@ class Facture extends CommonInvoice * @param int $pa_ht Price (without tax) of product when it was bought * @param string $label Label of the line (deprecated, do not use) * @param int $special_code Special code (also used by externals modules!) - * @param array $array_options extrafields array + * @param array $array_options extrafields array * @param int $situation_percent Situation advance percentage * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency @@ -3208,7 +3208,7 @@ class Facture extends CommonInvoice * @param string $ref_ext External reference of the line * @return int < 0 if KO, > 0 if OK */ - public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '') + public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '') { global $conf, $user; // Deprecation warning @@ -3251,7 +3251,7 @@ class Facture extends CommonInvoice $remise_percent = price2num($remise_percent); $qty = price2num($qty); $pu = price2num($pu); - $pu_ht_devise = price2num($pu_ht_devise); + $pu_ht_devise = price2num($pu_ht_devise); $pa_ht = price2num($pa_ht); $txtva = price2num($txtva); $txlocaltax1 = price2num($txlocaltax1); @@ -3267,12 +3267,12 @@ class Facture extends CommonInvoice $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. - } + $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, $situation_percent, $this->multicurrency_tx, $pu_ht_devise); @@ -3287,8 +3287,8 @@ class Facture extends CommonInvoice // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; // Old properties: $price, $remise (deprecated) @@ -3313,8 +3313,8 @@ class Facture extends CommonInvoice $product_type = $product->type; if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); + $langs->load("errors"); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); $this->db->rollback(); return -3; } @@ -3324,7 +3324,7 @@ class Facture extends CommonInvoice $line->oldline = $staticline; $this->line = $line; - $this->line->context = $this->context; + $this->line->context = $this->context; // Reorder if fk_parent_line change if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) @@ -3337,7 +3337,7 @@ class Facture extends CommonInvoice $this->line->rowid = $rowid; $this->line->label = $label; $this->line->desc = $desc; - $this->line->ref_ext = $ref_ext; + $this->line->ref_ext = $ref_ext; $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative $this->line->vat_src_code = $vat_src_code; @@ -3370,8 +3370,8 @@ class Facture extends CommonInvoice // Multicurrency $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; if (is_array($array_options) && count($array_options) > 0) { // We replace values in this->line->array_options only for entries defined into $array_options @@ -3391,7 +3391,7 @@ class Facture extends CommonInvoice $this->db->commit(); return $result; } else { - $this->error = $this->line->error; + $this->error = $this->line->error; $this->db->rollback(); return -1; } @@ -3408,7 +3408,7 @@ class Facture extends CommonInvoice * @param float $situation_percent progress percentage need to be test * @return false if KO, true if OK */ - public function checkProgressLine($idline, $situation_percent) + public function checkProgressLine($idline, $situation_percent) { $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid) @@ -3428,7 +3428,7 @@ class Facture extends CommonInvoice else return $situation_percent < $obj->situation_percent; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update invoice line with percentage * @@ -3436,16 +3436,16 @@ class Facture extends CommonInvoice * @param int $percent Percentage * @return void */ - public function update_percent($line, $percent) + public function update_percent($line, $percent) { - // phpcs:enable - global $mysoc, $user; + // phpcs:enable + global $mysoc, $user; - // Progress should never be changed for discount lines - if (($line->info_bits & 2) == 2) - { - return; - } + // Progress should never be changed for discount lines + if (($line->info_bits & 2) == 2) + { + return; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -3471,9 +3471,9 @@ class Facture extends CommonInvoice * @param int $rowid Id of line to delete * @return int <0 if KO, >0 if OK */ - public function deleteline($rowid) + public function deleteline($rowid) { - global $user; + global $user; dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG); @@ -3501,7 +3501,7 @@ class Facture extends CommonInvoice $line = new FactureLigne($this->db); - $line->context = $this->context; + $line->context = $this->context; // For triggers $result = $line->fetch($rowid); @@ -3527,7 +3527,7 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set percent discount * @@ -3536,9 +3536,9 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ - public function set_remise($user, $remise, $notrigger = 0) + public function set_remise($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable // Clean parameters if (empty($remise)) $remise = 0; @@ -3591,7 +3591,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set absolute discount * @@ -3600,9 +3600,9 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function set_remise_absolue($user, $remise, $notrigger = 0) + public function set_remise_absolue($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable if (empty($remise)) $remise = 0; if ($user->rights->facture->creer) @@ -3665,7 +3665,7 @@ class Facture extends CommonInvoice * @param string $mode 'next' for next value or 'last' for last value * @return string free ref or last ref */ - public function getNextNumRef($soc, $mode = 'next') + public function getNextNumRef($soc, $mode = 'next') { global $conf, $langs; @@ -3763,7 +3763,7 @@ class Facture extends CommonInvoice * @param int $id Id of object to load * @return void */ - public function info($id) + public function info($id) { $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,'; $sql .= ' date_closing as dateclosing,'; @@ -3809,7 +3809,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices (eventually filtered on a user) into an array * @@ -3823,9 +3823,9 @@ class Facture extends CommonInvoice * @param string $sortorder Sort order * @return array|int -1 if KO, array with result if OK */ - public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') + public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') { - // phpcs:enable + // phpcs:enable global $conf, $user; $ga = array(); @@ -3880,7 +3880,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices qualified to be replaced by another invoice. * Invoices matching the following rules are returned: @@ -3889,9 +3889,9 @@ class Facture extends CommonInvoice * @param int $socid Id thirdparty * @return array|int Array of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) */ - public function list_replacable_invoices($socid = 0) + public function list_replacable_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -3928,7 +3928,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices qualified to be corrected by a credit note. * Invoices matching the following rules are returned: @@ -3937,9 +3937,9 @@ class Facture extends CommonInvoice * @param int $socid Id thirdparty * @return array Array of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) */ - public function list_qualified_avoir_invoices($socid = 0) + public function list_qualified_avoir_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -3958,17 +3958,17 @@ class Facture extends CommonInvoice $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) { - // Select the last situation invoice - $sqlSit = 'SELECT MAX(fs.rowid)'; - $sqlSit .= " FROM ".MAIN_DB_PREFIX."facture as fs"; - $sqlSit .= " WHERE fs.entity IN (".getEntity('invoice').")"; - $sqlSit .= " AND fs.type = ".self::TYPE_SITUATION; - $sqlSit .= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; - $sqlSit .= " GROUP BY fs.situation_cycle_ref"; - $sqlSit .= " ORDER BY fs.situation_counter"; - $sql .= " AND ( f.type != ".self::TYPE_SITUATION." OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir + // Select the last situation invoice + $sqlSit = 'SELECT MAX(fs.rowid)'; + $sqlSit .= " FROM ".MAIN_DB_PREFIX."facture as fs"; + $sqlSit .= " WHERE fs.entity IN (".getEntity('invoice').")"; + $sqlSit .= " AND fs.type = ".self::TYPE_SITUATION; + $sqlSit .= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; + $sqlSit .= " GROUP BY fs.situation_cycle_ref"; + $sqlSit .= " ORDER BY fs.situation_counter"; + $sql .= " AND ( f.type != ".self::TYPE_SITUATION." OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir } else { - $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir + $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir } if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; @@ -3999,16 +3999,16 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @param User $user Object user * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ - public function load_board($user) + public function load_board($user) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $clause = " WHERE"; @@ -4071,7 +4071,7 @@ class Facture extends CommonInvoice * * @return array Liste des id contacts facturation */ - public function getIdBillingContact() + public function getIdBillingContact() { return $this->getIdContact('external', 'BILLING'); } @@ -4081,7 +4081,7 @@ class Facture extends CommonInvoice * * @return array Liste des id contacts livraison */ - public function getIdShippingContact() + public function getIdShippingContact() { return $this->getIdContact('external', 'SHIPPING'); } @@ -4095,7 +4095,7 @@ class Facture extends CommonInvoice * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines * @return void */ - public function initAsSpecimen($option = '') + public function initAsSpecimen($option = '') { global $conf, $langs; @@ -4103,7 +4103,7 @@ class Facture 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(); $sql = "SELECT rowid"; @@ -4250,15 +4250,15 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @return int <0 if KO, >0 if OK */ - public function load_state_board() + public function load_state_board() { - // phpcs:enable + // phpcs:enable global $conf, $user; $this->nb = array(); @@ -4283,7 +4283,7 @@ class Facture extends CommonInvoice { $this->nb["invoices"] = $obj->nb; } - $this->db->free($resql); + $this->db->free($resql); return 1; } else { dol_print_error($this->db); @@ -4297,9 +4297,9 @@ class Facture extends CommonInvoice * * @return int >0 if OK, <0 if KO */ - public function getLinesArray() + public function getLinesArray() { - return $this->fetch_lines(); + return $this->fetch_lines(); } /** @@ -4344,7 +4344,7 @@ class Facture extends CommonInvoice * * @return int >= 1 if OK, -1 if error */ - public function newCycle() + public function newCycle() { $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")"; @@ -4367,27 +4367,27 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Checks if the invoice is the first of a cycle * * @return boolean */ - public function is_first() + public function is_first() { - // phpcs:enable + // phpcs:enable return ($this->situation_counter == 1); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns an array containing the previous situations as Facture objects * * @return mixed -1 if error, array of previous situations */ - public function get_prev_sits() + public function get_prev_sits() { - // phpcs:enable + // phpcs:enable global $conf; $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture'; @@ -4419,7 +4419,7 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function setFinal(User $user, $notrigger = 0) + public function setFinal(User $user, $notrigger = 0) { $error = 0; @@ -4458,15 +4458,15 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Checks if the invoice is the last in its cycle * * @return bool Last of the cycle status */ - public function is_last_in_cycle() + public function is_last_in_cycle() { - // phpcs:enable + // phpcs:enable global $conf; if (!empty($this->situation_cycle_ref)) { @@ -4524,21 +4524,21 @@ class Facture extends CommonInvoice $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay); if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) { - $totalpaye = $this->getSommePaiement(); - $totalpaye = floatval($totalpaye); - $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); - if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) - { - if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) - { - $hasDelay = 1; - } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) - { - $hasDelay = 1; - } else { - $hasDelay = 0; - } - } + $totalpaye = $this->getSommePaiement(); + $totalpaye = floatval($totalpaye); + $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); + if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) + { + if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } else { + $hasDelay = 0; + } + } } return $hasDelay; @@ -4589,45 +4589,45 @@ class Facture extends CommonInvoice public function getRetainedWarrantyAmount($rounding = -1) { global $conf; - if (empty($this->retained_warranty)) { - return -1; - } + if (empty($this->retained_warranty)) { + return -1; + } - $retainedWarrantyAmount = 0; + $retainedWarrantyAmount = 0; - // Billed - retained warranty - if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) - { - $displayWarranty = true; - // Check if this situation invoice is 100% for real - if (!empty($this->lines)) { - foreach ($this->lines as $i => $line) { - if ($line->product_type < 2 && $line->situation_percent < 100) { - $displayWarranty = false; - break; - } - } - } + // Billed - retained warranty + if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) + { + $displayWarranty = true; + // Check if this situation invoice is 100% for real + if (!empty($this->lines)) { + foreach ($this->lines as $i => $line) { + if ($line->product_type < 2 && $line->situation_percent < 100) { + $displayWarranty = false; + break; + } + } + } - if ($displayWarranty && !empty($this->situation_final)) - { - $this->fetchPreviousNextSituationInvoice(); - $TPreviousIncoice = $this->tab_previous_situation_invoice; + if ($displayWarranty && !empty($this->situation_final)) + { + $this->fetchPreviousNextSituationInvoice(); + $TPreviousIncoice = $this->tab_previous_situation_invoice; - $total2BillWT = 0; - foreach ($TPreviousIncoice as &$fac) { - $total2BillWT += $fac->total_ttc; - } - $total2BillWT += $this->total_ttc; + $total2BillWT = 0; + foreach ($TPreviousIncoice as &$fac) { + $total2BillWT += $fac->total_ttc; + } + $total2BillWT += $this->total_ttc; - $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100; - } else { - return -1; - } - } else { - // Because one day retained warranty could be used on standard invoices - $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100; - } + $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100; + } else { + return -1; + } + } else { + // Because one day retained warranty could be used on standard invoices + $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100; + } if ($rounding < 0) { $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT); @@ -4637,7 +4637,7 @@ class Facture extends CommonInvoice return round($retainedWarrantyAmount, $rounding); } - return $retainedWarrantyAmount; + return $retainedWarrantyAmount; } /** @@ -4648,28 +4648,28 @@ class Facture extends CommonInvoice */ public function setRetainedWarranty($value) { - dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')'); - if ($this->statut >= 0) - { - $fieldname = 'retained_warranty'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.floatval($value); - $sql .= ' WHERE rowid='.$this->id; + dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')'); + if ($this->statut >= 0) + { + $fieldname = 'retained_warranty'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.floatval($value); + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->retained_warranty = floatval($value); - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + if ($this->db->query($sql)) + { + $this->retained_warranty = floatval($value); + return 1; + } else { + dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } else { + dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } @@ -4682,33 +4682,33 @@ class Facture extends CommonInvoice */ public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false) { - if (!$timestamp && $dateYmd) { - $timestamp = $this->db->jdate($dateYmd); - } + if (!$timestamp && $dateYmd) { + $timestamp = $this->db->jdate($dateYmd); + } - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')'); - if ($this->statut >= 0) - { - $fieldname = 'retained_warranty_date_limit'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); - $sql .= ' WHERE rowid='.$this->id; + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')'); + if ($this->statut >= 0) + { + $fieldname = 'retained_warranty_date_limit'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->retained_warranty_date_limit = $timestamp; - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + if ($this->db->query($sql)) + { + $this->retained_warranty_date_limit = $timestamp; + return 1; + } else { + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } else { + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } } @@ -4718,12 +4718,12 @@ class Facture extends CommonInvoice */ class FactureLigne extends CommonInvoiceLine { - /** + /** * @var string ID to identify managed object */ public $element = 'facturedet'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'facturedet'; @@ -4809,7 +4809,7 @@ class FactureLigne extends CommonInvoiceLine * @param int $rowid id of invoice line to get * @return int <0 if KO, >0 if OK */ - public function fetch($rowid) + public function fetch($rowid) { $sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,'; $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,'; @@ -4888,7 +4888,7 @@ class FactureLigne extends CommonInvoiceLine return 1; } else { - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -4900,15 +4900,15 @@ class FactureLigne extends CommonInvoiceLine * @param int $noerrorifdiscountalreadylinked 1=Do not make error if lines is linked to a discount and discount already linked to another * @return int <0 if KO, >0 if OK */ - public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0) + public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0) { global $langs, $user, $conf; $error = 0; - $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. + $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. - dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); + dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); // Clean parameters $this->desc = trim($this->desc); @@ -4983,7 +4983,7 @@ class FactureLigne extends CommonInvoiceLine $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " '".$this->db->escape($this->desc)."',"; $sql .= " ".price2num($this->qty).","; - $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; $sql .= " ".price2num($this->tva_tx).","; $sql .= " ".price2num($this->localtax1_tx).","; $sql .= " ".price2num($this->localtax2_tx).","; @@ -5028,14 +5028,14 @@ class FactureLigne extends CommonInvoiceLine $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet'); $this->rowid = $this->id; // For backward compatibility - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } // Si fk_remise_except defini, on lie la remise a la facture // ce qui la flague comme "consommee". @@ -5048,16 +5048,16 @@ class FactureLigne extends CommonInvoiceLine // Check if discount was found if ($result > 0) { - // Check if discount not already affected to another invoice + // Check if discount not already affected to another invoice if ($discount->fk_facture_line > 0) { - if (empty($noerrorifdiscountalreadylinked)) - { - $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id); - dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -3; - } + if (empty($noerrorifdiscountalreadylinked)) + { + $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id); + dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -3; + } } else { $result = $discount->link_to_invoice($this->rowid, 0); if ($result < 0) @@ -5084,14 +5084,14 @@ class FactureLigne extends CommonInvoiceLine if (!$notrigger) { - // Call trigger - $result = $this->call_trigger('LINEBILL_INSERT', $user); - if ($result < 0) - { + // Call trigger + $result = $this->call_trigger('LINEBILL_INSERT', $user); + if ($result < 0) + { $this->db->rollback(); return -2; } - // End call triggers + // End call triggers } $this->db->commit(); @@ -5110,7 +5110,7 @@ class FactureLigne extends CommonInvoiceLine * @param int $notrigger Disable triggers * @return int <0 if KO, >0 if OK */ - public function update($user = '', $notrigger = 0) + public function update($user = '', $notrigger = 0) { global $user, $conf; @@ -5157,35 +5157,35 @@ class FactureLigne extends CommonInvoiceLine $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; - $sql .= " description='".$this->db->escape($this->desc)."'"; - $sql .= " ref_ext='".$this->db->escape($this->ref_ext)."'"; - $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); - $sql .= ", subprice=".price2num($this->subprice).""; - $sql .= ", remise_percent=".price2num($this->remise_percent).""; - if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except; - else $sql .= ", fk_remise_except=null"; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= " ref_ext='".$this->db->escape($this->ref_ext)."'"; + $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", subprice=".price2num($this->subprice).""; + $sql .= ", remise_percent=".price2num($this->remise_percent).""; + if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except; + else $sql .= ", fk_remise_except=null"; $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'"; - $sql .= ", tva_tx=".price2num($this->tva_tx).""; - $sql .= ", localtax1_tx=".price2num($this->localtax1_tx).""; - $sql .= ", localtax2_tx=".price2num($this->localtax2_tx).""; + $sql .= ", tva_tx=".price2num($this->tva_tx).""; + $sql .= ", localtax1_tx=".price2num($this->localtax1_tx).""; + $sql .= ", localtax2_tx=".price2num($this->localtax2_tx).""; $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql .= ", qty=".price2num($this->qty); - $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); - $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); - $sql .= ", product_type=".$this->product_type; - $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; - $sql .= ", special_code='".$this->db->escape($this->special_code)."'"; - if (empty($this->skip_update_total)) - { - $sql .= ", total_ht=".price2num($this->total_ht); - $sql .= ", total_tva=".price2num($this->total_tva); - $sql .= ", total_ttc=".price2num($this->total_ttc); - $sql .= ", total_localtax1=".price2num($this->total_localtax1); - $sql .= ", total_localtax2=".price2num($this->total_localtax2); - } + $sql .= ", qty=".price2num($this->qty); + $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); + $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= ", product_type=".$this->product_type; + $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; + $sql .= ", special_code='".$this->db->escape($this->special_code)."'"; + if (empty($this->skip_update_total)) + { + $sql .= ", total_ht=".price2num($this->total_ht); + $sql .= ", total_tva=".price2num($this->total_tva); + $sql .= ", total_ttc=".price2num($this->total_ttc); + $sql .= ", total_localtax1=".price2num($this->total_localtax1); + $sql .= ", total_localtax2=".price2num($this->total_localtax2); + } $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); $sql .= ", buy_price_ht='".price2num($this->pa_ht)."'"; $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); @@ -5196,9 +5196,9 @@ class FactureLigne extends CommonInvoiceLine // Multicurrency $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; $sql .= " WHERE rowid = ".$this->rowid; @@ -5206,26 +5206,26 @@ class FactureLigne extends CommonInvoiceLine $resql = $this->db->query($sql); if ($resql) { - if (!$error) - { - $this->id = $this->rowid; - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $this->id = $this->rowid; + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('LINEBILL_UPDATE', $user); - if ($result < 0) + // Call trigger + $result = $this->call_trigger('LINEBILL_UPDATE', $user); + if ($result < 0) { $this->db->rollback(); return -2; } - // End call triggers + // End call triggers } $this->db->commit(); return 1; @@ -5239,10 +5239,10 @@ class FactureLigne extends CommonInvoiceLine /** * Delete line in database * TODO Add param User $user and notrigger (see skeleton) - * + * * @return int <0 if KO, >0 if OK */ - public function delete() + public function delete() { global $user; @@ -5257,13 +5257,13 @@ class FactureLigne extends CommonInvoiceLine } // End call triggers - // extrafields - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } + // extrafields + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); @@ -5278,16 +5278,16 @@ class FactureLigne extends CommonInvoiceLine } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Update DB line fields total_xxx + * Update DB line fields total_xxx * Used by migration * * @return int <0 if KO, >0 if OK */ - public function update_total() + public function update_total() { - // phpcs:enable + // phpcs:enable $this->db->begin(); dol_syslog(get_class($this)."::update_total", LOG_DEBUG); @@ -5318,7 +5318,7 @@ class FactureLigne extends CommonInvoiceLine } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns situation_percent of the previous line. * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line. @@ -5327,14 +5327,14 @@ class FactureLigne extends CommonInvoiceLine * @param bool $include_credit_note Include credit note or not * @return int >= 0 */ - public function get_prev_progress($invoiceid, $include_credit_note = true) + public function get_prev_progress($invoiceid, $include_credit_note = true) { - // phpcs:enable + // phpcs:enable global $invoicecache; if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") { return 0; } else { - // If invoice is not a situation invoice, this->fk_prev_id is used for something else + // If invoice is not a situation invoice, this->fk_prev_id is used for something else if (!isset($invoicecache[$invoiceid])) { $invoicecache[$invoiceid] = new Facture($this->db); $invoicecache[$invoiceid]->fetch($invoiceid); @@ -5349,20 +5349,20 @@ class FactureLigne extends CommonInvoiceLine $returnPercent = floatval($res['situation_percent']); if ($include_credit_note) { - $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd'; - $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) '; - $sql .= ' WHERE fd.fk_prev_id ='.$this->fk_prev_id; - $sql .= ' AND f.situation_cycle_ref = '.$invoicecache[$invoiceid]->situation_cycle_ref; // Prevent cycle outed - $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE; + $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd'; + $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) '; + $sql .= ' WHERE fd.fk_prev_id ='.$this->fk_prev_id; + $sql .= ' AND f.situation_cycle_ref = '.$invoicecache[$invoiceid]->situation_cycle_ref; // Prevent cycle outed + $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE; - $res = $this->db->query($sql); - if ($res) { - while ($obj = $this->db->fetch_object($res)) { - $returnPercent = $returnPercent + floatval($obj->situation_percent); - } - } else { - dol_print_error($this->db); - } + $res = $this->db->query($sql); + if ($res) { + while ($obj = $this->db->fetch_object($res)) { + $returnPercent = $returnPercent + floatval($obj->situation_percent); + } + } else { + dol_print_error($this->db); + } } return $returnPercent; diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 0331861ea03..606e4e626b0 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -177,10 +177,10 @@ if (empty($reshook)) if ($canvas) $object->canvas = $canvas; $object->entity = (GETPOSTISSET('entity') ?GETPOST('entity', 'int') : $conf->entity); - $object->socid = GETPOST("socid", 'int'); + $object->socid = GETPOST("socid", 'int'); $object->lastname = GETPOST("lastname", 'alpha'); $object->firstname = GETPOST("firstname", 'alpha'); - $object->civility_code = GETPOST("civility_code", 'alpha'); + $object->civility_code = GETPOST("civility_code", 'alpha'); $object->poste = GETPOST("poste", 'alpha'); $object->address = GETPOST("address", 'alpha'); $object->zip = GETPOST("zipcode", 'alpha'); @@ -1355,7 +1355,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->fetch_thirdparty(); - if (! empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { + if (!empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3) { print '
'; @@ -1368,11 +1368,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; + if ($action != 'editlevel' && $user->rights->societe->contact->creer) print ''; print '
'; print $langs->trans('ProspectLevel'); print ''; - if ($action != 'editlevel' && $user->rights->societe->contact->creer) print 'id . '">' . img_edit($langs->trans('Modify'), 1) . 'id.'">'.img_edit($langs->trans('Modify'), 1).'
'; print ''; if ($action == 'editlevel') { - $formcompany->formProspectContactLevel($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_prospectlevel, 'prospect_contact_level_id', 1); + $formcompany->formProspectContactLevel($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_prospectlevel, 'prospect_contact_level_id', 1); } else { print $object->getLibProspLevel(); } @@ -1381,13 +1381,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Status of prospection $object->loadCacheOfProspStatus(); - print '' . $langs->trans("StatusProsp") . '' . $object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); + print ''.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); print '     '; print '
'; foreach ($object->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 ($object->stcomm_id != $val['id']) print '' . img_action($titlealt, $val['code'], $val['picto']) . ''; + if ($object->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; } print '
'; diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index a474df3b910..1772f94abfb 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -158,8 +158,8 @@ $fieldstosearchall = array( 'p.phone_perso'=>"PhonePerso", 'p.phone_mobile'=>"PhoneMobile", 'p.fax'=>"Fax", - 'p.note_public'=>"NotePublic", - 'p.note_private'=>"NotePrivate", + 'p.note_public'=>"NotePublic", + 'p.note_private'=>"NotePrivate", ); // Definition of fields for list @@ -541,7 +541,7 @@ $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; if ($user->rights->societe->contact->creer) { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewContactAddress'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewContactAddress'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?action=create'); } print '
'; @@ -734,9 +734,9 @@ if (!empty($arrayfields['p.thirdparty']['checked'])) if (!empty($arrayfields['p.priv']['checked'])) { print ''; - $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); - print $form->selectarray('search_priv', $selectarray, $search_priv, 1); - print ''; + $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); + print $form->selectarray('search_priv', $selectarray, $search_priv, 1); + print ''; } // Prospect level if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) @@ -808,7 +808,7 @@ if (!empty($arrayfields['p.town']['checked'])) print_liste_field_ //if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); //if (! empty($arrayfields['region.nom']['checked'])) print_liste_field_titre($arrayfields['region.nom']['label'],$_SERVER["PHP_SELF"],"region.nom","",$param,'',$sortfield,$sortorder); if (!empty($arrayfields['country.code_iso']['checked'])) { - print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "co.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "co.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); } if (!empty($arrayfields['p.phone']['checked'])) print_liste_field_titre($arrayfields['p.phone']['label'], $_SERVER["PHP_SELF"], "p.phone", $begin, $param, '', $sortfield, $sortorder); if (!empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre($arrayfields['p.phone_perso']['label'], $_SERVER["PHP_SELF"], "p.phone_perso", $begin, $param, '', $sortfield, $sortorder); @@ -831,24 +831,24 @@ if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) print_liste_field_ 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); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (!empty($arrayfields['p.datec']['checked'])) { - print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } if (!empty($arrayfields['p.tms']['checked'])) { - print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } if (!empty($arrayfields['p.statut']['checked'])) { - print_liste_field_titre($arrayfields['p.statut']['label'], $_SERVER["PHP_SELF"], "p.statut", "", $param, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre($arrayfields['p.statut']['label'], $_SERVER["PHP_SELF"], "p.statut", "", $param, '', $sortfield, $sortorder, 'center '); } if (!empty($arrayfields['p.import_key']['checked'])) { - print_liste_field_titre($arrayfields['p.import_key']['label'], $_SERVER["PHP_SELF"], "p.import_key", "", $param, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre($arrayfields['p.import_key']['label'], $_SERVER["PHP_SELF"], "p.import_key", "", $param, '', $sortfield, $sortorder, 'center '); } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; @@ -986,15 +986,15 @@ while ($i < min($num, $limit)) } } } - // Company + // Company if (!empty($arrayfields['p.thirdparty']['checked'])) { print ''; if ($obj->socid) { - $objsoc = new Societe($db); - $objsoc->fetch($obj->socid); - print $objsoc->getNomUrl(1); + $objsoc = new Societe($db); + $objsoc->fetch($obj->socid); + print $objsoc->getNomUrl(1); } else print ' '; print ''; if (!$i) $totalarray['nbfield']++; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 5048bcd31e8..73a6043f095 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -170,7 +170,7 @@ class CMailFile $this->sendmode = ''; if (!empty($this->sendcontext)) { $smtpContextKey = strtoupper($this->sendcontext); - $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_' . $smtpContextKey; + $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_'.$smtpContextKey; $smtpContextSendMode = $conf->global->{$keyForSMTPSendMode}; if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { $this->sendmode = $smtpContextSendMode; @@ -443,9 +443,9 @@ class CMailFile // Set the From address with an associative array //$this->message->setFrom(array('john@doe.com' => 'John Doe')); - if (! empty($this->addr_from)) { + if (!empty($this->addr_from)) { try { - if (! empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) { + if (!empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) { // Prevent email spoofing for smtp server with a strict configuration $regexp = '/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; // This regular expression extracts all emails from a string $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom); @@ -465,7 +465,7 @@ class CMailFile } // Set the To addresses with an associative array - if (! empty($this->addr_to)) { + if (!empty($this->addr_to)) { try { $result = $this->message->setTo($this->getArrayAddress($this->addr_to)); } catch (Exception $e) { @@ -473,7 +473,7 @@ class CMailFile } } - if (! empty($this->reply_to)) { + if (!empty($this->reply_to)) { try { $result = $this->message->SetReplyTo($this->getArrayAddress($this->reply_to)); } catch (Exception $e) { @@ -529,8 +529,8 @@ class CMailFile } } - if (! empty($this->addr_cc)) $this->message->setCc($this->getArrayAddress($this->addr_cc)); - if (! empty($this->addr_bcc)) $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); + if (!empty($this->addr_cc)) $this->message->setCc($this->getArrayAddress($this->addr_cc)); + if (!empty($this->addr_bcc)) $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); //if (! empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to)); if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from)); } else { @@ -641,15 +641,15 @@ class CMailFile $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS'; if (!empty($this->sendcontext)) { $smtpContextKey = strtoupper($this->sendcontext); - $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_' . $smtpContextKey; + $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_'.$smtpContextKey; $smtpContextSendMode = $conf->global->{$keyForSMTPSendMode}; if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { - $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_' . $smtpContextKey; - $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_' . $smtpContextKey; - $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_' . $smtpContextKey; - $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_' . $smtpContextKey; - $keyfortls = 'MAIN_MAIL_EMAIL_TLS_' . $smtpContextKey; - $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_' . $smtpContextKey; + $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey; + $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey; + $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey; + $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey; + $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey; + $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey; } } diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index d3abceb7097..2396ecb808e 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -4567,245 +4567,245 @@ abstract class CommonObject if (empty($reshook)) { - dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); + dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - // Increase limit for PDF build - $err = error_reporting(); - error_reporting(0); - @set_time_limit(120); - error_reporting($err); + // Increase limit for PDF build + $err = error_reporting(); + error_reporting(0); + @set_time_limit(120); + error_reporting($err); - // If selected model is a filename template (then $modele="modelname" or "modelname:filename") - $tmp = explode(':', $modele, 2); - if (!empty($tmp[1])) - { - $modele = $tmp[0]; - $srctemplatepath = $tmp[1]; - } + // If selected model is a filename template (then $modele="modelname" or "modelname:filename") + $tmp = explode(':', $modele, 2); + if (!empty($tmp[1])) + { + $modele = $tmp[0]; + $srctemplatepath = $tmp[1]; + } - // Search template files + // Search template files $file = ''; $classname = ''; $filefound = ''; - $dirmodels = array('/'); - if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { - foreach (array('doc', 'pdf') as $prefix) - { - if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php - else $file = $prefix."_".$modele.".modules.php"; + $dirmodels = array('/'); + if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + foreach (array('doc', 'pdf') as $prefix) + { + if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php + else $file = $prefix."_".$modele.".modules.php"; - // On verifie l'emplacement du modele - $file = dol_buildpath($reldir.$modelspath.$file, 0); - if (file_exists($file)) - { - $filefound = $file; - $classname = $prefix.'_'.$modele; - break; - } - } - if ($filefound) break; - } + // On verifie l'emplacement du modele + $file = dol_buildpath($reldir.$modelspath.$file, 0); + if (file_exists($file)) + { + $filefound = $file; + $classname = $prefix.'_'.$modele; + break; + } + } + if ($filefound) break; + } - // If generator was found - if ($filefound) - { - global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. + // If generator was found + if ($filefound) + { + global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. - require_once $file; + require_once $file; - $obj = new $classname($this->db); + $obj = new $classname($this->db); - // If generator is ODT, we must have srctemplatepath defined, if not we set it. - if ($obj->type == 'odt' && empty($srctemplatepath)) - { - $varfortemplatedir = $obj->scandir; - if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) - { - $dirtoscan = $conf->global->$varfortemplatedir; + // If generator is ODT, we must have srctemplatepath defined, if not we set it. + if ($obj->type == 'odt' && empty($srctemplatepath)) + { + $varfortemplatedir = $obj->scandir; + if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) + { + $dirtoscan = $conf->global->$varfortemplatedir; - $listoffiles = array(); + $listoffiles = array(); - // Now we add first model found in directories scanned - $listofdir = explode(',', $dirtoscan); - foreach ($listofdir as $key => $tmpdir) - { - $tmpdir = trim($tmpdir); - $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); - if (!$tmpdir) { unset($listofdir[$key]); continue; } - if (is_dir($tmpdir)) - { - $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); - if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); - } - } + // Now we add first model found in directories scanned + $listofdir = explode(',', $dirtoscan); + foreach ($listofdir as $key => $tmpdir) + { + $tmpdir = trim($tmpdir); + $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); + if (!$tmpdir) { unset($listofdir[$key]); continue; } + if (is_dir($tmpdir)) + { + $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); + if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); + } + } - if (count($listoffiles)) - { - foreach ($listoffiles as $record) - { - $srctemplatepath = $record['fullname']; - break; - } - } - } + if (count($listoffiles)) + { + foreach ($listoffiles as $record) + { + $srctemplatepath = $record['fullname']; + break; + } + } + } - if (empty($srctemplatepath)) - { - $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; - return -1; - } - } + if (empty($srctemplatepath)) + { + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; + return -1; + } + } - if ($obj->type == 'odt' && !empty($srctemplatepath)) - { - if (!dol_is_file($srctemplatepath)) - { - dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING); - $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; - return -1; - } - } + if ($obj->type == 'odt' && !empty($srctemplatepath)) + { + if (!dol_is_file($srctemplatepath)) + { + dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING); + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; + return -1; + } + } - // We save charset_output to restore it because write_file can change it if needed for - // output format that does not support UTF8. - $sav_charset_output = $outputlangs->charset_output; + // We save charset_output to restore it because write_file can change it if needed for + // output format that does not support UTF8. + $sav_charset_output = $outputlangs->charset_output; - if (in_array(get_class($this), array('Adherent'))) - { - $arrayofrecords = array(); // The write_file of templates of adherent class need this var - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); - } else { - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); - } - // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. + if (in_array(get_class($this), array('Adherent'))) + { + $arrayofrecords = array(); // The write_file of templates of adherent class need this var + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); + } else { + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); + } + // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. - if ($resultwritefile > 0) - { - $outputlangs->charset_output = $sav_charset_output; + if ($resultwritefile > 0) + { + $outputlangs->charset_output = $sav_charset_output; - // We delete old preview - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_delete_preview($this); + // We delete old preview + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + dol_delete_preview($this); - // Index file in database - if (!empty($obj->result['fullpath'])) - { - $destfull = $obj->result['fullpath']; - $upload_dir = dirname($destfull); - $destfile = basename($destfull); - $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir); + // Index file in database + if (!empty($obj->result['fullpath'])) + { + $destfull = $obj->result['fullpath']; + $upload_dir = dirname($destfull); + $destfile = basename($destfull); + $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir); - if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir - { - $filename = basename($destfile); - $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); - $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); + if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir + { + $filename = basename($destfile); + $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); + $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile = new EcmFiles($this->db); - $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename); + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile = new EcmFiles($this->db); + $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename); - // Set the public "share" key - $setsharekey = false; - if ($this->element == 'propal') - { - $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok - if ($useonlinesignature) $setsharekey = true; - if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true; - } - if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } - if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } - if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } + // Set the public "share" key + $setsharekey = false; + if ($this->element == 'propal') + { + $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok + if ($useonlinesignature) $setsharekey = true; + if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true; + } + if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } + if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } + if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } - if ($setsharekey) { - if (empty($ecmfile->share)) // Because object not found or share not set yet - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $ecmfile->share = getRandomPassword(true); - } - } + if ($setsharekey) { + if (empty($ecmfile->share)) // Because object not found or share not set yet + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + } + } - if ($result > 0) - { - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $result = $ecmfile->update($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } else { - $ecmfile->entity = $conf->entity; - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $ecmfile->src_object_type = $this->table_element; - $ecmfile->src_object_id = $this->id; + if ($result > 0) + { + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $result = $ecmfile->update($user); + if ($result < 0) { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } else { + $ecmfile->entity = $conf->entity; + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $ecmfile->src_object_type = $this->table_element; + $ecmfile->src_object_id = $this->id; - $result = $ecmfile->create($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } + $result = $ecmfile->create($user); + if ($result < 0) { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } - /*$this->result['fullname']=$destfull; + /*$this->result['fullname']=$destfull; $this->result['filepath']=$ecmfile->filepath; $this->result['filename']=$ecmfile->filename;*/ - //var_dump($obj->update_main_doc_field);exit; + //var_dump($obj->update_main_doc_field);exit; - // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) - $update_main_doc_field = 0; - if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; - if ($update_main_doc_field && !empty($this->table_element)) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'"; - $sql .= ' WHERE rowid = '.$this->id; + // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) + $update_main_doc_field = 0; + if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; + if ($update_main_doc_field && !empty($this->table_element)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'"; + $sql .= ' WHERE rowid = '.$this->id; - $resql = $this->db->query($sql); - if (!$resql) { + $resql = $this->db->query($sql); + if (!$resql) { dol_print_error($this->db); } else { - $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; - } - } - } - } else { - dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); - } + $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; + } + } + } + } else { + dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); + } - // Success in building document. We build meta file. - dol_meta_create($this); + // Success in building document. We build meta file. + dol_meta_create($this); - return 1; - } else { - $outputlangs->charset_output = $sav_charset_output; - dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); - return -1; - } - } else { - if (!$filefound) { - $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele; - dol_print_error('', $this->error); - } else { - $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound); - dol_print_error('', $this->error); - } - return -1; - } + return 1; + } else { + $outputlangs->charset_output = $sav_charset_output; + dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); + return -1; + } + } else { + if (!$filefound) { + $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele; + dol_print_error('', $this->error); + } else { + $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound); + dol_print_error('', $this->error); + } + return -1; + } } else return $reshook; } @@ -7987,46 +7987,46 @@ abstract class CommonObject // Delete cascade first if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) { - foreach ($this->childtablesoncascade as $table) - { - $deleteFromObject = explode(':', $table); - if (count($deleteFromObject) >= 2) { - $className = str_replace('@', '', $deleteFromObject[0]); - $filePath = $deleteFromObject[1]; - $columnName = $deleteFromObject[2]; - if (dol_include_once($filePath)) { - $childObject = new $className($this->db); - if (method_exists($childObject, 'deleteByParentField')) { - $result = $childObject->deleteByParentField($this->id, $columnName); - if ($result < 0) { + foreach ($this->childtablesoncascade as $table) + { + $deleteFromObject = explode(':', $table); + if (count($deleteFromObject) >= 2) { + $className = str_replace('@', '', $deleteFromObject[0]); + $filePath = $deleteFromObject[1]; + $columnName = $deleteFromObject[2]; + if (dol_include_once($filePath)) { + $childObject = new $className($this->db); + if (method_exists($childObject, 'deleteByParentField')) { + $result = $childObject->deleteByParentField($this->id, $columnName); + if ($result < 0) { $error++; - $this->errors[] = $childObject->error; - break; - } - } else { + $this->errors[] = $childObject->error; + break; + } + } else { $error++; $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it"; break; } - } else { - $error++; - $this->errors[] = 'Cannot include child class file '.$filePath; - break; - } - } else { - // Delete record in child table - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id; - - $resql = $this->db->query($sql); - if (!$resql) { + } else { $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; + $this->errors[] = 'Cannot include child class file '.$filePath; break; - } - } - } - } + } + } else { + // Delete record in child table + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id; + + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + break; + } + } + } + } if (!$error) { if (!$notrigger) { diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 42691f14307..ad7d93506f4 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -31,385 +31,385 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; */ class CoreObject extends CommonObject { - public $withChild = true; + public $withChild = true; - /** - * @var Array $_fields Fields to synchronize with Database - */ - protected $fields = array(); + /** + * @var Array $_fields Fields to synchronize with Database + */ + protected $fields = array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct(DoliDB &$db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB &$db) + { + $this->db = $db; + } - /** - * Function to init fields - * - * @return bool - */ - protected function init() - { - $this->id = 0; - $this->datec = 0; - $this->tms = 0; + /** + * Function to init fields + * + * @return bool + */ + protected function init() + { + $this->id = 0; + $this->datec = 0; + $this->tms = 0; - if (!empty($this->fields)) - { - foreach ($this->fields as $field=>$info) - { - if ($this->isDate($info)) $this->{$field} = time(); - elseif ($this->isArray($info)) $this->{$field} = array(); - elseif ($this->isInt($info)) $this->{$field} = (int) 0; - elseif ($this->isFloat($info)) $this->{$field} = (double) 0; - else $this->{$field} = ''; - } + if (!empty($this->fields)) + { + foreach ($this->fields as $field=>$info) + { + if ($this->isDate($info)) $this->{$field} = time(); + elseif ($this->isArray($info)) $this->{$field} = array(); + elseif ($this->isInt($info)) $this->{$field} = (int) 0; + elseif ($this->isFloat($info)) $this->{$field} = (double) 0; + else $this->{$field} = ''; + } - $this->to_delete = false; - $this->is_clone = false; + $this->to_delete = false; + $this->is_clone = false; - return true; - } else { - return false; - } - } + return true; + } else { + return false; + } + } - /** - * Test type of field - * - * @param string $field name of field - * @param string $type type of field to test - * @return boolean value of field or false - */ - private function checkFieldType($field, $type) - { - if (isset($this->fields[$field]) && method_exists($this, 'is_'.$type)) - { - return $this->{'is_'.$type}($this->fields[$field]); - } else { - return false; - } - } + /** + * Test type of field + * + * @param string $field name of field + * @param string $type type of field to test + * @return boolean value of field or false + */ + private function checkFieldType($field, $type) + { + if (isset($this->fields[$field]) && method_exists($this, 'is_'.$type)) + { + return $this->{'is_'.$type}($this->fields[$field]); + } else { + return false; + } + } - /** - * Get object and children from database - * - * @param int $id Id of object to load - * @param bool $loadChild used to load children from database - * @return int >0 if OK, <0 if KO, 0 if not found - */ - public function fetch($id, $loadChild = true) - { - $res = $this->fetchCommon($id); - if ($res > 0) { - if ($loadChild) $this->fetchChild(); - } + /** + * Get object and children from database + * + * @param int $id Id of object to load + * @param bool $loadChild used to load children from database + * @return int >0 if OK, <0 if KO, 0 if not found + */ + public function fetch($id, $loadChild = true) + { + $res = $this->fetchCommon($id); + if ($res > 0) { + if ($loadChild) $this->fetchChild(); + } - return $res; - } + return $res; + } - /** - * Function to instantiate a new child - * - * @param string $tabName Table name of child - * @param int $id If id is given, we try to return his key if exist or load if we try_to_load - * @param string $key Attribute name of the object id - * @param bool $try_to_load Force the fetch if an id is given - * @return int - */ - public function addChild($tabName, $id = 0, $key = 'id', $try_to_load = false) - { - if (!empty($id)) - { - foreach ($this->{$tabName} as $k=>&$object) - { - if ($object->{$key} === $id) return $k; - } - } + /** + * Function to instantiate a new child + * + * @param string $tabName Table name of child + * @param int $id If id is given, we try to return his key if exist or load if we try_to_load + * @param string $key Attribute name of the object id + * @param bool $try_to_load Force the fetch if an id is given + * @return int + */ + public function addChild($tabName, $id = 0, $key = 'id', $try_to_load = false) + { + if (!empty($id)) + { + foreach ($this->{$tabName} as $k=>&$object) + { + if ($object->{$key} === $id) return $k; + } + } - $k = count($this->{$tabName}); + $k = count($this->{$tabName}); - $className = ucfirst($tabName); - $this->{$tabName}[$k] = new $className($this->db); - if ($id > 0 && $key === 'id' && $try_to_load) - { - $this->{$tabName}[$k]->fetch($id); - } + $className = ucfirst($tabName); + $this->{$tabName}[$k] = new $className($this->db); + if ($id > 0 && $key === 'id' && $try_to_load) + { + $this->{$tabName}[$k]->fetch($id); + } - return $k; - } + return $k; + } - /** - * Function to set a child as to delete - * - * @param string $tabName Table name of child - * @param int $id Id of child to set as to delete - * @param string $key Attribute name of the object id - * @return bool - */ - public function removeChild($tabName, $id, $key = 'id') - { - foreach ($this->{$tabName} as &$object) - { - if ($object->{$key} == $id) - { - $object->to_delete = true; - return true; - } - } - return false; - } + /** + * Function to set a child as to delete + * + * @param string $tabName Table name of child + * @param int $id Id of child to set as to delete + * @param string $key Attribute name of the object id + * @return bool + */ + public function removeChild($tabName, $id, $key = 'id') + { + foreach ($this->{$tabName} as &$object) + { + if ($object->{$key} == $id) + { + $object->to_delete = true; + return true; + } + } + return false; + } - /** - * Function to fetch children objects - * - * @return void - */ - public function fetchChild() - { - if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) - { - foreach ($this->childtables as &$childTable) - { - $className = ucfirst($childTable); + /** + * Function to fetch children objects + * + * @return void + */ + public function fetchChild() + { + if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) + { + foreach ($this->childtables as &$childTable) + { + $className = ucfirst($childTable); - $this->{$className} = array(); + $this->{$className} = array(); - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$childTable.' WHERE '.$this->fk_element.' = '.$this->id; - $res = $this->db->query($sql); + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$childTable.' WHERE '.$this->fk_element.' = '.$this->id; + $res = $this->db->query($sql); - if ($res) - { - while ($obj = $this->db->fetch_object($res)) - { - $o = new $className($this->db); - $o->fetch($obj->rowid); + if ($res) + { + while ($obj = $this->db->fetch_object($res)) + { + $o = new $className($this->db); + $o->fetch($obj->rowid); - $this->{$className}[] = $o; - } - } else { - $this->errors[] = $this->db->lasterror(); - } - } - } - } + $this->{$className}[] = $o; + } + } else { + $this->errors[] = $this->db->lasterror(); + } + } + } + } - /** - * Function to update children data - * - * @param User $user user object - * @return void - */ - public function saveChild(User &$user) - { - if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) - { - foreach ($this->childtables as &$childTable) - { - $className = ucfirst($childTable); - if (!empty($this->{$className})) - { - foreach ($this->{$className} as $i => &$object) - { - $object->{$this->fk_element} = $this->id; + /** + * Function to update children data + * + * @param User $user user object + * @return void + */ + public function saveChild(User &$user) + { + if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) + { + foreach ($this->childtables as &$childTable) + { + $className = ucfirst($childTable); + if (!empty($this->{$className})) + { + foreach ($this->{$className} as $i => &$object) + { + $object->{$this->fk_element} = $this->id; - $object->update($user); - if ($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete == true) unset($this->{$className}[$i]); - } - } - } - } - } + $object->update($user); + if ($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete == true) unset($this->{$className}[$i]); + } + } + } + } + } - /** - * Function to update object or create or delete if needed - * - * @param User $user User object - * @return int < 0 if KO, > 0 if OK - */ - public function update(User &$user) - { - if (empty($this->id)) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed - elseif (isset($this->to_delete) && $this->to_delete == true) return $this->delete($user); + /** + * Function to update object or create or delete if needed + * + * @param User $user User object + * @return int < 0 if KO, > 0 if OK + */ + public function update(User &$user) + { + if (empty($this->id)) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed + elseif (isset($this->to_delete) && $this->to_delete == true) return $this->delete($user); - $error = 0; - $this->db->begin(); + $error = 0; + $this->db->begin(); - $res = $this->updateCommon($user); - if ($res) - { - $result = $this->call_trigger(strtoupper($this->element).'_UPDATE', $user); - if ($result < 0) $error++; - else $this->saveChild($user); - } else { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - } + $res = $this->updateCommon($user); + if ($res) + { + $result = $this->call_trigger(strtoupper($this->element).'_UPDATE', $user); + if ($result < 0) $error++; + else $this->saveChild($user); + } else { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } - if (empty($error)) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + if (empty($error)) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Function to create object in database - * - * @param User $user User object - * @return int < 0 if KO, > 0 if OK - */ - public function create(User $user) - { - if ($this->id > 0) return $this->update($user); + /** + * Function to create object in database + * + * @param User $user User object + * @return int < 0 if KO, > 0 if OK + */ + public function create(User $user) + { + if ($this->id > 0) return $this->update($user); - $error = 0; - $this->db->begin(); + $error = 0; + $this->db->begin(); - $res = $this->createCommon($user); - if ($res) - { - $this->id = $this->db->last_insert_id($this->table_element); + $res = $this->createCommon($user); + if ($res) + { + $this->id = $this->db->last_insert_id($this->table_element); - $result = $this->call_trigger(strtoupper($this->element).'_CREATE', $user); - if ($result < 0) $error++; - else $this->saveChild($user); - } else { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - } + $result = $this->call_trigger(strtoupper($this->element).'_CREATE', $user); + if ($result < 0) $error++; + else $this->saveChild($user); + } else { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } - if (empty($error)) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + if (empty($error)) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Function to delete object in database - * - * @param User $user user object - * @return int < 0 if KO, > 0 if OK - */ - public function delete(User &$user) - { - if ($this->id <= 0) return 0; + /** + * Function to delete object in database + * + * @param User $user user object + * @return int < 0 if KO, > 0 if OK + */ + public function delete(User &$user) + { + if ($this->id <= 0) return 0; - $error = 0; - $this->db->begin(); + $error = 0; + $this->db->begin(); - $result = $this->call_trigger(strtoupper($this->element).'_DELETE', $user); - if ($result < 0) $error++; + $result = $this->call_trigger(strtoupper($this->element).'_DELETE', $user); + if ($result < 0) $error++; - if (!$error) - { - $this->deleteCommon($user); - if ($this->withChild && !empty($this->childtables)) - { - foreach ($this->childtables as &$childTable) - { - $className = ucfirst($childTable); - if (!empty($this->{$className})) - { - foreach ($this->{$className} as &$object) - { - $object->delete($user); - } - } - } - } - } + if (!$error) + { + $this->deleteCommon($user); + if ($this->withChild && !empty($this->childtables)) + { + foreach ($this->childtables as &$childTable) + { + $className = ucfirst($childTable); + if (!empty($this->{$className})) + { + foreach ($this->{$className} as &$object) + { + $object->delete($user); + } + } + } + } + } - if (empty($error)) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - $this->db->rollback(); - return -1; - } - } + if (empty($error)) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + $this->db->rollback(); + return -1; + } + } - /** - * Function to get a formatted date - * - * @param string $field Attribute to return - * @param string $format Output date format - * @return string - */ - public function getDate($field, $format = '') - { - if (empty($this->{$field})) return ''; - else { - return dol_print_date($this->{$field}, $format); - } - } + /** + * Function to get a formatted date + * + * @param string $field Attribute to return + * @param string $format Output date format + * @return string + */ + public function getDate($field, $format = '') + { + if (empty($this->{$field})) return ''; + else { + return dol_print_date($this->{$field}, $format); + } + } - /** - * Function to set date in field - * - * @param string $field field to set - * @param string $date formatted date to convert - * @return mixed - */ - public function setDate($field, $date) - { - if (empty($date)) - { - $this->{$field} = 0; - } else { - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $this->{$field} = dol_stringtotime($date); - } + /** + * Function to set date in field + * + * @param string $field field to set + * @param string $date formatted date to convert + * @return mixed + */ + public function setDate($field, $date) + { + if (empty($date)) + { + $this->{$field} = 0; + } else { + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + $this->{$field} = dol_stringtotime($date); + } - return $this->{$field}; - } + return $this->{$field}; + } - /** - * Function to update current object - * - * @param array $Tab Array of values - * @return int - */ - public function setValues(&$Tab) - { - foreach ($Tab as $key => $value) - { - if ($this->checkFieldType($key, 'date')) - { - $this->setDate($key, $value); - } elseif ($this->checkFieldType($key, 'float')) - { - $this->{$key} = (double) price2num($value); - } elseif ($this->checkFieldType($key, 'int')) { - $this->{$key} = (int) price2num($value); - } else { - $this->{$key} = dol_string_nohtmltag($value); - } - } + /** + * Function to update current object + * + * @param array $Tab Array of values + * @return int + */ + public function setValues(&$Tab) + { + foreach ($Tab as $key => $value) + { + if ($this->checkFieldType($key, 'date')) + { + $this->setDate($key, $value); + } elseif ($this->checkFieldType($key, 'float')) + { + $this->{$key} = (double) price2num($value); + } elseif ($this->checkFieldType($key, 'int')) { + $this->{$key} = (int) price2num($value); + } else { + $this->{$key} = dol_string_nohtmltag($value); + } + } - return 1; - } + return 1; + } } diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 993528464fd..1ed6056404e 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -38,103 +38,103 @@ class ExtraFields { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** - * @var array Array with type of element (for what object is the extrafield) + * @var array Array with type of element (for what object is the extrafield) * @deprecated - */ - public $attribute_elementtype; + */ + public $attribute_elementtype; - /** - * @var array Array with type of the extra field + /** + * @var array Array with type of the extra field * @deprecated - */ - public $attribute_type; + */ + public $attribute_type; - /** - * @var array Array with label of extra field + /** + * @var array Array with label of extra field * @deprecated - */ - public $attribute_label; + */ + public $attribute_label; - /** - * @var array Array with size of extra field + /** + * @var array Array with size of extra field * @deprecated - */ + */ public $attribute_size; - /** - * @var array Array with list of possible values for some types of extra fields + /** + * @var array Array with list of possible values for some types of extra fields * @deprecated - */ + */ public $attribute_choice; - /** - * @var array Array to store compute formula for computed fields + /** + * @var array Array to store compute formula for computed fields * @deprecated - */ + */ public $attribute_computed; - /** - * @var array Array to store default value + /** + * @var array Array to store default value * @deprecated - */ + */ public $attribute_default; - /** - * @var array Array to store if attribute is unique or not + /** + * @var array Array to store if attribute is unique or not * @deprecated - */ + */ public $attribute_unique; - /** - * @var array Array to store if attribute is required or not + /** + * @var array Array to store if attribute is required or not * @deprecated - */ + */ public $attribute_required; - /** - * @var array Array to store parameters of attribute (used in select type) + /** + * @var array Array to store parameters of attribute (used in select type) * @deprecated - */ + */ public $attribute_param; - /** - * @var array Array to store position of attribute + /** + * @var array Array to store position of attribute * @deprecated - */ + */ public $attribute_pos; - /** - * @var array Array to store if attribute is editable regardless of the document status + /** + * @var array Array to store if attribute is editable regardless of the document status * @deprecated - */ + */ public $attribute_alwayseditable; - /** - * @var array Array to store permission to check + /** + * @var array Array to store permission to check * @deprecated - */ + */ public $attribute_perms; - /** - * @var array Array to store language file to translate label of values + /** + * @var array Array to store language file to translate label of values * @deprecated - */ + */ public $attribute_langfile; - /** - * @var array Array to store if field is visible by default on list + /** + * @var array Array to store if field is visible by default on list * @deprecated - */ + */ public $attribute_list; /** - * @var array New array to store extrafields definition - */ + * @var array New array to store extrafields definition + */ public $attributes; /** @@ -147,33 +147,33 @@ class ExtraFields */ public $errors = array(); - /** + /** * @var string DB Error number */ public $errno; public static $type2label = array( - 'varchar'=>'String1Line', - 'text'=>'TextLongNLines', - 'html'=>'HtmlText', - 'int'=>'Int', - 'double'=>'Float', - 'date'=>'Date', - 'datetime'=>'DateAndTime', - 'boolean'=>'Boolean', - 'price'=>'ExtrafieldPrice', - 'phone'=>'ExtrafieldPhone', - 'mail'=>'ExtrafieldMail', - 'url'=>'ExtrafieldUrl', - 'password' => 'ExtrafieldPassword', - 'select' => 'ExtrafieldSelect', - 'sellist' => 'ExtrafieldSelectList', - 'radio' => 'ExtrafieldRadio', - 'checkbox' => 'ExtrafieldCheckBox', - 'chkbxlst' => 'ExtrafieldCheckBoxFromList', - 'link' => 'ExtrafieldLink', - 'separate' => 'ExtrafieldSeparator', + 'varchar'=>'String1Line', + 'text'=>'TextLongNLines', + 'html'=>'HtmlText', + 'int'=>'Int', + 'double'=>'Float', + 'date'=>'Date', + 'datetime'=>'DateAndTime', + 'boolean'=>'Boolean', + 'price'=>'ExtrafieldPrice', + 'phone'=>'ExtrafieldPhone', + 'mail'=>'ExtrafieldMail', + 'url'=>'ExtrafieldUrl', + 'password' => 'ExtrafieldPassword', + 'select' => 'ExtrafieldSelect', + 'sellist' => 'ExtrafieldSelectList', + 'radio' => 'ExtrafieldRadio', + 'checkbox' => 'ExtrafieldCheckBox', + 'chkbxlst' => 'ExtrafieldCheckBoxFromList', + 'link' => 'ExtrafieldLink', + 'separate' => 'ExtrafieldSeparator', ); @@ -181,7 +181,7 @@ class ExtraFields * Constructor * * @param DoliDB $db Database handler - */ + */ public function __construct($db) { $this->db = $db; @@ -225,7 +225,7 @@ class ExtraFields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is a measure. Must show a total on lists - * @param int $printable Is extrafield displayed on PDF + * @param int $printable Is extrafield displayed on PDF * @return int <=0 if KO, >0 if OK */ public function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique = 0, $required = 0, $default_value = '', $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) @@ -345,7 +345,7 @@ class ExtraFields } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add description of a new optional attribute * @@ -368,13 +368,13 @@ class ExtraFields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is a measure. Must show a total on lists - * @param int $printable Is extrafield displayed on PDF + * @param int $printable Is extrafield displayed on PDF * @return int <=0 if KO, >0 if OK - * @throws Exception + * @throws Exception */ private function create_label($attrname, $label = '', $type = '', $pos = 0, $size = 0, $elementtype = 'member', $unique = 0, $required = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { - // phpcs:enable + // phpcs:enable global $conf, $user; if ($elementtype == 'thirdparty') $elementtype = 'societe'; @@ -485,33 +485,33 @@ class ExtraFields $result = $this->delete_label($attrname, $elementtype); if ($result < 0) { - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); - $error++; + $error++; } if (!$error) { - $sql = "SELECT COUNT(rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; - $sql .= " WHERE elementtype = '".$elementtype."'"; - $sql .= " AND name = '".$attrname."'"; - //$sql.= " AND entity IN (0,".$conf->entity.")"; Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj->nb <= 0) - { - $result = $this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key - if ($result < 0) - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - $error++; - } - } - } + $sql = "SELECT COUNT(rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; + $sql .= " WHERE elementtype = '".$elementtype."'"; + $sql .= " AND name = '".$attrname."'"; + //$sql.= " AND entity IN (0,".$conf->entity.")"; Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj->nb <= 0) + { + $result = $this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key + if ($result < 0) + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + $error++; + } + } + } } return $result; @@ -520,7 +520,7 @@ class ExtraFields } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete description of an optional attribute * @@ -530,7 +530,7 @@ class ExtraFields */ private function delete_label($attrname, $elementtype = 'member') { - // phpcs:enable + // phpcs:enable global $conf; if ($elementtype == 'thirdparty') $elementtype = 'societe'; @@ -578,17 +578,17 @@ class ExtraFields * @param string $entity Entity of extrafields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not - * @param int $totalizable Is extrafield totalizable on list - * @param int $printable Is extrafield displayed on PDF + * @param int $totalizable Is extrafield totalizable on list + * @param int $printable Is extrafield displayed on PDF * @return int >0 if OK, <=0 if KO - * @throws Exception + * @throws Exception */ public function update($attrname, $label, $type, $length, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { if ($elementtype == 'thirdparty') $elementtype = 'societe'; if ($elementtype == 'contact') $elementtype = 'socpeople'; - $table = $elementtype.'_extrafields'; + $table = $elementtype.'_extrafields'; if ($elementtype == 'categorie') $table = 'categories_extrafields'; if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) @@ -660,7 +660,7 @@ class ExtraFields } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Modify description of personalized attribute * @@ -682,14 +682,14 @@ class ExtraFields * @param string $entity Entity of extrafields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not - * @param int $totalizable Is extrafield totalizable on list - * @param int $printable Is extrafield displayed on PDF - * @return int <=0 if KO, >0 if OK - * @throws Exception + * @param int $totalizable Is extrafield totalizable on list + * @param int $printable Is extrafield displayed on PDF + * @return int <=0 if KO, >0 if OK + * @throws Exception */ private function update_label($attrname, $label, $type, $size, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '0', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { - // phpcs:enable + // phpcs:enable global $conf, $user; dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable.", ".$printable); @@ -699,9 +699,9 @@ class ExtraFields if (empty($pos)) $pos = 0; if (empty($list)) $list = '0'; - if (empty($totalizable)) { - $totalizable = 0; - } + if (empty($totalizable)) { + $totalizable = 0; + } if (empty($required)) $required = 0; if (empty($unique)) $unique = 0; if (empty($alwayseditable)) $alwayseditable = 0; @@ -752,7 +752,7 @@ class ExtraFields $sql .= " param,"; $sql .= " list,"; $sql .= " printable,"; - $sql .= " totalizable,"; + $sql .= " totalizable,"; $sql .= " fielddefault,"; $sql .= " fieldcomputed,"; $sql .= " fk_user_author,"; @@ -776,7 +776,7 @@ class ExtraFields $sql .= " '".$this->db->escape($params)."',"; $sql .= " '".$this->db->escape($list)."', "; $sql .= " '".$this->db->escape($printable)."', "; - $sql .= " ".($totalizable ? 'TRUE' : 'FALSE').","; + $sql .= " ".($totalizable ? 'TRUE' : 'FALSE').","; $sql .= " ".(($default != '') ? "'".$this->db->escape($default)."'" : "null").","; $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").","; $sql .= " ".$user->id.","; @@ -803,7 +803,7 @@ class ExtraFields } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load array this->attributes, or old this->attribute_xxx like attribute_label, attribute_type, ... * @@ -813,7 +813,7 @@ class ExtraFields */ public function fetch_name_optionals_label($elementtype, $forceload = false) { - // phpcs:enable + // phpcs:enable global $conf; if (empty($elementtype)) return array(); @@ -839,15 +839,15 @@ class ExtraFields { while ($tab = $this->db->fetch_object($resql)) { - if ($tab->entity != 0 && $tab->entity != $conf->entity) - { - // This field is not in current entity. We discard but before we save it into the array of mandatory fields if it is a mandatory field without default value - if ($tab->fieldrequired && is_null($tab->fielddefault)) - { - $this->attributes[$tab->elementtype]['mandatoryfieldsofotherentities'][$tab->name] = $tab->type; - } - continue; - } + if ($tab->entity != 0 && $tab->entity != $conf->entity) + { + // This field is not in current entity. We discard but before we save it into the array of mandatory fields if it is a mandatory field without default value + if ($tab->fieldrequired && is_null($tab->fielddefault)) + { + $this->attributes[$tab->elementtype]['mandatoryfieldsofotherentities'][$tab->name] = $tab->type; + } + continue; + } // We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label'] if ($tab->type != 'separate') @@ -889,7 +889,7 @@ class ExtraFields $this->attributes[$tab->elementtype]['langfile'][$tab->name] = $tab->langs; $this->attributes[$tab->elementtype]['list'][$tab->name] = $tab->list; $this->attributes[$tab->elementtype]['printable'][$tab->name] = $tab->printable; - $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = ($tab->totalizable ? 1 : 0); + $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = ($tab->totalizable ? 1 : 0); $this->attributes[$tab->elementtype]['entityid'][$tab->name] = $tab->entity; $this->attributes[$tab->elementtype]['enabled'][$tab->name] = $tab->enabled; $this->attributes[$tab->elementtype]['help'][$tab->name] = $tab->help; @@ -1125,8 +1125,8 @@ class ExtraFields // 2 : key fields name (if differ of rowid) // 3 : key field parent (for dependent lists) // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value - // 5 : id category type - // 6 : ids categories list separated by comma for category root + // 5 : id category type + // 6 : ids categories list separated by comma for category root $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); @@ -1145,122 +1145,122 @@ class ExtraFields $keyList .= ', '.$parentField; } - $filter_categorie = false; - if (count($InfoFieldList) > 5) { - if ($InfoFieldList[0] == 'categorie') { - $filter_categorie = true; - } - } + $filter_categorie = false; + if (count($InfoFieldList) > 5) { + if ($InfoFieldList[0] == 'categorie') { + $filter_categorie = true; + } + } - if ($filter_categorie === false) { - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) { - $keyList .= ', '; - $keyList .= implode(', ', $fields_label); - } + if ($filter_categorie === false) { + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $keyList .= ', '; + $keyList .= implode(', ', $fields_label); + } - $sqlwhere = ''; - $sql = 'SELECT '.$keyList; - $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; - if (!empty($InfoFieldList[4])) { - // can use curent entity filter - if (strpos($InfoFieldList[4], '$ENTITY$') !== false) { - $InfoFieldList[4] = str_replace('$ENTITY$', $conf->entity, $InfoFieldList[4]); - } - // can use SELECT request - if (strpos($InfoFieldList[4], '$SEL$') !== false) { - $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); - } + $sqlwhere = ''; + $sql = 'SELECT '.$keyList; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; + if (!empty($InfoFieldList[4])) { + // can use curent entity filter + if (strpos($InfoFieldList[4], '$ENTITY$') !== false) { + $InfoFieldList[4] = str_replace('$ENTITY$', $conf->entity, $InfoFieldList[4]); + } + // can use SELECT request + if (strpos($InfoFieldList[4], '$SEL$') !== false) { + $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); + } - // current object id can be use into filter - if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) { - $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]); - } else { - $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); - } - //We have to join on extrafield table - if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; - $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; - } else { - $sqlwhere .= ' WHERE '.$InfoFieldList[4]; - } - } else { - $sqlwhere .= ' WHERE 1=1'; - } - // Some tables may have field, some other not. For the moment we disable it. - if (in_array($InfoFieldList[0], array('tablewithentity'))) { - $sqlwhere .= ' AND entity = '.$conf->entity; - } - $sql .= $sqlwhere; - //print $sql; + // current object id can be use into filter + if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) { + $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]); + } else { + $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); + } + //We have to join on extrafield table + if (strpos($InfoFieldList[4], 'extra') !== false) { + $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; + } else { + $sqlwhere .= ' WHERE '.$InfoFieldList[4]; + } + } else { + $sqlwhere .= ' WHERE 1=1'; + } + // Some tables may have field, some other not. For the moment we disable it. + if (in_array($InfoFieldList[0], array('tablewithentity'))) { + $sqlwhere .= ' AND entity = '.$conf->entity; + } + $sql .= $sqlwhere; + //print $sql; - $sql .= ' ORDER BY '.implode(', ', $fields_label); + $sql .= ' ORDER BY '.implode(', ', $fields_label); - dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $out .= ''; - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) { - $labeltoshow = ''; - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $out .= ''; + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $labeltoshow = ''; + $obj = $this->db->fetch_object($resql); - // Several field into label (eq table:code|libelle:rowid) - $notrans = false; - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label) && count($fields_label) > 1) { - $notrans = true; - foreach ($fields_label as $field_toshow) { - $labeltoshow .= $obj->$field_toshow.' '; - } - } else { - $labeltoshow = $obj->{$InfoFieldList[1]}; - } - $labeltoshow = dol_trunc($labeltoshow, 45); + // Several field into label (eq table:code|libelle:rowid) + $notrans = false; + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label) && count($fields_label) > 1) { + $notrans = true; + foreach ($fields_label as $field_toshow) { + $labeltoshow .= $obj->$field_toshow.' '; + } + } else { + $labeltoshow = $obj->{$InfoFieldList[1]}; + } + $labeltoshow = dol_trunc($labeltoshow, 45); - if ($value == $obj->rowid) { - if (!$notrans) { - foreach ($fields_label as $field_toshow) { - $translabel = $langs->trans($obj->$field_toshow); - $labeltoshow = dol_trunc($translabel, 18).' '; - } - } - $out .= ''; - } else { - if (!$notrans) { - $translabel = $langs->trans($obj->{$InfoFieldList[1]}); - $labeltoshow =$translabel; - } - if (empty($labeltoshow)) $labeltoshow = '(not defined)'; + if ($value == $obj->rowid) { + if (!$notrans) { + foreach ($fields_label as $field_toshow) { + $translabel = $langs->trans($obj->$field_toshow); + $labeltoshow = dol_trunc($translabel, 18).' '; + } + } + $out .= ''; + } else { + if (!$notrans) { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + $labeltoshow =$translabel; + } + if (empty($labeltoshow)) $labeltoshow = '(not defined)'; - if (!empty($InfoFieldList[3]) && $parentField) { - $parent = $parentName.':'.$obj->{$parentField}; - } + if (!empty($InfoFieldList[3]) && $parentField) { + $parent = $parentName.':'.$obj->{$parentField}; + } - $out .= ''; - } + $out .= ''; + } - $i++; - } - $this->db->free($resql); - } else { - print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; - } - } else { + $i++; + } + $this->db->free($resql); + } else { + print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; + } + } else { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1); - $out .= ''; - foreach ($data as $data_key => $data_value) { - $out .= ''; + foreach ($data as $data_key => $data_value) { + $out .= '
'; - } - if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') { - if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) { - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).''; - } - $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; - } + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && !empty($usercancreate) && $action == 'edit_thirdparty') { + $morehtmlref .= ' : '; + $morehtmlref .= '
'; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $form->select_company($object->thirdparty->id, 'new_socid', 's.fournisseur=1', '', 0, 0, array(), 0, 'minwidth300'); + $morehtmlref .= ''; + $morehtmlref .= '
'; + } + if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') { + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).''; + } + $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; + } // Project - if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($usercancreate) { - if ($action != 'classify') - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
'; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1, 0, 'maxwidth500'); - $morehtmlref .= ''; - $morehtmlref .= '
'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } - } + if (!empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '
'.$langs->trans('Project').' '; + if ($usercancreate) { + if ($action != 'classify') + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
'; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1, 0, 'maxwidth500'); + $morehtmlref .= ''; + $morehtmlref .= '
'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } + } $morehtmlref .= ''; diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index 3fb825c06b9..617de720ae5 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -111,152 +111,152 @@ if (empty($reshook)) header("Location: ".$backtopage); exit; } - $action = ''; + $action = ''; } // If create a request if ($action == 'create') { - // If no right to create a request - if (!$cancreate) - { - $error++; - setEventMessages($langs->trans('CantCreateCP'), null, 'errors'); - $action = 'request'; - } + // If no right to create a request + if (!$cancreate) + { + $error++; + setEventMessages($langs->trans('CantCreateCP'), null, 'errors'); + $action = 'request'; + } - if (!$error) - { - $object = new Holiday($db); + if (!$error) + { + $object = new Holiday($db); - $db->begin(); + $db->begin(); - $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year')); - $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year')); - $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1); - $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); - $starthalfday = GETPOST('starthalfday'); - $endhalfday = GETPOST('endhalfday'); - $type = GETPOST('type'); - $halfday = 0; - if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday = 2; - elseif ($starthalfday == 'afternoon') $halfday = -1; - elseif ($endhalfday == 'morning') $halfday = 1; + $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year')); + $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year')); + $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1); + $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); + $starthalfday = GETPOST('starthalfday'); + $endhalfday = GETPOST('endhalfday'); + $type = GETPOST('type'); + $halfday = 0; + if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday = 2; + elseif ($starthalfday == 'afternoon') $halfday = -1; + elseif ($endhalfday == 'morning') $halfday = 1; - $valideur = GETPOST('valideur', 'int'); - $description = trim(GETPOST('description', 'none')); + $valideur = GETPOST('valideur', 'int'); + $description = trim(GETPOST('description', 'none')); - // If no type - if ($type <= 0) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error++; - $action = 'create'; - } + // If no type + if ($type <= 0) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error++; + $action = 'create'; + } - // If no start date - if (empty($date_debut)) - { - setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); - $error++; - $action = 'create'; - } - // If no end date - if (empty($date_fin)) - { - setEventMessages($langs->trans("NoDateFin"), null, 'errors'); - $error++; - $action = 'create'; - } - // If start date after end date - if ($date_debut > $date_fin) - { - setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); - $error++; - $action = 'create'; - } + // If no start date + if (empty($date_debut)) + { + setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); + $error++; + $action = 'create'; + } + // If no end date + if (empty($date_fin)) + { + setEventMessages($langs->trans("NoDateFin"), null, 'errors'); + $error++; + $action = 'create'; + } + // If start date after end date + if ($date_debut > $date_fin) + { + setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); + $error++; + $action = 'create'; + } - // Check if there is already holiday for this period - $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday); - if (!$verifCP) - { - setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); - $error++; - $action = 'create'; - } + // Check if there is already holiday for this period + $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday); + if (!$verifCP) + { + setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); + $error++; + $action = 'create'; + } - // If there is no Business Days within request - $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); - if ($nbopenedday < 0.5) - { - setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); - $error++; - $action = 'create'; - } + // If there is no Business Days within request + $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); + if ($nbopenedday < 0.5) + { + setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); + $error++; + $action = 'create'; + } - // If no validator designated - if ($valideur < 1) - { - setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors'); - $error++; - } + // If no validator designated + if ($valideur < 1) + { + setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors'); + $error++; + } - $result = 0; + $result = 0; - if (!$error) - { - $object->fk_user = $fuserid; - $object->description = $description; - $object->fk_validator = $valideur; - $object->fk_type = $type; - $object->date_debut = $date_debut; - $object->date_fin = $date_fin; - $object->halfday = $halfday; + if (!$error) + { + $object->fk_user = $fuserid; + $object->description = $description; + $object->fk_validator = $valideur; + $object->fk_type = $type; + $object->date_debut = $date_debut; + $object->date_fin = $date_fin; + $object->halfday = $halfday; - $result = $object->create($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } + $result = $object->create($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } - // If no SQL error we redirect to the request card - if (!$error) - { + // If no SQL error we redirect to the request card + if (!$error) + { $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - $db->rollback(); - } - } + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } else { + $db->rollback(); + } + } } if ($action == 'update' && GETPOSTISSET('savevalidator') && !empty($user->rights->holiday->approve)) { - $object->fetch($id); + $object->fetch($id); - $object->oldcopy = dol_clone($object); + $object->oldcopy = dol_clone($object); - $object->fk_validator = GETPOST('valideur', 'int'); + $object->fk_validator = GETPOST('valideur', 'int'); - if ($object->fk_validator != $object->oldcopy->fk_validator) - { - $verif = $object->update($user); + if ($object->fk_validator != $object->oldcopy->fk_validator) + { + $verif = $object->update($user); - if ($verif <= 0) - { - setEventMessages($object->error, $object->errors, 'warnings'); - $action = 'editvalidator'; - } else { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } + if ($verif <= 0) + { + setEventMessages($object->error, $object->errors, 'warnings'); + $action = 'editvalidator'; + } else { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } - $action = ''; + $action = ''; } if ($action == 'update' && !GETPOSTISSET('savevalidator')) diff --git a/htdocs/index.php b/htdocs/index.php index 307b356d522..65787fda020 100644 --- a/htdocs/index.php +++ b/htdocs/index.php @@ -450,14 +450,14 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->approve) { include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $board = new ExpenseReport($db); - $dashboardlines[$board->element . '_toapprove'] = $board->load_board($user, 'toapprove'); + $dashboardlines[$board->element.'_toapprove'] = $board->load_board($user, 'toapprove'); } // Number of expense reports to pay if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->to_paid) { include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $board = new ExpenseReport($db); - $dashboardlines[$board->element . '_topay'] = $board->load_board($user, 'topay'); + $dashboardlines[$board->element.'_topay'] = $board->load_board($user, 'topay'); } // Number of holidays to approve diff --git a/htdocs/loan/class/paymentloan.class.php b/htdocs/loan/class/paymentloan.class.php index 2d9501ea549..9c5c1b559ad 100644 --- a/htdocs/loan/class/paymentloan.class.php +++ b/htdocs/loan/class/paymentloan.class.php @@ -41,63 +41,63 @@ class PaymentLoan extends CommonObject */ public $table_element = 'payment_loan'; - /** - * @var string String with name of icon for PaymentLoan - */ - public $picto = 'money-bill-alt'; + /** + * @var string String with name of icon for PaymentLoan + */ + public $picto = 'money-bill-alt'; - /** - * @var int Loan ID - */ - public $fk_loan; + /** + * @var int Loan ID + */ + public $fk_loan; - /** - * @var string Create date - */ - public $datec = ''; + /** + * @var string Create date + */ + public $datec = ''; - public $tms = ''; + public $tms = ''; - /** - * @var string Payment date - */ - public $datep = ''; + /** + * @var string Payment date + */ + public $datep = ''; - public $amounts = array(); // Array of amounts + public $amounts = array(); // Array of amounts - public $amount_capital; // Total amount of payment + public $amount_capital; // Total amount of payment - public $amount_insurance; + public $amount_insurance; - public $amount_interest; + public $amount_interest; - /** - * @var int Payment mode ID - */ - public $fk_typepayment; + /** + * @var int Payment mode ID + */ + public $fk_typepayment; - /** - * @var int Payment ID - */ - public $num_payment; + /** + * @var int Payment ID + */ + public $num_payment; - /** - * @var int Bank ID - */ - public $fk_bank; + /** + * @var int Bank ID + */ + public $fk_bank; - /** - * @var int User ID - */ - public $fk_user_creat; + /** + * @var int User ID + */ + public $fk_user_creat; - /** - * @var int user ID - */ - public $fk_user_modif; + /** + * @var int user ID + */ + public $fk_user_modif; - public $type_code; - public $type_label; + public $type_code; + public $type_label; /** @@ -367,23 +367,23 @@ class PaymentLoan extends CommonObject if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } } - // Set loan unpaid if loan has no other payment - if (!$error) - { - require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; - $loan = new Loan($this->db); - $loan->fetch($this->fk_loan); - $sum_payment = $loan->getSumPayment(); - if ($sum_payment == 0) - { - dol_syslog(get_class($this)."::delete : set loan to unpaid", LOG_DEBUG); - if ($loan->set_unpaid($user) < 1) - { - $error++; - dol_print_error($this->db); - } - } - } + // Set loan unpaid if loan has no other payment + if (!$error) + { + require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; + $loan = new Loan($this->db); + $loan->fetch($this->fk_loan); + $sum_payment = $loan->getSumPayment(); + if ($sum_payment == 0) + { + dol_syslog(get_class($this)."::delete : set loan to unpaid", LOG_DEBUG); + if ($loan->set_unpaid($user) < 1) + { + $error++; + dol_print_error($this->db); + } + } + } //if (! $error) //{ @@ -435,7 +435,7 @@ class PaymentLoan extends CommonObject global $conf; $error = 0; - $this->db->begin(); + $this->db->begin(); if (!empty($conf->banque->enabled)) { @@ -448,9 +448,9 @@ class PaymentLoan extends CommonObject if ($mode == 'payment_loan') $total = -$total; // Insert payment into llx_bank - $bank_line_id = $acc->addline( + $bank_line_id = $acc->addline( $this->datep, - $this->fk_typepayment, // Payment mode ID or code ("CHQ or VIR for example") + $this->fk_typepayment, // Payment mode ID or code ("CHQ or VIR for example") $label, $total, $this->num_payment, @@ -498,36 +498,36 @@ class PaymentLoan extends CommonObject } - // Set loan payment started if no set - if (!$error) - { - require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; - $loan = new Loan($this->db); - $loan->fetch($fk_loan); - if ($loan->paid == $loan::STATUS_UNPAID) - { - dol_syslog(get_class($this)."::addPaymentToBank : set loan payment to started", LOG_DEBUG); - if ($loan->set_started($user) < 1) - { - $error++; - dol_print_error($this->db); - } - } - } + // Set loan payment started if no set + if (!$error) + { + require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; + $loan = new Loan($this->db); + $loan->fetch($fk_loan); + if ($loan->paid == $loan::STATUS_UNPAID) + { + dol_syslog(get_class($this)."::addPaymentToBank : set loan payment to started", LOG_DEBUG); + if ($loan->set_started($user) < 1) + { + $error++; + dol_print_error($this->db); + } + } + } if (!$error) { - $this->db->commit(); + $this->db->commit(); return 1; } else { - $this->db->rollback(); + $this->db->rollback(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update link between loan's payment and the line generate in llx_bank * @@ -536,14 +536,14 @@ class PaymentLoan extends CommonObject */ public function update_fk_bank($id_bank) { - // phpcs:enable + // phpcs:enable $sql = "UPDATE ".MAIN_DB_PREFIX."payment_loan SET fk_bank = ".$id_bank." WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { - $this->fk_bank = $id_bank; + $this->fk_bank = $id_bank; return 1; } else { $this->error = $this->db->error(); @@ -556,9 +556,9 @@ class PaymentLoan extends CommonObject * * @param int $withpicto 0=No picto, 1=Include picto into link, 2=No picto * @param int $maxlen Max length label - * @param int $notooltip 1=Disable tooltip - * @param string $moretitle Add more text to title 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 string $moretitle Add more text to title 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, $maxlen = 0, $notooltip = 0, $moretitle = '', $save_lastsearch_value = -1) diff --git a/htdocs/opensurvey/card.php b/htdocs/opensurvey/card.php index 2f9b8babfed..2d714deeb2c 100644 --- a/htdocs/opensurvey/card.php +++ b/htdocs/opensurvey/card.php @@ -49,8 +49,8 @@ $object = new Opensurveysondage($db); $result = $object->fetch(0, $numsondage); if ($result <= 0) { - dol_print_error($db, $object->error); - exit; + dol_print_error($db, $object->error); + exit; } $expiredate = dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'), GETPOST('expireyear')); @@ -67,112 +67,112 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($cancel) $action = ''; + if ($cancel) $action = ''; - // Delete - if ($action == 'delete_confirm') - { - // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + // Delete + if ($action == 'delete_confirm') + { + // Security check + if (!$user->rights->opensurvey->write) accessforbidden(); - $result = $object->delete($user, '', $numsondage); + $result = $object->delete($user, '', $numsondage); - header('Location: '.dol_buildpath('/opensurvey/list.php', 1)); - exit(); - } + header('Location: '.dol_buildpath('/opensurvey/list.php', 1)); + exit(); + } - // Close - if ($action == 'close') - { - $object->status = Opensurveysondage::STATUS_CLOSED; - $object->update($user); - } + // Close + if ($action == 'close') + { + $object->status = Opensurveysondage::STATUS_CLOSED; + $object->update($user); + } - // Reopend - if ($action == 'reopen') - { - $object->status = Opensurveysondage::STATUS_VALIDATED; - $object->update($user); - } + // Reopend + if ($action == 'reopen') + { + $object->status = Opensurveysondage::STATUS_VALIDATED; + $object->update($user); + } - // Update - if ($action == 'update') - { - // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + // Update + if ($action == 'update') + { + // Security check + if (!$user->rights->opensurvey->write) accessforbidden(); - $error = 0; + $error = 0; - if (!GETPOST('nouveautitre')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); - $error++; - $action = 'edit'; - } + if (!GETPOST('nouveautitre')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); + $error++; + $action = 'edit'; + } - if (!$error) - { - $object->title = GETPOST('nouveautitre', 'nohtml'); - $object->description = GETPOST('nouveauxcommentaires', 'restricthtml'); - $object->mail_admin = GETPOST('nouvelleadresse', 'alpha'); - $object->date_fin = $expiredate; - $object->allow_comments = GETPOST('cancomment', 'alpha') == 'on' ? 1 : 0; - $object->allow_spy = GETPOST('canseeothersvote', 'alpha') == 'on' ? 1 : 0; - $object->mailsonde = GETPOST('mailsonde', 'alpha') == 'on' ? true : false; + if (!$error) + { + $object->title = GETPOST('nouveautitre', 'nohtml'); + $object->description = GETPOST('nouveauxcommentaires', 'restricthtml'); + $object->mail_admin = GETPOST('nouvelleadresse', 'alpha'); + $object->date_fin = $expiredate; + $object->allow_comments = GETPOST('cancomment', 'alpha') == 'on' ? 1 : 0; + $object->allow_spy = GETPOST('canseeothersvote', 'alpha') == 'on' ? 1 : 0; + $object->mailsonde = GETPOST('mailsonde', 'alpha') == 'on' ? true : false; - $res = $object->update($user); - if ($res < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'edit'; - } - } - } + $res = $object->update($user); + if ($res < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'edit'; + } + } + } - // Add comment - if (GETPOST('ajoutcomment')) - { - $error = 0; + // Add comment + if (GETPOST('ajoutcomment')) + { + $error = 0; - if (!GETPOST('comment')) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); - } - if (!GETPOST('commentuser')) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("User")), null, 'errors'); - } + if (!GETPOST('comment')) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); + } + if (!GETPOST('commentuser')) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("User")), null, 'errors'); + } - if (!$error) - { - $comment = GETPOST("comment"); - $comment_user = GETPOST('commentuser'); + if (!$error) + { + $comment = GETPOST("comment"); + $comment_user = GETPOST('commentuser'); - $resql = $object->addComment($comment, $comment_user); + $resql = $object->addComment($comment, $comment_user); - if (!$resql) - { - setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors'); - } - } - } + if (!$resql) + { + setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors'); + } + } + } - // Delete comment - $idcomment = GETPOST('deletecomment', 'int'); - if ($idcomment) - { - // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + // Delete comment + $idcomment = GETPOST('deletecomment', 'int'); + if ($idcomment) + { + // Security check + if (!$user->rights->opensurvey->write) accessforbidden(); - $resql = $object->deleteComment($idcomment); - } + $resql = $object->deleteComment($idcomment); + } - if ($action == 'edit') { - // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); - } + if ($action == 'edit') { + // Security check + if (!$user->rights->opensurvey->write) accessforbidden(); + } } @@ -302,8 +302,8 @@ print ''; print ''.$langs->trans('ExpireDate').''; if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); else { - print dol_print_date($object->date_fin, 'day'); - if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); + print dol_print_date($object->date_fin, 'day'); + if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); } print ''; @@ -356,19 +356,19 @@ print ''."\n"; print '
'; if ($action != 'edit' && $user->rights->opensurvey->write) { - //Modify button - print ''.$langs->trans("Modify").''; + //Modify button + print ''.$langs->trans("Modify").''; - if ($object->status == Opensurveysondage::STATUS_VALIDATED) - { - //Close button - print ''.$langs->trans("Close").''; - } - if ($object->status == Opensurveysondage::STATUS_CLOSED) - { - //Opened button - print ''.$langs->trans("ReOpen").''; - } + if ($object->status == Opensurveysondage::STATUS_VALIDATED) + { + //Close button + print ''.$langs->trans("Close").''; + } + if ($object->status == Opensurveysondage::STATUS_CLOSED) + { + //Opened button + print ''.$langs->trans("ReOpen").''; + } //Delete button print ''.$langs->trans('Delete').''; diff --git a/htdocs/opensurvey/class/opensurveysondage.class.php b/htdocs/opensurvey/class/opensurveysondage.class.php index 0c2b00735ff..71288266b45 100644 --- a/htdocs/opensurvey/class/opensurveysondage.class.php +++ b/htdocs/opensurvey/class/opensurveysondage.class.php @@ -34,616 +34,616 @@ require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php"; */ class Opensurveysondage extends CommonObject { - /** - * @var string ID to identify managed object - */ - public $element = 'opensurvey_sondage'; - - /** - * @var string Name of table without prefix where object is stored - */ - public $table_element = 'opensurvey_sondage'; - - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'poll'; - - - /** - * @var string ID survey - */ - public $id_sondage; - - /** - * @var string description - */ - public $description; - - public $mail_admin; - public $nom_admin; - - /** - * Id of user author of the poll - * @var int - */ - public $fk_user_creat; - - /** - * @var string Title - */ - public $title; - - public $date_fin = ''; - public $status = 1; - public $format; - public $mailsonde; - - public $sujet; - - /** - * @var int Allow comments on this poll - */ - public $allow_comments; - - /** - * @var int Allow users see others vote - */ - public $allow_spy; - - - /** - * Draft status (not used) - */ - const STATUS_DRAFT = 0; - /** - * Validated/Opened status - */ - const STATUS_VALIDATED = 1; - /** - * Closed - */ - const STATUS_CLOSED = 2; - - - - /** - * 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 $user, $notrigger = 0) - { - $error = 0; - - // Clean parameters - $this->cleanParameters(); - - // Check parameters - if (!$this->date_fin > 0) - { - $this->error = 'BadValueForEndDate'; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_sondage("; - $sql .= "id_sondage,"; - $sql .= "commentaires,"; - $sql .= "fk_user_creat,"; - $sql .= "titre,"; - $sql .= "date_fin,"; - $sql .= "status,"; - $sql .= "format,"; - $sql .= "mailsonde,"; - $sql .= "allow_comments,"; - $sql .= "allow_spy,"; - $sql .= "sujet"; - $sql .= ") VALUES ("; - $sql .= "'".$this->db->escape($this->id_sondage)."',"; - $sql .= " ".(empty($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").","; - $sql .= " ".$user->id.","; - $sql .= " '".$this->db->escape($this->title)."',"; - $sql .= " '".$this->db->idate($this->date_fin)."',"; - $sql .= " ".$this->status.","; - $sql .= " '".$this->db->escape($this->format)."',"; - $sql .= " ".$this->db->escape($this->mailsonde).","; - $sql .= " ".$this->db->escape($this->allow_comments).","; - $sql .= " ".$this->db->escape($this->allow_spy).","; - $sql .= " '".$this->db->escape($this->sujet)."'"; - $sql .= ")"; - - $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(); } - - if (!$error) - { - if (!$notrigger) - { - global $langs, $conf; - - // Call trigger - $result = $this->call_trigger('OPENSURVEY_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; - } - } - - - /** - * Load object in memory from the database - * - * @param int $id Id object - * @param string $numsurvey Ref of survey (admin or not) - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $numsurvey = '') - { - $sql = "SELECT"; - $sql .= " t.id_sondage,"; - $sql .= " t.titre as title,"; - $sql .= " t.commentaires as description,"; - $sql .= " t.mail_admin,"; - $sql .= " t.nom_admin,"; - $sql .= " t.fk_user_creat,"; - $sql .= " t.date_fin,"; - $sql .= " t.status,"; - $sql .= " t.format,"; - $sql .= " t.mailsonde,"; - $sql .= " t.allow_comments,"; - $sql .= " t.allow_spy,"; - $sql .= " t.sujet,"; - $sql .= " t.tms"; - $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as t"; - $sql .= " WHERE t.id_sondage = '".$this->db->escape($id ? $id : $numsurvey)."'"; - - 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_sondage = $obj->id_sondage; - $this->ref = $this->id_sondage; //For compatibility - - $this->description = $obj->description; - $this->mail_admin = $obj->mail_admin; - $this->nom_admin = $obj->nom_admin; - $this->title = $obj->title; - $this->date_fin = $this->db->jdate($obj->date_fin); - $this->status = $obj->status; - $this->format = $obj->format; - $this->mailsonde = $obj->mailsonde; - $this->allow_comments = $obj->allow_comments; - $this->allow_spy = $obj->allow_spy; - $this->sujet = $obj->sujet; - $this->fk_user_creat = $obj->fk_user_creat; - - $this->date_m = $this->db->jdate($obj->tls); - $ret = 1; - } else { - $sondage = ($id ? 'id='.$id : 'sondageid='.$numsurvey); - $this->error = 'Fetch no poll found for '.$sondage; - dol_syslog($this->error, LOG_ERR); - $ret = 0; - } - - $this->db->free($resql); - } else { - $this->error = "Error ".$this->db->lasterror(); - $ret = -1; - } - - return $ret; - } - - - /** - * 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 $user, $notrigger = 0) - { - global $conf, $langs; - $error = 0; - - // Clean parameters - $this->cleanParameters(); - - // Check parameters - // Put here code to add a control on parameters values - - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."opensurvey_sondage SET"; - $sql .= " id_sondage=".(isset($this->id_sondage) ? "'".$this->db->escape($this->id_sondage)."'" : "null").","; - $sql .= " commentaires=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").","; - $sql .= " mail_admin=".(isset($this->mail_admin) ? "'".$this->db->escape($this->mail_admin)."'" : "null").","; - $sql .= " nom_admin=".(isset($this->nom_admin) ? "'".$this->db->escape($this->nom_admin)."'" : "null").","; - $sql .= " titre=".(isset($this->title) ? "'".$this->db->escape($this->title)."'" : "null").","; - $sql .= " date_fin=".(dol_strlen($this->date_fin) != 0 ? "'".$this->db->idate($this->date_fin)."'" : 'null').","; - $sql .= " status=".(isset($this->status) ? "'".$this->db->escape($this->status)."'" : "null").","; - $sql .= " format=".(isset($this->format) ? "'".$this->db->escape($this->format)."'" : "null").","; - $sql .= " mailsonde=".(isset($this->mailsonde) ? $this->db->escape($this->mailsonde) : "null").","; - $sql .= " allow_comments=".$this->db->escape($this->allow_comments).","; - $sql .= " allow_spy=".$this->db->escape($this->allow_spy); - $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'"; - - $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(); } - - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('OPENSURVEY_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; - } - } - - /** - * Delete object in database - * - * @param User $user User that deletes - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @param string $numsondage Num sondage admin to delete - * @return int <0 if KO, >0 if OK - */ - public function delete(User $user, $notrigger = 0, $numsondage = '') - { - global $conf, $langs; - $error = 0; - - if (empty($numsondage)) - { - $numsondage = $this->id_sondage; - } - - $this->db->begin(); - - if (!$error) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('OPENSURVEY_DELETE', $user); - if ($result < 0) $error++; - // End call triggers - } - } - - if (!$error) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'"; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_user_studs WHERE id_sondage = '".$this->db->escape($numsondage)."'"; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."opensurvey_sondage"; - $sql .= " WHERE id_sondage = '".$this->db->escape($numsondage)."'"; - - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - } - - // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else { - $this->db->commit(); - return 1; - } - } - - /** - * 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 $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, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) - { - global $db, $conf, $langs; - global $dolibarr_main_authentication, $dolibarr_main_demo; - global $menumanager; - - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - - $result = ''; - $companylink = ''; - - $label = ''.$langs->trans("ShowSurvey").''; - $label .= '
'; - $label .= ''.$langs->trans('Ref').': '.$this->ref.'
'; - $label .= ''.$langs->trans('Title').': '.$this->title.'
'; - - $url = DOL_URL_ROOT.'/opensurvey/card.php?id='.$this->id; - - // 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.'"' : ''); - - $linkstart = ''; - $linkend = ''; - - $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($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; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return array of lines - * - * @return int <0 if KO, >0 if OK - */ - public function fetch_lines() - { - // phpcs:enable - $ret = array(); - - $sql = "SELECT id_users, nom as name, reponses FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; - $sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'"; - $resql = $this->db->query($sql); - - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses); - - $ret[] = $tmp; - $i++; - } - } else dol_print_error($this->db); - - $this->lines = $ret; - - return count($this->lines); - } - - /** - * Initialise object with example values - * Id must be 0 if object instance is a specimen - * - * @return void - */ - public function initAsSpecimen() - { - $this->id = 0; - - $this->id_sondage = ''; - $this->description = 'Description of the specimen survey'; - $this->mail_admin = ''; - $this->nom_admin = ''; - $this->title = 'This is a specimen survey'; - $this->date_fin = dol_now() + 3600 * 24 * 10; - $this->status = 1; - $this->format = 'classic'; - $this->mailsonde = ''; - } - - /** - * Returns all comments for the current opensurvey poll - * - * @return Object[] - */ - public function getComments() - { - $comments = array(); - - $sql = 'SELECT id_comment, usercomment, comment'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_comments'; - $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'"; - $sql .= " ORDER BY id_comment"; - $resql = $this->db->query($sql); - - if ($resql) - { - $num_rows = $this->db->num_rows($resql); - - if ($num_rows > 0) - { - while ($obj = $this->db->fetch_object($resql)) - { - $comments[] = $obj; - } - } - } - - return $comments; - } - - /** - * Adds a comment to the poll - * - * @param string $comment Comment content - * @param string $comment_user Comment author - * @return boolean False in case of the query fails, true if it was successful - */ - public function addComment($comment, $comment_user) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_comments (id_sondage, comment, usercomment)"; - $sql .= " VALUES ('".$this->db->escape($this->id_sondage)."','".$this->db->escape($comment)."','".$this->db->escape($comment_user)."')"; - $resql = $this->db->query($sql); - - if (!$resql) { - return false; - } - - return true; - } - - /** - * Deletes a comment of the poll - * - * @param int $id_comment Id of the comment - * @return boolean False in case of the query fails, true if it was successful - */ - public function deleteComment($id_comment) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_comments WHERE id_comment = '.$id_comment.' AND id_sondage = "'.$this->db->escape($this->id_sondage).'"'; - $resql = $this->db->query($sql); - - if (!$resql) { - return false; - } - - return true; - } - - /** - * Cleans all the class variables before doing an update or an insert - * - * @return void - */ - private function cleanParameters() - { - $this->id_sondage = trim($this->id_sondage); - $this->description = trim($this->description); - $this->mail_admin = trim($this->mail_admin); - $this->nom_admin = trim($this->nom_admin); - $this->title = trim($this->title); - $this->status = trim($this->status); - $this->format = trim($this->format); - $this->mailsonde = ($this->mailsonde ? 1 : 0); - $this->allow_comments = ($this->allow_comments ? 1 : 0); - $this->allow_spy = ($this->allow_spy ? 1 : 0); - $this->sujet = trim($this->sujet); - } - - - /** - * Return status label of Order - * - * @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) - { - return $this->LibStatut($this->status, $mode); - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return label of status - * - * @param int $status Id 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 Label of status - */ - public function LibStatut($status, $mode) - { - // phpcs:enable - global $langs, $conf; - - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { - global $langs; - //$langs->load("mymodule"); - $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); - $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Opened'); - $this->labelStatus[self::STATUS_CLOSED] = $langs->trans('Closed'); - $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft'); - $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Opened'); - $this->labelStatusShort[self::STATUS_CLOSED] = $langs->trans('Closed'); - } - - $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) { - if (0) $statusType = 'status1'; - else $statusType = 'status4'; - } - if ($status == self::STATUS_CLOSED) $statusType = 'status6'; - - return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); - } + /** + * @var string ID to identify managed object + */ + public $element = 'opensurvey_sondage'; + + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'opensurvey_sondage'; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'poll'; + + + /** + * @var string ID survey + */ + public $id_sondage; + + /** + * @var string description + */ + public $description; + + public $mail_admin; + public $nom_admin; + + /** + * Id of user author of the poll + * @var int + */ + public $fk_user_creat; + + /** + * @var string Title + */ + public $title; + + public $date_fin = ''; + public $status = 1; + public $format; + public $mailsonde; + + public $sujet; + + /** + * @var int Allow comments on this poll + */ + public $allow_comments; + + /** + * @var int Allow users see others vote + */ + public $allow_spy; + + + /** + * Draft status (not used) + */ + const STATUS_DRAFT = 0; + /** + * Validated/Opened status + */ + const STATUS_VALIDATED = 1; + /** + * Closed + */ + const STATUS_CLOSED = 2; + + + + /** + * 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 $user, $notrigger = 0) + { + $error = 0; + + // Clean parameters + $this->cleanParameters(); + + // Check parameters + if (!$this->date_fin > 0) + { + $this->error = 'BadValueForEndDate'; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_sondage("; + $sql .= "id_sondage,"; + $sql .= "commentaires,"; + $sql .= "fk_user_creat,"; + $sql .= "titre,"; + $sql .= "date_fin,"; + $sql .= "status,"; + $sql .= "format,"; + $sql .= "mailsonde,"; + $sql .= "allow_comments,"; + $sql .= "allow_spy,"; + $sql .= "sujet"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->escape($this->id_sondage)."',"; + $sql .= " ".(empty($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").","; + $sql .= " ".$user->id.","; + $sql .= " '".$this->db->escape($this->title)."',"; + $sql .= " '".$this->db->idate($this->date_fin)."',"; + $sql .= " ".$this->status.","; + $sql .= " '".$this->db->escape($this->format)."',"; + $sql .= " ".$this->db->escape($this->mailsonde).","; + $sql .= " ".$this->db->escape($this->allow_comments).","; + $sql .= " ".$this->db->escape($this->allow_spy).","; + $sql .= " '".$this->db->escape($this->sujet)."'"; + $sql .= ")"; + + $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(); } + + if (!$error) + { + if (!$notrigger) + { + global $langs, $conf; + + // Call trigger + $result = $this->call_trigger('OPENSURVEY_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; + } + } + + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $numsurvey Ref of survey (admin or not) + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $numsurvey = '') + { + $sql = "SELECT"; + $sql .= " t.id_sondage,"; + $sql .= " t.titre as title,"; + $sql .= " t.commentaires as description,"; + $sql .= " t.mail_admin,"; + $sql .= " t.nom_admin,"; + $sql .= " t.fk_user_creat,"; + $sql .= " t.date_fin,"; + $sql .= " t.status,"; + $sql .= " t.format,"; + $sql .= " t.mailsonde,"; + $sql .= " t.allow_comments,"; + $sql .= " t.allow_spy,"; + $sql .= " t.sujet,"; + $sql .= " t.tms"; + $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as t"; + $sql .= " WHERE t.id_sondage = '".$this->db->escape($id ? $id : $numsurvey)."'"; + + 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_sondage = $obj->id_sondage; + $this->ref = $this->id_sondage; //For compatibility + + $this->description = $obj->description; + $this->mail_admin = $obj->mail_admin; + $this->nom_admin = $obj->nom_admin; + $this->title = $obj->title; + $this->date_fin = $this->db->jdate($obj->date_fin); + $this->status = $obj->status; + $this->format = $obj->format; + $this->mailsonde = $obj->mailsonde; + $this->allow_comments = $obj->allow_comments; + $this->allow_spy = $obj->allow_spy; + $this->sujet = $obj->sujet; + $this->fk_user_creat = $obj->fk_user_creat; + + $this->date_m = $this->db->jdate($obj->tls); + $ret = 1; + } else { + $sondage = ($id ? 'id='.$id : 'sondageid='.$numsurvey); + $this->error = 'Fetch no poll found for '.$sondage; + dol_syslog($this->error, LOG_ERR); + $ret = 0; + } + + $this->db->free($resql); + } else { + $this->error = "Error ".$this->db->lasterror(); + $ret = -1; + } + + return $ret; + } + + + /** + * 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 $user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + $this->cleanParameters(); + + // Check parameters + // Put here code to add a control on parameters values + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."opensurvey_sondage SET"; + $sql .= " id_sondage=".(isset($this->id_sondage) ? "'".$this->db->escape($this->id_sondage)."'" : "null").","; + $sql .= " commentaires=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").","; + $sql .= " mail_admin=".(isset($this->mail_admin) ? "'".$this->db->escape($this->mail_admin)."'" : "null").","; + $sql .= " nom_admin=".(isset($this->nom_admin) ? "'".$this->db->escape($this->nom_admin)."'" : "null").","; + $sql .= " titre=".(isset($this->title) ? "'".$this->db->escape($this->title)."'" : "null").","; + $sql .= " date_fin=".(dol_strlen($this->date_fin) != 0 ? "'".$this->db->idate($this->date_fin)."'" : 'null').","; + $sql .= " status=".(isset($this->status) ? "'".$this->db->escape($this->status)."'" : "null").","; + $sql .= " format=".(isset($this->format) ? "'".$this->db->escape($this->format)."'" : "null").","; + $sql .= " mailsonde=".(isset($this->mailsonde) ? $this->db->escape($this->mailsonde) : "null").","; + $sql .= " allow_comments=".$this->db->escape($this->allow_comments).","; + $sql .= " allow_spy=".$this->db->escape($this->allow_spy); + $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'"; + + $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(); } + + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('OPENSURVEY_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; + } + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param string $numsondage Num sondage admin to delete + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = 0, $numsondage = '') + { + global $conf, $langs; + $error = 0; + + if (empty($numsondage)) + { + $numsondage = $this->id_sondage; + } + + $this->db->begin(); + + if (!$error) + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('OPENSURVEY_DELETE', $user); + if ($result < 0) $error++; + // End call triggers + } + } + + if (!$error) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'"; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_user_studs WHERE id_sondage = '".$this->db->escape($numsondage)."'"; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."opensurvey_sondage"; + $sql .= " WHERE id_sondage = '".$this->db->escape($numsondage)."'"; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + } + + // Commit or rollback + if ($error) + { + foreach ($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * 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 $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, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $db, $conf, $langs; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + + $result = ''; + $companylink = ''; + + $label = ''.$langs->trans("ShowSurvey").''; + $label .= '
'; + $label .= ''.$langs->trans('Ref').': '.$this->ref.'
'; + $label .= ''.$langs->trans('Title').': '.$this->title.'
'; + + $url = DOL_URL_ROOT.'/opensurvey/card.php?id='.$this->id; + + // 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.'"' : ''); + + $linkstart = ''; + $linkend = ''; + + $result .= $linkstart; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($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; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return array of lines + * + * @return int <0 if KO, >0 if OK + */ + public function fetch_lines() + { + // phpcs:enable + $ret = array(); + + $sql = "SELECT id_users, nom as name, reponses FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; + $sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'"; + $resql = $this->db->query($sql); + + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses); + + $ret[] = $tmp; + $i++; + } + } else dol_print_error($this->db); + + $this->lines = $ret; + + return count($this->lines); + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->id = 0; + + $this->id_sondage = ''; + $this->description = 'Description of the specimen survey'; + $this->mail_admin = ''; + $this->nom_admin = ''; + $this->title = 'This is a specimen survey'; + $this->date_fin = dol_now() + 3600 * 24 * 10; + $this->status = 1; + $this->format = 'classic'; + $this->mailsonde = ''; + } + + /** + * Returns all comments for the current opensurvey poll + * + * @return Object[] + */ + public function getComments() + { + $comments = array(); + + $sql = 'SELECT id_comment, usercomment, comment'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_comments'; + $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'"; + $sql .= " ORDER BY id_comment"; + $resql = $this->db->query($sql); + + if ($resql) + { + $num_rows = $this->db->num_rows($resql); + + if ($num_rows > 0) + { + while ($obj = $this->db->fetch_object($resql)) + { + $comments[] = $obj; + } + } + } + + return $comments; + } + + /** + * Adds a comment to the poll + * + * @param string $comment Comment content + * @param string $comment_user Comment author + * @return boolean False in case of the query fails, true if it was successful + */ + public function addComment($comment, $comment_user) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_comments (id_sondage, comment, usercomment)"; + $sql .= " VALUES ('".$this->db->escape($this->id_sondage)."','".$this->db->escape($comment)."','".$this->db->escape($comment_user)."')"; + $resql = $this->db->query($sql); + + if (!$resql) { + return false; + } + + return true; + } + + /** + * Deletes a comment of the poll + * + * @param int $id_comment Id of the comment + * @return boolean False in case of the query fails, true if it was successful + */ + public function deleteComment($id_comment) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_comments WHERE id_comment = '.$id_comment.' AND id_sondage = "'.$this->db->escape($this->id_sondage).'"'; + $resql = $this->db->query($sql); + + if (!$resql) { + return false; + } + + return true; + } + + /** + * Cleans all the class variables before doing an update or an insert + * + * @return void + */ + private function cleanParameters() + { + $this->id_sondage = trim($this->id_sondage); + $this->description = trim($this->description); + $this->mail_admin = trim($this->mail_admin); + $this->nom_admin = trim($this->nom_admin); + $this->title = trim($this->title); + $this->status = trim($this->status); + $this->format = trim($this->format); + $this->mailsonde = ($this->mailsonde ? 1 : 0); + $this->allow_comments = ($this->allow_comments ? 1 : 0); + $this->allow_spy = ($this->allow_spy ? 1 : 0); + $this->sujet = trim($this->sujet); + } + + + /** + * Return status label of Order + * + * @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) + { + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return label of status + * + * @param int $status Id 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 Label of status + */ + public function LibStatut($status, $mode) + { + // phpcs:enable + global $langs, $conf; + + if (empty($this->labelStatus) || empty($this->labelStatusShort)) + { + global $langs; + //$langs->load("mymodule"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Opened'); + $this->labelStatus[self::STATUS_CLOSED] = $langs->trans('Closed'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Opened'); + $this->labelStatusShort[self::STATUS_CLOSED] = $langs->trans('Closed'); + } + + $statusType = 'status'.$status; + if ($status == self::STATUS_VALIDATED) { + if (0) $statusType = 'status1'; + else $statusType = 'status4'; + } + if ($status == self::STATUS_CLOSED) $statusType = 'status6'; + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } } diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 697c51f09c4..1753cf7e8df 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -2210,7 +2210,7 @@ class Product extends CommonObject } }*/ } else { - $this->error=$this->db->lasterror; + $this->error = $this->db->lasterror; return -1; } } @@ -2255,12 +2255,12 @@ class Product extends CommonObject } $this->prices_by_qty_list[0] = $resultat; } else { - $this->error=$this->db->lasterror; + $this->error = $this->db->lasterror; return -1; } } } else { - $this->error=$this->db->lasterror; + $this->error = $this->db->lasterror; return -1; } } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) // prices per customer and quantity @@ -2314,12 +2314,12 @@ class Product extends CommonObject } $this->prices_by_qty_list[$i] = $resultat; } else { - $this->error=$this->db->lasterror; + $this->error = $this->db->lasterror; return -1; } } } else { - $this->error=$this->db->lasterror; + $this->error = $this->db->lasterror; return -1; } } @@ -2346,7 +2346,7 @@ class Product extends CommonObject return 0; } } else { - $this->error=$this->db->lasterror; + $this->error = $this->db->lasterror; return -1; } } @@ -4769,7 +4769,7 @@ class Product extends CommonObject if ($result < 0) dol_print_error($this->db, $this->error); $stock_sending_client = $this->stats_expedition['qty']; } - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || ! empty($conf->supplier_order->enabled)) + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) { $filterStatus = '1,2,3,4'; if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus; diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index 3949f8af6fe..357251fe512 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -447,11 +447,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Documents if ($includedocgeneration) { $objref = dol_sanitizeFileName($object->ref); - $relativepath = $objref . '/' . $objref . '.pdf'; + $relativepath = $objref.'/'.$objref.'.pdf'; $filedir = $conf->mymodule->dir_output.'/'.$object->element.'/'.$objref; - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->mymodule->myobject->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->mymodule->myobject->write; // If you can create/edit, you can remove a file on card + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->mymodule->myobject->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->mymodule->myobject->write; // If you can create/edit, you can remove a file on card print $formfile->showdocuments('mymodule:MyObject', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang); } diff --git a/htdocs/product/inventory/inventory.php b/htdocs/product/inventory/inventory.php index 001194495bb..790d30b444f 100644 --- a/htdocs/product/inventory/inventory.php +++ b/htdocs/product/inventory/inventory.php @@ -133,7 +133,7 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); } - if (! $error && ! empty($conf->productbatch->enabled)) { + if (!$error && !empty($conf->productbatch->enabled)) { $tmpproduct = new Product($db); $result = $tmpproduct->fetch($fk_product); @@ -320,53 +320,53 @@ if ($object->id > 0) print '
'; print ''; } else { - print '
'."\n"; - $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print '
'."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (empty($reshook)) - { - if ($object->status == Inventory::STATUS_DRAFT) - { - if ($permissiontoadd) - { - print ''.$langs->trans("Validate").' ('.$langs->trans("Start").')'."\n"; - } else { - print ''.$langs->trans('Validate').' ('.$langs->trans("Start").')'."\n"; - } - } + if (empty($reshook)) + { + if ($object->status == Inventory::STATUS_DRAFT) + { + if ($permissiontoadd) + { + print ''.$langs->trans("Validate").' ('.$langs->trans("Start").')'."\n"; + } else { + print ''.$langs->trans('Validate').' ('.$langs->trans("Start").')'."\n"; + } + } - if ($object->status == Inventory::STATUS_VALIDATED) - { - if ($permissiontoadd) - { - /* + if ($object->status == Inventory::STATUS_VALIDATED) + { + if ($permissiontoadd) + { + /* if ($conf->barcode->enabled) { print ''.$langs->trans("UpdateByScaningProductBarcode").''; } if ($conf->productbatch->enabled) { print ''.$langs->trans('UpdateByScaningLot').''; }*/ - if ($conf->barcode->enabled || $conf->productbatch->enabled) { - print ''.$langs->trans("UpdateByScaning").''; - } - } else { - print ''.$langs->trans('Save').''."\n"; - } - } + if ($conf->barcode->enabled || $conf->productbatch->enabled) { + print ''.$langs->trans("UpdateByScaning").''; + } + } else { + print ''.$langs->trans('Save').''."\n"; + } + } - if ($object->status == Inventory::STATUS_VALIDATED) - { - if ($permissiontoadd) - { - print ''.$langs->trans("Finish").''."\n"; - } else { - print ''.$langs->trans('Finish').''."\n"; - } - } + if ($object->status == Inventory::STATUS_VALIDATED) + { + if ($permissiontoadd) + { + print ''.$langs->trans("Finish").''."\n"; + } else { + print ''.$langs->trans('Finish').''."\n"; + } + } - /*if ($object->status == Inventory::STATUS_VALIDATED) + /*if ($object->status == Inventory::STATUS_VALIDATED) { if ($permissiontoadd) { diff --git a/htdocs/product/list.php b/htdocs/product/list.php index d28bbef42c3..35a04f93613 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -219,7 +219,7 @@ $arrayfields = array( ); // MultiPrices -if ($conf->global->PRODUIT_MULTIPRICES){ +if ($conf->global->PRODUIT_MULTIPRICES) { for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; @@ -753,7 +753,7 @@ if ($resql) } // Multiprice - if ($conf->global->PRODUIT_MULTIPRICES){ + if ($conf->global->PRODUIT_MULTIPRICES) { foreach ($arraypricelevel as $key => $value) { if (!empty($arrayfields['p.sellprice'.$key]['checked'])) @@ -905,7 +905,7 @@ if ($resql) } // Multiprices - if ($conf->global->PRODUIT_MULTIPRICES){ + if ($conf->global->PRODUIT_MULTIPRICES) { foreach ($arraypricelevel as $key => $value) { if (!empty($arrayfields['p.sellprice'.$key]['checked'])) @@ -1265,7 +1265,7 @@ if ($resql) // Multiprices - if ($conf->global->PRODUIT_MULTIPRICES){ + if ($conf->global->PRODUIT_MULTIPRICES) { foreach ($arraypricelevel as $key => $value) { if (!empty($arrayfields['p.sellprice'.$key]['checked'])) diff --git a/htdocs/product/stock/class/entrepot.class.php b/htdocs/product/stock/class/entrepot.class.php index 25857803843..d63469308b3 100644 --- a/htdocs/product/stock/class/entrepot.class.php +++ b/htdocs/product/stock/class/entrepot.class.php @@ -736,7 +736,7 @@ class Entrepot extends CommonObject $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 .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label)?$this->libelle:$this->label)); + if ($withpicto != 2) $result .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label)); $result .= $linkend; global $action; diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php index fe6e8d3e829..cd83f2c19c8 100644 --- a/htdocs/product/stock/product.php +++ b/htdocs/product/stock/product.php @@ -39,7 +39,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productstockentrepot.class.php'; if (!empty($conf->productbatch->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; } if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -88,7 +88,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); if ($id > 0 || !empty($ref)) { - $result = $object->fetch($id, $ref); + $result = $object->fetch($id, $ref); } if (empty($id) && !empty($object->id)) $id = $object->id; @@ -100,9 +100,9 @@ $canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas"); $objcanvas = null; if (!empty($canvas)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; - $objcanvas = new Canvas($db, $action); - $objcanvas->getCanvas('stockproduct', 'card', $canvas); + require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; + $objcanvas = new Canvas($db, $action); + $objcanvas->getCanvas('stockproduct', 'card', $canvas); } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -168,27 +168,27 @@ if ($action == 'delete_productstockwarehouse' && !empty($user->rights->produit-> // Set stock limit if ($action == 'setseuil_stock_alerte' && !empty($user->rights->produit->creer)) { - $object = new Product($db); - $result = $object->fetch($id); - $object->seuil_stock_alerte = $stocklimit; - $result = $object->update($object->id, $user, 0, 'update'); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); - //else - // setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs'); - $action = ''; + $object = new Product($db); + $result = $object->fetch($id); + $object->seuil_stock_alerte = $stocklimit; + $result = $object->update($object->id, $user, 0, 'update'); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); + //else + // setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs'); + $action = ''; } // Set desired stock if ($action == 'setdesiredstock' && !empty($user->rights->produit->creer)) { - $object = new Product($db); - $result = $object->fetch($id); - $object->desiredstock = $desiredstock; - $result = $object->update($object->id, $user, 0, 'update'); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); - $action = ''; + $object = new Product($db); + $result = $object->fetch($id); + $object->desiredstock = $desiredstock; + $result = $object->update($object->id, $user, 0, 'update'); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); + $action = ''; } @@ -258,12 +258,12 @@ if ($action == "correct_stock" && !$cancel) ); // We do not change value of stock for a correction } else { $result = $object->correct_stock( - $user, - GETPOST("id_entrepot", 'int'), + $user, + GETPOST("id_entrepot", 'int'), $nbpiece, - GETPOST("mouvement", 'int'), - GETPOST("label", 'alphanohtml'), - $priceunit, + GETPOST("mouvement", 'int'), + GETPOST("label", 'alphanohtml'), + $priceunit, GETPOST('inventorycode', 'alphanohtml'), $origin_element, $origin_id @@ -277,12 +277,12 @@ if ($action == "correct_stock" && !$cancel) header("Location: ".$backtopage); exit; } else { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; } } else { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'correction'; + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'correction'; } } } @@ -311,15 +311,15 @@ if ($action == "transfert_stock" && !$cancel) } if (!empty($conf->productbatch->enabled)) { - $object = new Product($db); - $result = $object->fetch($id); + $object = new Product($db); + $result = $object->fetch($id); - if ($object->hasbatch() && !$batchnumber) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); - $error++; - $action = 'transfert'; - } + if ($object->hasbatch() && !$batchnumber) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); + $error++; + $action = 'transfert'; + } } if (!$error) @@ -399,31 +399,31 @@ if ($action == "transfert_stock" && !$cancel) } else { if (!$error) { - // Remove stock - $result1 = $object->correct_stock( - $user, - GETPOST("id_entrepot", 'int'), - $nbpiece, - 1, - GETPOST("label", 'alphanohtml'), - $pricesrc, - GETPOST('inventorycode', 'alphanohtml') - ); - if ($result1 < 0) $error++; + // Remove stock + $result1 = $object->correct_stock( + $user, + GETPOST("id_entrepot", 'int'), + $nbpiece, + 1, + GETPOST("label", 'alphanohtml'), + $pricesrc, + GETPOST('inventorycode', 'alphanohtml') + ); + if ($result1 < 0) $error++; } if (!$error) { - // Add stock - $result2 = $object->correct_stock( - $user, - GETPOST("id_entrepot_destination", 'int'), - $nbpiece, - 0, - GETPOST("label", 'alphanohtml'), - $pricedest, - GETPOST('inventorycode', 'alphanohtml') - ); - if ($result2 < 0) $error++; + // Add stock + $result2 = $object->correct_stock( + $user, + GETPOST("id_entrepot_destination", 'int'), + $nbpiece, + 0, + GETPOST("label", 'alphanohtml'), + $pricedest, + GETPOST('inventorycode', 'alphanohtml') + ); + if ($result2 < 0) $error++; } } @@ -452,35 +452,35 @@ if ($action == "transfert_stock" && !$cancel) // Update batch information if ($action == 'updateline' && GETPOST('save') == $langs->trans('Save')) { - $pdluo = new Productbatch($db); - $result = $pdluo->fetch(GETPOST('pdluoid', 'int')); + $pdluo = new Productbatch($db); + $result = $pdluo->fetch(GETPOST('pdluoid', 'int')); - if ($result > 0) - { - if ($pdluo->id) - { - if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors'); - } else { - $d_eatby = dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); - $d_sellby = dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); - $pdluo->batch = $batchnumber; - $pdluo->eatby = $d_eatby; - $pdluo->sellby = $d_sellby; - $result = $pdluo->update($user); - if ($result < 0) - { - setEventMessages($pdluo->error, $pdluo->errors, 'errors'); - } - } - } else { - setEventMessages($langs->trans('BatchInformationNotfound'), null, 'errors'); - } - } else { - setEventMessages($pdluo->error, null, 'errors'); - } - header("Location: product.php?id=".$id); - exit; + if ($result > 0) + { + if ($pdluo->id) + { + if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors'); + } else { + $d_eatby = dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); + $d_sellby = dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); + $pdluo->batch = $batchnumber; + $pdluo->eatby = $d_eatby; + $pdluo->sellby = $d_sellby; + $result = $pdluo->update($user); + if ($result < 0) + { + setEventMessages($pdluo->error, $pdluo->errors, 'errors'); + } + } + } else { + setEventMessages($langs->trans('BatchInformationNotfound'), null, 'errors'); + } + } else { + setEventMessages($pdluo->error, null, 'errors'); + } + header("Location: product.php?id=".$id); + exit; } @@ -528,17 +528,17 @@ if ($id > 0 || $ref) dol_htmloutput_events(); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $shownav = 1; - if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + $shownav = 1; + if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; - dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); + dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); - print '
'; + print '
'; - print '
'; - print ''; + print '
'; + print '
'; if (!$variants) { if ($conf->productbatch->enabled) { @@ -629,7 +629,7 @@ if ($id > 0 || $ref) $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) ? $langs->trans("ReStockOnBill").'
' : ''); $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) ? $langs->trans("ReStockOnValidateOrder").'
' : ''); $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) ? $langs->trans("ReStockOnDispatchOrder").'
' : ''); - $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) ? $langs->trans("StockOnReception").'
' : ''); + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) ? $langs->trans("StockOnReception").'
' : ''); print '
'; print $form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1); @@ -656,13 +656,13 @@ if ($id > 0 || $ref) // Number of product from customer order already sent (partial shipping) if (!empty($conf->expedition->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; - $filterShipmentStatus = ''; - if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { - $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED; - } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { - $filterShipmentStatus = Expedition::STATUS_CLOSED; - } + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; + $filterShipmentStatus = ''; + if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { + $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED; + } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { + $filterShipmentStatus = Expedition::STATUS_CLOSED; + } if ($found) $helpondiff .= '
'; else $found = 1; $result = $object->load_stats_sending(0, '2', 1, $filterShipmentStatus); $helpondiff .= $langs->trans("ProductQtyInShipmentAlreadySent").': '.$object->stats_expedition['qty']; @@ -730,8 +730,8 @@ if ($id > 0 || $ref) } print "
"; - print '
'; - print '
'; + print '
'; + print '
'; dol_fiche_end(); } @@ -763,7 +763,7 @@ if (empty($reshook)) { if (empty($action) && $object->id) { - print "
\n"; + print "
\n"; if ($user->rights->stock->mouvement->creer) { diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index a9175780491..539617f55aa 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -492,7 +492,7 @@ class Project extends CommonObject $sql .= " WHERE entity IN (".getEntity('project').")"; if (!empty($ref)) { $sql .= " AND ref = '".$this->db->escape($ref)."'"; - } elseif (! empty($ref_ext)) { + } elseif (!empty($ref_ext)) { $sql .= " AND ref_ext = '".$this->db->escape($ref_ext)."'"; } else { $sql .= " AND email_msgid = '".$this->db->escape($email_msgid)."'"; diff --git a/htdocs/recruitment/recruitmentindex.php b/htdocs/recruitment/recruitmentindex.php index 5b7a268d6fb..4087ae25bd7 100644 --- a/htdocs/recruitment/recruitmentindex.php +++ b/htdocs/recruitment/recruitmentindex.php @@ -321,14 +321,14 @@ $NBMAX = 3; $max = 3; // Last modified job position -if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) +if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) { $sql = "SELECT s.rowid, s.ref, s.label, s.date_creation, s.tms, s.status"; - $sql.= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE s.entity IN (".getEntity($staticrecruitmentjobposition->element).")"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($socid) $sql.= " AND s.fk_soc = $socid"; + $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE s.entity IN (".getEntity($staticrecruitmentjobposition->element).")"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) $sql .= " AND s.fk_soc = $socid"; $sql .= " ORDER BY s.tms DESC"; $sql .= $db->plimit($max, 0); @@ -379,15 +379,15 @@ if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitm } // Last modified job position -if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) +if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) { $sql = "SELECT rc.rowid, rc.ref, rc.email, rc.lastname, rc.firstname, rc.date_creation, rc.tms, rc.status"; - $sql.= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s ON rc.fk_recruitmentjobposition = s.rowid"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE rc.entity IN (".getEntity($staticrecruitmentjobposition->element).")"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($socid) $sql.= " AND s.fk_soc = $socid"; + $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s ON rc.fk_recruitmentjobposition = s.rowid"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE rc.entity IN (".getEntity($staticrecruitmentjobposition->element).")"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) $sql .= " AND s.fk_soc = $socid"; $sql .= " ORDER BY rc.tms DESC"; $sql .= $db->plimit($max, 0); @@ -409,9 +409,9 @@ if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitm while ($i < $num) { $objp = $db->fetch_object($resql); - $staticrecruitmentcandidature->id=$objp->rowid; - $staticrecruitmentcandidature->ref=$objp->ref; - $staticrecruitmentcandidature->email=$objp->email; + $staticrecruitmentcandidature->id = $objp->rowid; + $staticrecruitmentcandidature->ref = $objp->ref; + $staticrecruitmentcandidature->email = $objp->email; $staticrecruitmentcandidature->status = $objp->status; $staticrecruitmentcandidature->date_creation = $objp->date_creation; $staticrecruitmentcandidature->firstname = $objp->firstname; diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 539a39b4140..6d412ae6f0a 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -36,11 +36,11 @@ class Stripe extends CommonObject /** * @var int Thirdparty ID */ - public $fk_soc; + public $fk_soc; - /** - * @var int ID - */ + /** + * @var int ID + */ public $fk_key; /** @@ -62,9 +62,9 @@ class Stripe extends CommonObject public $code; public $declinecode; - /** - * @var string Message - */ + /** + * @var string Message + */ public $message; /** @@ -102,21 +102,21 @@ class Stripe extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) { + if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $tokenstring = $obj->tokenstring; + $tokenstring = $obj->tokenstring; - $tmparray = dol_json_decode($tokenstring); - $key = $tmparray->stripe_user_id; - } else { - $tokenstring = ''; - } - } else { - dol_print_error($this->db); - } + $tmparray = dol_json_decode($tokenstring); + $key = $tmparray->stripe_user_id; + } else { + $tokenstring = ''; + } + } else { + dol_print_error($this->db); + } - dol_syslog("No dedicated Stripe Connect account available for entity ".$conf->entity); + dol_syslog("No dedicated Stripe Connect account available for entity ".$conf->entity); return $key; } @@ -194,7 +194,7 @@ class Stripe extends CommonObject } } elseif ($createifnotlinkedtostripe) { - $ipaddress = getUserRemoteIP(); + $ipaddress = getUserRemoteIP(); $dataforcustomer = array( "email" => $object->email, @@ -291,9 +291,9 @@ class Stripe extends CommonObject return $stripepaymentmethod; } - /** + /** * Get the Stripe payment intent. Create it with confirmnow=false - * Warning. If a payment was tried and failed, a payment intent was created. + * Warning. If a payment was tried and failed, a payment intent was created. * But if we change something on object to pay (amount or other), reusing same payment intent is not allowed by Stripe. * Recommended solution is to recreate a new payment intent each time we need one (old one will be automatically closed after a delay), * that's why i comment the part of code to retreive a payment intent with object id (never mind if we cumulate payment intent with old ones that will not be used) @@ -333,9 +333,9 @@ class Stripe extends CommonObject $fee = $amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE; if ($fee >= $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL && $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL > $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) { - $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL; + $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL; } elseif ($fee < $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) { - $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL; + $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL; } if (!in_array($currency_code, $arrayzerounitcurrency)) { $stripefee = round($fee * 100); @@ -345,7 +345,7 @@ class Stripe extends CommonObject $paymentintent = null; - if (is_object($object) && ! empty($conf->global->STRIPE_REUSE_EXISTING_INTENT_IF_FOUND)) + if (is_object($object) && !empty($conf->global->STRIPE_REUSE_EXISTING_INTENT_IF_FOUND)) { // Warning. If a payment was tried and failed, a payment intent was created. // But if we change something on object to pay (amount or other that does not change the idempotency key), reusing same payment intent is not allowed by Stripe. @@ -354,167 +354,167 @@ class Stripe extends CommonObject // That's why we can comment the part of code to retreive a payment intent with object id (never mind if we cumulate payment intent with old ones that will not be used) $sql = "SELECT pi.ext_payment_id, pi.entity, pi.fk_facture, pi.sourcetype, pi.ext_payment_site"; - $sql.= " FROM " . MAIN_DB_PREFIX . "prelevement_facture_demande as pi"; - $sql.= " WHERE pi.fk_facture = " . $object->id; - $sql.= " AND pi.sourcetype = '" . $object->element . "'"; - $sql.= " AND pi.entity IN (".getEntity('societe').")"; - $sql.= " AND pi.ext_payment_site = '" . $service . "'"; + $sql.= " FROM " . MAIN_DB_PREFIX . "prelevement_facture_demande as pi"; + $sql.= " WHERE pi.fk_facture = " . $object->id; + $sql.= " AND pi.sourcetype = '" . $object->element . "'"; + $sql.= " AND pi.entity IN (".getEntity('societe').")"; + $sql.= " AND pi.ext_payment_site = '" . $service . "'"; - dol_syslog(get_class($this) . "::getPaymentIntent search stripe payment intent for object id = ".$object->id, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - if ($num) - { - $obj = $this->db->fetch_object($resql); - $intent = $obj->ext_payment_id; + dol_syslog(get_class($this) . "::getPaymentIntent search stripe payment intent for object id = ".$object->id, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + if ($num) + { + $obj = $this->db->fetch_object($resql); + $intent = $obj->ext_payment_id; - dol_syslog(get_class($this) . "::getPaymentIntent found existing payment intent record"); + dol_syslog(get_class($this) . "::getPaymentIntent found existing payment intent record"); - // Force to use the correct API key - global $stripearrayofkeysbyenv; - \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']); + // Force to use the correct API key + global $stripearrayofkeysbyenv; + \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']); - try { - if (empty($key)) { // If the Stripe connect account not set, we use common API usage - $paymentintent = \Stripe\PaymentIntent::retrieve($intent); - } else { - $paymentintent = \Stripe\PaymentIntent::retrieve($intent, array("stripe_account" => $key)); - } - } - catch (Exception $e) { - $error++; - $this->error = $e->getMessage(); - } - } - } + try { + if (empty($key)) { // If the Stripe connect account not set, we use common API usage + $paymentintent = \Stripe\PaymentIntent::retrieve($intent); + } else { + $paymentintent = \Stripe\PaymentIntent::retrieve($intent, array("stripe_account" => $key)); + } + } + catch (Exception $e) { + $error++; + $this->error = $e->getMessage(); + } + } + } } if (empty($paymentintent)) { - $ipaddress = getUserRemoteIP(); - $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress); - if (is_object($object)) - { - $metadata['dol_type'] = $object->element; - $metadata['dol_id'] = $object->id; + $ipaddress = getUserRemoteIP(); + $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress); + if (is_object($object)) + { + $metadata['dol_type'] = $object->element; + $metadata['dol_id'] = $object->id; if (is_object($object->thirdparty) && $object->thirdparty->id > 0) $metadata['dol_thirdparty_id'] = $object->thirdparty->id; - } + } - // list of payment method types - $paymentmethodtypes = array("card"); - if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT) ) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) - if (!empty($conf->global->STRIPE_IDEAL) ) $paymentmethodtypes[] = "ideal"; //&& ($object->thirdparty->isInEEC()) + // list of payment method types + $paymentmethodtypes = array("card"); + if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT) ) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) + if (!empty($conf->global->STRIPE_IDEAL) ) $paymentmethodtypes[] = "ideal"; //&& ($object->thirdparty->isInEEC()) - $dataforintent = array( - "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent - "confirmation_method" => $mode, - "amount" => $stripeamount, - "currency" => $currency_code, - "payment_method_types" => $paymentmethodtypes, - "description" => $description, - "statement_descriptor_suffix" => dol_trunc($tag, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) - //"save_payment_method" => true, + $dataforintent = array( + "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent + "confirmation_method" => $mode, + "amount" => $stripeamount, + "currency" => $currency_code, + "payment_method_types" => $paymentmethodtypes, + "description" => $description, + "statement_descriptor_suffix" => dol_trunc($tag, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + //"save_payment_method" => true, "setup_future_usage" => "on_session", - "metadata" => $metadata - ); - if (!is_null($customer)) $dataforintent["customer"] = $customer; - // payment_method = - // payment_method_types = array('card') - //var_dump($dataforintent); - if ($off_session) - { - unset($dataforintent['setup_future_usage']); - $dataforintent["off_session"] = true; - } - if (!is_null($payment_method)) - { - $dataforintent["payment_method"] = $payment_method; - $description .= ' - '.$payment_method; - } + "metadata" => $metadata + ); + if (!is_null($customer)) $dataforintent["customer"] = $customer; + // payment_method = + // payment_method_types = array('card') + //var_dump($dataforintent); + if ($off_session) + { + unset($dataforintent['setup_future_usage']); + $dataforintent["off_session"] = true; + } + if (!is_null($payment_method)) + { + $dataforintent["payment_method"] = $payment_method; + $description .= ' - '.$payment_method; + } - if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) - { - $dataforintent["application_fee_amount"] = $stripefee; - } - if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) - { - $dataforintent["receipt_email"] = $object->thirdparty->email; - } + if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) + { + $dataforintent["application_fee_amount"] = $stripefee; + } + if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) + { + $dataforintent["receipt_email"] = $object->thirdparty->email; + } - try { - // Force to use the correct API key - global $stripearrayofkeysbyenv; - \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']); + try { + // Force to use the correct API key + global $stripearrayofkeysbyenv; + \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']); - $arrayofoptions = array(); - if (empty($noidempotency_key)) { - $arrayofoptions["idempotency_key"] = $description; - } - // Note: If all data for payment intent are same than a previous on, even if we use 'create', Stripe will return ID of the old existing payment intent. - if (!empty($key)) { // If the Stripe connect account not set, we use common API usage - $arrayofoptions["stripe_account"] = $key; - } - $paymentintent = \Stripe\PaymentIntent::create($dataforintent, $arrayofoptions); + $arrayofoptions = array(); + if (empty($noidempotency_key)) { + $arrayofoptions["idempotency_key"] = $description; + } + // Note: If all data for payment intent are same than a previous on, even if we use 'create', Stripe will return ID of the old existing payment intent. + if (!empty($key)) { // If the Stripe connect account not set, we use common API usage + $arrayofoptions["stripe_account"] = $key; + } + $paymentintent = \Stripe\PaymentIntent::create($dataforintent, $arrayofoptions); - // Store the payment intent - if (is_object($object)) - { - $paymentintentalreadyexists = 0; - // Check that payment intent $paymentintent->id is not already recorded. - $sql = "SELECT pi.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pi"; - $sql .= " WHERE pi.entity IN (".getEntity('societe').")"; - $sql .= " AND pi.ext_payment_site = '".$service."'"; - $sql .= " AND pi.ext_payment_id = '".$this->db->escape($paymentintent->id)."'"; + // Store the payment intent + if (is_object($object)) + { + $paymentintentalreadyexists = 0; + // Check that payment intent $paymentintent->id is not already recorded. + $sql = "SELECT pi.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pi"; + $sql .= " WHERE pi.entity IN (".getEntity('societe').")"; + $sql .= " AND pi.ext_payment_site = '".$service."'"; + $sql .= " AND pi.ext_payment_id = '".$this->db->escape($paymentintent->id)."'"; - dol_syslog(get_class($this)."::getPaymentIntent search if payment intent already in prelevement_facture_demande", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - if ($num) - { - $obj = $this->db->fetch_object($resql); - if ($obj) $paymentintentalreadyexists++; - } - } else dol_print_error($this->db); + dol_syslog(get_class($this)."::getPaymentIntent search if payment intent already in prelevement_facture_demande", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + if ($num) + { + $obj = $this->db->fetch_object($resql); + if ($obj) $paymentintentalreadyexists++; + } + } else dol_print_error($this->db); - // If not, we create it. - if (!$paymentintentalreadyexists) - { - $now = dol_now(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture_demande (date_demande, fk_user_demande, ext_payment_id, fk_facture, sourcetype, entity, ext_payment_site, amount)"; - $sql .= " VALUES ('".$this->db->idate($now)."', ".$user->id.", '".$this->db->escape($paymentintent->id)."', ".$object->id.", '".$this->db->escape($object->element)."', ".$conf->entity.", '".$service."', ".$amount.")"; - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::PaymentIntent failed to insert paymentintent with id=".$paymentintent->id." into database."); - } - } - } else { - $_SESSION["stripe_payment_intent"] = $paymentintent; - } - } catch (Stripe\Error\Card $e) - { - $error++; - $this->error = $e->getMessage(); - $this->code = $e->getStripeCode(); - $this->declinecode = $e->getDeclineCode(); - } catch (Exception $e) - { - /*var_dump($dataforintent); + // If not, we create it. + if (!$paymentintentalreadyexists) + { + $now = dol_now(); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture_demande (date_demande, fk_user_demande, ext_payment_id, fk_facture, sourcetype, entity, ext_payment_site, amount)"; + $sql .= " VALUES ('".$this->db->idate($now)."', ".$user->id.", '".$this->db->escape($paymentintent->id)."', ".$object->id.", '".$this->db->escape($object->element)."', ".$conf->entity.", '".$service."', ".$amount.")"; + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::PaymentIntent failed to insert paymentintent with id=".$paymentintent->id." into database."); + } + } + } else { + $_SESSION["stripe_payment_intent"] = $paymentintent; + } + } catch (Stripe\Error\Card $e) + { + $error++; + $this->error = $e->getMessage(); + $this->code = $e->getStripeCode(); + $this->declinecode = $e->getDeclineCode(); + } catch (Exception $e) + { + /*var_dump($dataforintent); var_dump($description); var_dump($key); var_dump($paymentintent); var_dump($e->getMessage()); var_dump($e);*/ - $error++; - $this->error = $e->getMessage(); - $this->code = ''; - $this->declinecode = ''; - } + $error++; + $this->error = $e->getMessage(); + $this->code = ''; + $this->declinecode = ''; + } } dol_syslog("getPaymentIntent return error=".$error." this->error=".$this->error, LOG_INFO, -1); @@ -572,7 +572,7 @@ class Stripe extends CommonObject // list of payment method types $paymentmethodtypes = array("card"); - if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT) ) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) + if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) // iDEAL not supported with setupIntent $dataforintent = array( @@ -933,10 +933,10 @@ class Stripe extends CommonObject } } elseif (preg_match('/acct_/i', $source)) { - $charge = \Stripe\Charge::create(array( + $charge = \Stripe\Charge::create(array( "amount" => "$stripeamount", "currency" => "$currency", - "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) "description" => "Stripe payment: ".$description, "capture" => $capture, "metadata" => $metadata, @@ -946,7 +946,7 @@ class Stripe extends CommonObject $paymentarray = array( "amount" => "$stripeamount", "currency" => "$currency", - "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) "description" => "Stripe payment: ".$description, "capture" => $capture, "metadata" => $metadata, @@ -965,9 +965,9 @@ class Stripe extends CommonObject // With Stripe Connect $fee = $amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE; if ($fee >= $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL && $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL > $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) { - $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL; + $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL; } elseif ($fee < $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) { - $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL; + $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL; } if (!in_array($currency, $arrayzerounitcurrency)) $stripefee = round($fee * 100); diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php index 344bea2d6be..d2f1ef2011e 100644 --- a/htdocs/supplier_proposal/class/supplier_proposal.class.php +++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php @@ -776,1897 +776,1897 @@ class SupplierProposal extends CommonObject $this->line->multicurrency_total_tva = $multicurrency_total_tva; $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $result = $this->line->update(); - if ($result > 0) - { - // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + $result = $this->line->update(); + if ($result > 0) + { + // Reorder if child line + if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); - $this->update_price(1); + $this->update_price(1); - $this->fk_supplier_proposal = $this->id; + $this->fk_supplier_proposal = $this->id; - $this->db->commit(); - return $result; - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } else { - dol_syslog(get_class($this)."::updateline Erreur -2 SupplierProposal en mode incompatible pour cette action"); - return -2; - } - } + $this->db->commit(); + return $result; + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } else { + dol_syslog(get_class($this)."::updateline Erreur -2 SupplierProposal en mode incompatible pour cette action"); + return -2; + } + } - /** - * Delete detail line - * - * @param int $lineid Id of line to delete - * @return int >0 if OK, <0 if KO - */ - public function deleteline($lineid) - { - if ($this->statut == 0) - { - $line = new SupplierProposalLine($this->db); + /** + * Delete detail line + * + * @param int $lineid Id of line to delete + * @return int >0 if OK, <0 if KO + */ + public function deleteline($lineid) + { + if ($this->statut == 0) + { + $line = new SupplierProposalLine($this->db); - // For triggers - $line->fetch($lineid); + // For triggers + $line->fetch($lineid); - if ($line->delete() > 0) - { - $this->update_price(1); + if ($line->delete() > 0) + { + $this->update_price(1); - return 1; - } else { - return -1; - } - } else { - return -2; - } - } + return 1; + } else { + return -1; + } + } else { + return -2; + } + } - /** - * Create commercial proposal into database - * this->ref can be set or empty. If empty, we will use "(PROVid)" - * - * @param User $user User that create - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >=0 if OK - */ - public function create($user, $notrigger = 0) - { - global $langs, $conf, $mysoc, $hookmanager; - $error = 0; + /** + * Create commercial proposal into database + * this->ref can be set or empty. If empty, we will use "(PROVid)" + * + * @param User $user User that create + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >=0 if OK + */ + public function create($user, $notrigger = 0) + { + global $langs, $conf, $mysoc, $hookmanager; + $error = 0; - $now = dol_now(); + $now = dol_now(); - dol_syslog(get_class($this)."::create"); + dol_syslog(get_class($this)."::create"); - // Check parameters - $result = $this->fetch_thirdparty(); - if ($result < 0) - { - $this->error = "Failed to fetch company"; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -3; - } + // Check parameters + $result = $this->fetch_thirdparty(); + if ($result < 0) + { + $this->error = "Failed to fetch company"; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -3; + } - // Check parameters - if (!empty($this->ref)) // We check that ref is not already used - { - $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used - if ($result > 0) - { - $this->error = 'ErrorRefAlreadyExists'; - dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); - $this->db->rollback(); - return -1; - } - } + // Check parameters + if (!empty($this->ref)) // We check that ref is not already used + { + $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used + if ($result > 0) + { + $this->error = 'ErrorRefAlreadyExists'; + dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); + $this->db->rollback(); + return -1; + } + } - // Multicurrency - if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now); - if (empty($this->fk_multicurrency)) - { - $this->multicurrency_code = $conf->currency; - $this->fk_multicurrency = 0; - $this->multicurrency_tx = 1; - } + // Multicurrency + if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now); + if (empty($this->fk_multicurrency)) + { + $this->multicurrency_code = $conf->currency; + $this->fk_multicurrency = 0; + $this->multicurrency_tx = 1; + } - $this->db->begin(); + $this->db->begin(); - // Insert into database - $sql = "INSERT INTO ".MAIN_DB_PREFIX."supplier_proposal ("; - $sql .= "fk_soc"; - $sql .= ", price"; - $sql .= ", remise"; - $sql .= ", remise_percent"; - $sql .= ", remise_absolue"; - $sql .= ", tva"; - $sql .= ", total"; - $sql .= ", datec"; - $sql .= ", ref"; - $sql .= ", fk_user_author"; - $sql .= ", note_private"; - $sql .= ", note_public"; - $sql .= ", model_pdf"; - $sql .= ", fk_cond_reglement"; - $sql .= ", fk_mode_reglement"; - $sql .= ", fk_account"; - $sql .= ", date_livraison"; - $sql .= ", fk_shipping_method"; - $sql .= ", fk_projet"; - $sql .= ", entity"; - $sql .= ", fk_multicurrency"; - $sql .= ", multicurrency_code"; - $sql .= ", multicurrency_tx"; - $sql .= ") "; - $sql .= " VALUES ("; - $sql .= $this->socid; - $sql .= ", 0"; - $sql .= ", ".$this->remise; - $sql .= ", ".($this->remise_percent ? $this->db->escape($this->remise_percent) : 'null'); - $sql .= ", ".($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'null'); - $sql .= ", 0"; - $sql .= ", 0"; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", '(PROV)'"; - $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null"); - $sql .= ", '".$this->db->escape($this->note_private)."'"; - $sql .= ", '".$this->db->escape($this->note_public)."'"; - $sql .= ", '".$this->db->escape($this->modelpdf)."'"; - $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); - $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); - $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); - $sql .= ", ".($this->date_livraison != '' ? "'".$this->db->idate($this->date_livraison)."'" : "null"); - $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL'); - $sql .= ", ".($this->fk_project ? $this->fk_project : "null"); - $sql .= ", ".$conf->entity; - $sql .= ", ".(int) $this->fk_multicurrency; - $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql .= ", ".(double) $this->multicurrency_tx; - $sql .= ")"; + // Insert into database + $sql = "INSERT INTO ".MAIN_DB_PREFIX."supplier_proposal ("; + $sql .= "fk_soc"; + $sql .= ", price"; + $sql .= ", remise"; + $sql .= ", remise_percent"; + $sql .= ", remise_absolue"; + $sql .= ", tva"; + $sql .= ", total"; + $sql .= ", datec"; + $sql .= ", ref"; + $sql .= ", fk_user_author"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", model_pdf"; + $sql .= ", fk_cond_reglement"; + $sql .= ", fk_mode_reglement"; + $sql .= ", fk_account"; + $sql .= ", date_livraison"; + $sql .= ", fk_shipping_method"; + $sql .= ", fk_projet"; + $sql .= ", entity"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ") "; + $sql .= " VALUES ("; + $sql .= $this->socid; + $sql .= ", 0"; + $sql .= ", ".$this->remise; + $sql .= ", ".($this->remise_percent ? $this->db->escape($this->remise_percent) : 'null'); + $sql .= ", ".($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'null'); + $sql .= ", 0"; + $sql .= ", 0"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", '(PROV)'"; + $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null"); + $sql .= ", '".$this->db->escape($this->note_private)."'"; + $sql .= ", '".$this->db->escape($this->note_public)."'"; + $sql .= ", '".$this->db->escape($this->modelpdf)."'"; + $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); + $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); + $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); + $sql .= ", ".($this->date_livraison != '' ? "'".$this->db->idate($this->date_livraison)."'" : "null"); + $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL'); + $sql .= ", ".($this->fk_project ? $this->fk_project : "null"); + $sql .= ", ".$conf->entity; + $sql .= ", ".(int) $this->fk_multicurrency; + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".(double) $this->multicurrency_tx; + $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."supplier_proposal"); + 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."supplier_proposal"); - if ($this->id) - { - $this->ref = '(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + if ($this->id) + { + $this->ref = '(PROV'.$this->id.')'; + $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) $error++; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) $error++; - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { - $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds - } + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects + { + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds + } - // Add object linked - if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) - { - 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) - { - dol_print_error($this->db); - $error++; - } - } - } - } - } + // Add object linked + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) + { + 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) + { + dol_print_error($this->db); + $error++; + } + } + } + } + } - /* + /* * Insertion du detail des produits dans la base */ - if (!$error) - { - $fk_parent_line = 0; - $num = count($this->lines); + if (!$error) + { + $fk_parent_line = 0; + $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { - // Reset fk_parent_line for no child products and special product - if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { - $fk_parent_line = 0; - } + for ($i = 0; $i < $num; $i++) + { + // Reset fk_parent_line for no child products and special product + if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { + $fk_parent_line = 0; + } - $result = $this->addline( - $this->lines[$i]->desc, - $this->lines[$i]->subprice, - $this->lines[$i]->qty, - $this->lines[$i]->tva_tx, - $this->lines[$i]->localtax1_tx, - $this->lines[$i]->localtax2_tx, - $this->lines[$i]->fk_product, - $this->lines[$i]->remise_percent, - 'HT', - 0, - 0, - $this->lines[$i]->product_type, - $this->lines[$i]->rang, - $this->lines[$i]->special_code, - $fk_parent_line, - $this->lines[$i]->fk_fournprice, - $this->lines[$i]->pa_ht, - $this->lines[$i]->label, - $this->lines[$i]->array_options, - $this->lines[$i]->ref_fourn, - $this->lines[$i]->fk_unit, - 'supplier_proposal', - $this->lines[$i]->rowid - ); + $result = $this->addline( + $this->lines[$i]->desc, + $this->lines[$i]->subprice, + $this->lines[$i]->qty, + $this->lines[$i]->tva_tx, + $this->lines[$i]->localtax1_tx, + $this->lines[$i]->localtax2_tx, + $this->lines[$i]->fk_product, + $this->lines[$i]->remise_percent, + 'HT', + 0, + 0, + $this->lines[$i]->product_type, + $this->lines[$i]->rang, + $this->lines[$i]->special_code, + $fk_parent_line, + $this->lines[$i]->fk_fournprice, + $this->lines[$i]->pa_ht, + $this->lines[$i]->label, + $this->lines[$i]->array_options, + $this->lines[$i]->ref_fourn, + $this->lines[$i]->fk_unit, + 'supplier_proposal', + $this->lines[$i]->rowid + ); - if ($result < 0) - { - $error++; - $this->error = $this->db->error; - dol_print_error($this->db); - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $this->lines[$i]->product_type == 9) { - $fk_parent_line = $result; - } - } - } + if ($result < 0) + { + $error++; + $this->error = $this->db->error; + dol_print_error($this->db); + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $this->lines[$i]->product_type == 9) { + $fk_parent_line = $result; + } + } + } - if (!$error) - { - // Mise a jour infos denormalisees - $resql = $this->update_price(1); - if ($resql) - { - $action = 'update'; + if (!$error) + { + // Mise a jour infos denormalisees + $resql = $this->update_price(1); + if ($resql) + { + $action = 'update'; - // Actions on extra fields - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + // Actions on extra fields + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('PROPOSAL_SUPPLIER_CREATE', $user); - if ($result < 0) { $error++; } - // End call triggers - } - } else { - $this->error = $this->db->lasterror(); - $error++; - } - } - } else { - $this->error = $this->db->lasterror(); - $error++; - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('PROPOSAL_SUPPLIER_CREATE', $user); + if ($result < 0) { $error++; } + // End call triggers + } + } else { + $this->error = $this->db->lasterror(); + $error++; + } + } + } else { + $this->error = $this->db->lasterror(); + $error++; + } - if (!$error) - { - $this->db->commit(); - dol_syslog(get_class($this)."::create done id=".$this->id); - return $this->id; - } else { - $this->db->rollback(); - return -2; - } - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + dol_syslog(get_class($this)."::create done id=".$this->id); + return $this->id; + } else { + $this->db->rollback(); + return -2; + } + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Insert into DB a supplier_proposal object completely defined by its data members (ex, results from copy). - * - * @param User $user User that create - * @return int Id of the new object if ok, <0 if ko - * @see create() - */ - public function create_from($user) - { - // phpcs:enable - $this->products = $this->lines; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Insert into DB a supplier_proposal object completely defined by its data members (ex, results from copy). + * + * @param User $user User that create + * @return int Id of the new object if ok, <0 if ko + * @see create() + */ + public function create_from($user) + { + // phpcs:enable + $this->products = $this->lines; - return $this->create($user); - } + return $this->create($user); + } - /** - * Load an object from its id and create a new one in database - * + /** + * Load an object from its id and create a new one in database + * * @param User $user User making the clone - * @param int $fromid Id of thirdparty - * @return int New id of clone - */ - public function createFromClone(User $user, $fromid = 0) - { - global $conf, $hookmanager; - - $error = 0; - $now = dol_now(); - - $this->db->begin(); - - // get extrafields so they will be clone - foreach ($this->lines as $line) - $line->fetch_optionals(); - - // Load source object - $objFrom = clone $this; - - $objsoc = new Societe($this->db); - - // Change socid if needed - if (!empty($fromid) && $fromid != $this->socid) - { - if ($objsoc->fetch($fromid) > 0) - { - $this->socid = $objsoc->id; - $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $this->fk_project = ''; - } - - // TODO Change product price if multi-prices - } else { - $objsoc->fetch($this->socid); - } - - $this->id = 0; - $this->statut = 0; - - if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php")) - { - $this->error = 'ErrorSetupNotComplete'; - return -1; - } - - // Clear fields - $this->user_author = $user->id; - $this->user_valid = ''; - $this->date = $now; - - // Set ref - require_once DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.'.php'; - $obj = $conf->global->SUPPLIER_PROPOSAL_ADDON; - $modSupplierProposal = new $obj; - $this->ref = $modSupplierProposal->getNextValue($objsoc, $this); - - // Create clone - $this->context['createfromclone'] = 'createfromclone'; - $result = $this->create($user); - if ($result < 0) $error++; - - if (!$error) - { - // Hook of thirdparty module - if (is_object($hookmanager)) - { - $parameters = array('objFrom'=>$objFrom); - $action = ''; - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; - } - } - - unset($this->context['createfromclone']); - - // End - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } - - /** - * Load a proposal from database and its ligne array - * - * @param int $rowid id of object to load - * @param string $ref Ref of proposal - * @return int >0 if OK, <0 if KO - */ - public function fetch($rowid, $ref = '') - { - global $conf; - - $sql = "SELECT p.rowid, p.entity, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; - $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; - $sql .= ", p.datec"; - $sql .= ", p.date_valid as datev"; - $sql .= ", p.date_livraison as date_livraison"; - $sql .= ", p.model_pdf, p.extraparams"; - $sql .= ", p.note_private, p.note_public"; - $sql .= ", p.fk_projet as fk_project, p.fk_statut"; - $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; - $sql .= ", p.fk_cond_reglement"; - $sql .= ", p.fk_mode_reglement"; - $sql .= ', p.fk_account'; - $sql .= ", p.fk_shipping_method"; - $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; - $sql .= ", c.label as statut_label"; - $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; - $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; - $sql .= " WHERE p.fk_statut = c.id"; - $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; - if ($ref) $sql .= " AND p.ref='".$ref."'"; - else $sql .= " AND p.rowid=".$rowid; - - 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->remise = $obj->remise; - $this->remise_percent = $obj->remise_percent; - $this->remise_absolue = $obj->remise_absolue; - $this->total = $obj->total; // TODO deprecated - $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->tva; - $this->total_localtax1 = $obj->localtax1; - $this->total_localtax2 = $obj->localtax2; - $this->total_ttc = $obj->total; - $this->socid = $obj->fk_soc; - $this->fk_project = $obj->fk_project; - $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; - $this->note = $obj->note_private; // TODO deprecated - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->statut = (int) $obj->fk_statut; - $this->statut_libelle = $obj->statut_label; - $this->datec = $this->db->jdate($obj->datec); // TODO deprecated - $this->datev = $this->db->jdate($obj->datev); // TODO deprecated - $this->date_creation = $this->db->jdate($obj->datec); //Creation date - $this->date_validation = $this->db->jdate($obj->datev); //Validation date - $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null; - - $this->mode_reglement_id = $obj->fk_mode_reglement; - $this->mode_reglement_code = $obj->mode_reglement_code; - $this->mode_reglement = $obj->mode_reglement; - $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null; - $this->cond_reglement_id = $obj->fk_cond_reglement; - $this->cond_reglement_code = $obj->cond_reglement_code; - $this->cond_reglement = $obj->cond_reglement; - $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; - - $this->extraparams = (array) json_decode($obj->extraparams, true); - - $this->user_author_id = $obj->fk_user_author; - $this->user_valid_id = $obj->fk_user_valid; - $this->user_close_id = $obj->fk_user_cloture; - - // Multicurrency - $this->fk_multicurrency = $obj->fk_multicurrency; - $this->multicurrency_code = $obj->multicurrency_code; - $this->multicurrency_tx = $obj->multicurrency_tx; - $this->multicurrency_total_ht = $obj->multicurrency_total_ht; - $this->multicurrency_total_tva = $obj->multicurrency_total_tva; - $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - - if ($obj->fk_statut == 0) - { - $this->brouillon = 1; - } - - // Retreive all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); - - $this->db->free($resql); - - $this->lines = array(); - - // Lines of supplier proposals - $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,"; - $sql .= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,"; - $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,'; - $sql .= ' d.ref_fourn as ref_produit_fourn,'; - $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit'; - $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; - $sql .= " WHERE d.fk_supplier_proposal = ".$this->id; - $sql .= " ORDER by d.rang"; - - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - - while ($i < $num) - { - $objp = $this->db->fetch_object($result); - - $line = new SupplierProposalLine($this->db); - - $line->rowid = $objp->rowid; // deprecated - $line->id = $objp->rowid; - $line->fk_supplier_proposal = $objp->fk_supplier_proposal; - $line->fk_parent_line = $objp->fk_parent_line; - $line->product_type = $objp->product_type; - $line->label = $objp->custom_label; - $line->desc = $objp->description; // Description ligne - $line->qty = $objp->qty; - $line->tva_tx = $objp->tva_tx; - $line->localtax1_tx = $objp->localtax1_tx; - $line->localtax2_tx = $objp->localtax2_tx; - $line->subprice = $objp->subprice; - $line->fk_remise_except = $objp->fk_remise_except; - $line->remise_percent = $objp->remise_percent; - - $line->info_bits = $objp->info_bits; - $line->total_ht = $objp->total_ht; - $line->total_tva = $objp->total_tva; - $line->total_localtax1 = $objp->total_localtax1; - $line->total_localtax2 = $objp->total_localtax2; - $line->total_ttc = $objp->total_ttc; - $line->fk_fournprice = $objp->fk_fournprice; - $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); - $line->pa_ht = $marginInfos[0]; - $line->marge_tx = $marginInfos[1]; - $line->marque_tx = $marginInfos[2]; - $line->special_code = $objp->special_code; - $line->rang = $objp->rang; - - $line->fk_product = $objp->fk_product; - - $line->ref = $objp->product_ref; // deprecated - $line->product_ref = $objp->product_ref; - $line->libelle = $objp->product_label; // deprecated - $line->product_label = $objp->product_label; - $line->product_desc = $objp->product_desc; // Description produit - $line->fk_product_type = $objp->fk_product_type; - - $line->ref_fourn = $objp->ref_produit_fourn; - - // Multicurrency - $line->fk_multicurrency = $objp->fk_multicurrency; - $line->multicurrency_code = $objp->multicurrency_code; - $line->multicurrency_subprice = $objp->multicurrency_subprice; - $line->multicurrency_total_ht = $objp->multicurrency_total_ht; - $line->multicurrency_total_tva = $objp->multicurrency_total_tva; - $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $line->fk_unit = $objp->fk_unit; - - $this->lines[$i] = $line; - - $i++; - } - $this->db->free($result); - } else { - $this->error = $this->db->error(); - return -1; - } - - // Retreive all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); - - return 1; - } - - $this->error = "Record Not Found"; - return 0; - } else { - $this->error = $this->db->error(); - return -1; - } - } - - /** - * Set status to validated - * - * @param User $user Object user that validate - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >=0 if OK - */ - public function valid($user, $notrigger = 0) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - global $conf, $langs; - - $error = 0; - $now = dol_now(); - - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance))) - { - $this->db->begin(); - - // Numbering module definition - $soc = new Societe($this->db); - $soc->fetch($this->socid); - - // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { - $num = $this->getNextNumRef($soc); - } else { - $num = $this->ref; - } - $this->newref = dol_sanitizeFileName($num); - - $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql .= " SET ref = '".$this->db->escape($num)."',"; - $sql .= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; - $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - - dol_syslog(get_class($this)."::valid", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - dol_print_error($this->db); - $error++; - } - - // Trigger calls - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('PROPOSAL_SUPPLIER_VALIDATE', $user); - if ($result < 0) { $error++; } - // End call triggers - } - - if (!$error) - { - $this->oldref = $this->ref; - - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { - // Now we rename also files into index - $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'"; - $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } - - // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments - $oldref = dol_sanitizeFileName($this->ref); - $newref = dol_sanitizeFileName($num); - $dirsource = $conf->supplier_proposal->dir_output.'/'.$oldref; - $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { - dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { - dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles = dol_dir_list($conf->supplier_proposal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { - $dirsource = $fileentry['name']; - $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource = $fileentry['path'].'/'.$dirsource; - $dirdest = $fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } - } - } - } - - $this->ref = $num; - $this->brouillon = 0; - $this->statut = 1; - $this->user_valid_id = $user->id; - $this->datev = $now; - - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - dol_syslog("You don't have permission to validate supplier proposal", LOG_WARNING); - return -2; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set delivery date - * - * @param User $user Object user that modify - * @param int $date_livraison Delivery date - * @return int <0 if ko, >0 if ok - */ - public function set_date_livraison($user, $date_livraison) - { - // phpcs:enable - if (!empty($user->rights->supplier_proposal->creer)) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; - $sql .= " SET date_livraison = ".($date_livraison != '' ? "'".$this->db->idate($date_livraison)."'" : 'null'); - $sql .= " WHERE rowid = ".$this->id; - - if ($this->db->query($sql)) - { - $this->date_livraison = $date_livraison; - return 1; - } else { - $this->error = $this->db->error(); - dol_syslog(get_class($this)."::set_date_livraison Erreur SQL"); - return -1; - } - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set an overall discount on the proposal - * - * @param User $user Object user that modify - * @param double $remise Amount discount - * @return int <0 if ko, >0 if ok - */ - public function set_remise_percent($user, $remise) - { - // phpcs:enable - $remise = trim($remise) ?trim($remise) : 0; - - if (!empty($user->rights->supplier_proposal->creer)) - { - $remise = price2num($remise); - - $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET remise_percent = ".$remise; - $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - - if ($this->db->query($sql)) - { - $this->remise_percent = $remise; - $this->update_price(1); - return 1; - } else { - $this->error = $this->db->error(); - return -1; - } - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set an absolute overall discount on the proposal - * - * @param User $user Object user that modify - * @param double $remise Amount discount - * @return int <0 if ko, >0 if ok - */ - public function set_remise_absolue($user, $remise) - { - // phpcs:enable - $remise = trim($remise) ?trim($remise) : 0; - - if (!empty($user->rights->supplier_proposal->creer)) - { - $remise = price2num($remise); - - $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; - $sql .= " SET remise_absolue = ".$remise; - $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - - if ($this->db->query($sql)) - { - $this->remise_absolue = $remise; - $this->update_price(1); - return 1; - } else { - $this->error = $this->db->error(); - return -1; - } - } - } - - - - /** - * Reopen the commercial proposal - * - * @param User $user Object user that close - * @param int $statut Statut - * @param string $note Comment - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - public function reopen($user, $statut, $note = '', $notrigger = 0) - { - global $langs, $conf; - - $this->statut = $statut; - $error = 0; - - $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql .= " SET fk_statut = ".$this->statut.","; - if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',"; - $sql .= " date_cloture=NULL, fk_user_cloture=NULL"; - $sql .= " WHERE rowid = ".$this->id; - - $this->db->begin(); - - dol_syslog(get_class($this)."::reopen", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); - } - if (!$error) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('PROPOSAL_SUPPLIER_REOPEN', $user); - if ($result < 0) { $error++; } - // End call triggers - } - } - - // Commit or rollback - if ($error) - { - if (!empty($this->errors)) - { - 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; - } - } - - - /** - * Close the askprice - * - * @param User $user Object user that close - * @param int $status Status - * @param string $note Comment - * @return int <0 if KO, >0 if OK - */ - public function cloture($user, $status, $note) - { - global $langs, $conf; - - $this->statut = $status; - $error = 0; - $now = dol_now(); - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql .= " SET fk_statut = ".$status.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; - $sql .= " WHERE rowid = ".$this->id; - - $resql = $this->db->query($sql); - if ($resql) - { - $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : $this->modelpdf; - $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED'; - - if ($status == 2) - { - $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED'; - $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : $this->modelpdf; - - if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists - { - $result = $this->updateOrCreatePriceFournisseur($user); - } - } - if ($status == 4) - { - $triggerName = 'PROPOSAL_SUPPLIER_CLASSIFY_BILLED'; - } - - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - // Define output language - $outputlangs = $langs; - if (!empty($conf->global->MAIN_MULTILANGS)) { - $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); - $outputlangs->setDefaultLang($newlang); - } - //$ret=$object->fetch($id); // Reload to get new records - $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - - // Call trigger - $result = $this->call_trigger($triggerName, $user); - if ($result < 0) { $error++; } - // End call triggers - - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - /** - * Add or update supplier price according to result of proposal - * - * @param User $user Object user - * @return int > 0 if OK - */ - public function updateOrCreatePriceFournisseur($user) - { - global $conf; - - dol_syslog(get_class($this)."::updateOrCreatePriceFournisseur", LOG_DEBUG); - foreach ($this->lines as $product) - { - if ($product->subprice <= 0) continue; - $productsupplier = new ProductFournisseur($this->db); - - $multicurrency_tx = 1; - $fk_multicurrency = 0; - - if (empty($this->thirdparty)) $this->fetch_thirdparty(); - - $ref_fourn = $product->ref_fourn; - if (empty($ref_fourn)) $ref_fourn = $product->ref_supplier; - if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code); - $productsupplier->id = $product->fk_product; - - $productsupplier->update_buyprice($product->qty, $product->total_ht, $user, 'HT', $this->thirdparty, '', $ref_fourn, $product->tva_tx, 0, 0, 0, $product->info_bits, '', '', array(), '', $product->multicurrency_total_ht, 'HT', $multicurrency_tx, $product->multicurrency_code, '', '', ''); - } - - return 1; - } - - /** - * Upate ProductFournisseur - * - * @param int $idProductFournPrice id of llx_product_fournisseur_price - * @param Product $product contain informations to update - * @param User $user Object user - * @return int <0 if KO, >0 if OK - */ - public function updatePriceFournisseur($idProductFournPrice, $product, $user) - { - $price = price2num($product->subprice * $product->qty, 'MU'); - $unitPrice = price2num($product->subprice, 'MU'); - - $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_fournisseur_price SET '.(!empty($product->ref_fourn) ? 'ref_fourn = "'.$product->ref_fourn.'", ' : '').' price ='.$price.', unitprice ='.$unitPrice.' WHERE rowid = '.$idProductFournPrice; - - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } - - /** - * Create ProductFournisseur - * - * @param Product $product Object Product - * @param User $user Object user - * @return int <0 if KO, >0 if OK - */ - public function createPriceFournisseur($product, $user) - { - global $conf; - - $price = price2num($product->subprice * $product->qty, 'MU'); - $qty = price2num($product->qty); - $unitPrice = price2num($product->subprice, 'MU'); - - $now = dol_now(); - - $values = array( - "'".$this->db->idate($now)."'", - $product->fk_product, - $this->thirdparty->id, - "'".$product->ref_fourn."'", - $price, - $qty, - $unitPrice, - $product->tva_tx, - $user->id - ); - if (!empty($conf->multicurrency->enabled)) { - if (!empty($product->multicurrency_code)) { + * @param int $fromid Id of thirdparty + * @return int New id of clone + */ + public function createFromClone(User $user, $fromid = 0) + { + global $conf, $hookmanager; + + $error = 0; + $now = dol_now(); + + $this->db->begin(); + + // get extrafields so they will be clone + foreach ($this->lines as $line) + $line->fetch_optionals(); + + // Load source object + $objFrom = clone $this; + + $objsoc = new Societe($this->db); + + // Change socid if needed + if (!empty($fromid) && $fromid != $this->socid) + { + if ($objsoc->fetch($fromid) > 0) + { + $this->socid = $objsoc->id; + $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $this->fk_project = ''; + } + + // TODO Change product price if multi-prices + } else { + $objsoc->fetch($this->socid); + } + + $this->id = 0; + $this->statut = 0; + + if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php")) + { + $this->error = 'ErrorSetupNotComplete'; + return -1; + } + + // Clear fields + $this->user_author = $user->id; + $this->user_valid = ''; + $this->date = $now; + + // Set ref + require_once DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.'.php'; + $obj = $conf->global->SUPPLIER_PROPOSAL_ADDON; + $modSupplierProposal = new $obj; + $this->ref = $modSupplierProposal->getNextValue($objsoc, $this); + + // Create clone + $this->context['createfromclone'] = 'createfromclone'; + $result = $this->create($user); + if ($result < 0) $error++; + + if (!$error) + { + // Hook of thirdparty module + if (is_object($hookmanager)) + { + $parameters = array('objFrom'=>$objFrom); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } + } + + unset($this->context['createfromclone']); + + // End + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load a proposal from database and its ligne array + * + * @param int $rowid id of object to load + * @param string $ref Ref of proposal + * @return int >0 if OK, <0 if KO + */ + public function fetch($rowid, $ref = '') + { + global $conf; + + $sql = "SELECT p.rowid, p.entity, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; + $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; + $sql .= ", p.datec"; + $sql .= ", p.date_valid as datev"; + $sql .= ", p.date_livraison as date_livraison"; + $sql .= ", p.model_pdf, p.extraparams"; + $sql .= ", p.note_private, p.note_public"; + $sql .= ", p.fk_projet as fk_project, p.fk_statut"; + $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; + $sql .= ", p.fk_cond_reglement"; + $sql .= ", p.fk_mode_reglement"; + $sql .= ', p.fk_account'; + $sql .= ", p.fk_shipping_method"; + $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; + $sql .= ", c.label as statut_label"; + $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; + $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; + $sql .= " WHERE p.fk_statut = c.id"; + $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; + if ($ref) $sql .= " AND p.ref='".$ref."'"; + else $sql .= " AND p.rowid=".$rowid; + + 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->remise = $obj->remise; + $this->remise_percent = $obj->remise_percent; + $this->remise_absolue = $obj->remise_absolue; + $this->total = $obj->total; // TODO deprecated + $this->total_ht = $obj->total_ht; + $this->total_tva = $obj->tva; + $this->total_localtax1 = $obj->localtax1; + $this->total_localtax2 = $obj->localtax2; + $this->total_ttc = $obj->total; + $this->socid = $obj->fk_soc; + $this->fk_project = $obj->fk_project; + $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; + $this->note = $obj->note_private; // TODO deprecated + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->statut = (int) $obj->fk_statut; + $this->statut_libelle = $obj->statut_label; + $this->datec = $this->db->jdate($obj->datec); // TODO deprecated + $this->datev = $this->db->jdate($obj->datev); // TODO deprecated + $this->date_creation = $this->db->jdate($obj->datec); //Creation date + $this->date_validation = $this->db->jdate($obj->datev); //Validation date + $this->date_livraison = $this->db->jdate($obj->date_livraison); + $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null; + + $this->mode_reglement_id = $obj->fk_mode_reglement; + $this->mode_reglement_code = $obj->mode_reglement_code; + $this->mode_reglement = $obj->mode_reglement; + $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null; + $this->cond_reglement_id = $obj->fk_cond_reglement; + $this->cond_reglement_code = $obj->cond_reglement_code; + $this->cond_reglement = $obj->cond_reglement; + $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + + $this->extraparams = (array) json_decode($obj->extraparams, true); + + $this->user_author_id = $obj->fk_user_author; + $this->user_valid_id = $obj->fk_user_valid; + $this->user_close_id = $obj->fk_user_cloture; + + // Multicurrency + $this->fk_multicurrency = $obj->fk_multicurrency; + $this->multicurrency_code = $obj->multicurrency_code; + $this->multicurrency_tx = $obj->multicurrency_tx; + $this->multicurrency_total_ht = $obj->multicurrency_total_ht; + $this->multicurrency_total_tva = $obj->multicurrency_total_tva; + $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; + + if ($obj->fk_statut == 0) + { + $this->brouillon = 1; + } + + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); + + $this->db->free($resql); + + $this->lines = array(); + + // Lines of supplier proposals + $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,"; + $sql .= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,"; + $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,'; + $sql .= ' d.ref_fourn as ref_produit_fourn,'; + $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit'; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; + $sql .= " WHERE d.fk_supplier_proposal = ".$this->id; + $sql .= " ORDER by d.rang"; + + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + + while ($i < $num) + { + $objp = $this->db->fetch_object($result); + + $line = new SupplierProposalLine($this->db); + + $line->rowid = $objp->rowid; // deprecated + $line->id = $objp->rowid; + $line->fk_supplier_proposal = $objp->fk_supplier_proposal; + $line->fk_parent_line = $objp->fk_parent_line; + $line->product_type = $objp->product_type; + $line->label = $objp->custom_label; + $line->desc = $objp->description; // Description ligne + $line->qty = $objp->qty; + $line->tva_tx = $objp->tva_tx; + $line->localtax1_tx = $objp->localtax1_tx; + $line->localtax2_tx = $objp->localtax2_tx; + $line->subprice = $objp->subprice; + $line->fk_remise_except = $objp->fk_remise_except; + $line->remise_percent = $objp->remise_percent; + + $line->info_bits = $objp->info_bits; + $line->total_ht = $objp->total_ht; + $line->total_tva = $objp->total_tva; + $line->total_localtax1 = $objp->total_localtax1; + $line->total_localtax2 = $objp->total_localtax2; + $line->total_ttc = $objp->total_ttc; + $line->fk_fournprice = $objp->fk_fournprice; + $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); + $line->pa_ht = $marginInfos[0]; + $line->marge_tx = $marginInfos[1]; + $line->marque_tx = $marginInfos[2]; + $line->special_code = $objp->special_code; + $line->rang = $objp->rang; + + $line->fk_product = $objp->fk_product; + + $line->ref = $objp->product_ref; // deprecated + $line->product_ref = $objp->product_ref; + $line->libelle = $objp->product_label; // deprecated + $line->product_label = $objp->product_label; + $line->product_desc = $objp->product_desc; // Description produit + $line->fk_product_type = $objp->fk_product_type; + + $line->ref_fourn = $objp->ref_produit_fourn; + + // Multicurrency + $line->fk_multicurrency = $objp->fk_multicurrency; + $line->multicurrency_code = $objp->multicurrency_code; + $line->multicurrency_subprice = $objp->multicurrency_subprice; + $line->multicurrency_total_ht = $objp->multicurrency_total_ht; + $line->multicurrency_total_tva = $objp->multicurrency_total_tva; + $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc; + $line->fk_unit = $objp->fk_unit; + + $this->lines[$i] = $line; + + $i++; + } + $this->db->free($result); + } else { + $this->error = $this->db->error(); + return -1; + } + + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); + + return 1; + } + + $this->error = "Record Not Found"; + return 0; + } else { + $this->error = $this->db->error(); + return -1; + } + } + + /** + * Set status to validated + * + * @param User $user Object user that validate + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >=0 if OK + */ + public function valid($user, $notrigger = 0) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + global $conf, $langs; + + $error = 0; + $now = dol_now(); + + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance))) + { + $this->db->begin(); + + // Numbering module definition + $soc = new Societe($this->db); + $soc->fetch($this->socid); + + // Define new ref + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life + { + $num = $this->getNextNumRef($soc); + } else { + $num = $this->ref; + } + $this->newref = dol_sanitizeFileName($num); + + $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + + dol_syslog(get_class($this)."::valid", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + dol_print_error($this->db); + $error++; + } + + // Trigger calls + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('PROPOSAL_SUPPLIER_VALIDATE', $user); + if ($result < 0) { $error++; } + // End call triggers + } + + if (!$error) + { + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) + { + // Now we rename also files into index + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->supplier_proposal->dir_output.'/'.$oldref; + $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref; + if (!$error && file_exists($dirsource)) + { + dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); + if (@rename($dirsource, $dirdest)) + { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->supplier_proposal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) + { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + + $this->ref = $num; + $this->brouillon = 0; + $this->statut = 1; + $this->user_valid_id = $user->id; + $this->datev = $now; + + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + dol_syslog("You don't have permission to validate supplier proposal", LOG_WARNING); + return -2; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Set delivery date + * + * @param User $user Object user that modify + * @param int $date_livraison Delivery date + * @return int <0 if ko, >0 if ok + */ + public function set_date_livraison($user, $date_livraison) + { + // phpcs:enable + if (!empty($user->rights->supplier_proposal->creer)) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; + $sql .= " SET date_livraison = ".($date_livraison != '' ? "'".$this->db->idate($date_livraison)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id; + + if ($this->db->query($sql)) + { + $this->date_livraison = $date_livraison; + return 1; + } else { + $this->error = $this->db->error(); + dol_syslog(get_class($this)."::set_date_livraison Erreur SQL"); + return -1; + } + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Set an overall discount on the proposal + * + * @param User $user Object user that modify + * @param double $remise Amount discount + * @return int <0 if ko, >0 if ok + */ + public function set_remise_percent($user, $remise) + { + // phpcs:enable + $remise = trim($remise) ?trim($remise) : 0; + + if (!empty($user->rights->supplier_proposal->creer)) + { + $remise = price2num($remise); + + $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET remise_percent = ".$remise; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + + if ($this->db->query($sql)) + { + $this->remise_percent = $remise; + $this->update_price(1); + return 1; + } else { + $this->error = $this->db->error(); + return -1; + } + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Set an absolute overall discount on the proposal + * + * @param User $user Object user that modify + * @param double $remise Amount discount + * @return int <0 if ko, >0 if ok + */ + public function set_remise_absolue($user, $remise) + { + // phpcs:enable + $remise = trim($remise) ?trim($remise) : 0; + + if (!empty($user->rights->supplier_proposal->creer)) + { + $remise = price2num($remise); + + $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; + $sql .= " SET remise_absolue = ".$remise; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + + if ($this->db->query($sql)) + { + $this->remise_absolue = $remise; + $this->update_price(1); + return 1; + } else { + $this->error = $this->db->error(); + return -1; + } + } + } + + + + /** + * Reopen the commercial proposal + * + * @param User $user Object user that close + * @param int $statut Statut + * @param string $note Comment + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + public function reopen($user, $statut, $note = '', $notrigger = 0) + { + global $langs, $conf; + + $this->statut = $statut; + $error = 0; + + $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; + $sql .= " SET fk_statut = ".$this->statut.","; + if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',"; + $sql .= " date_cloture=NULL, fk_user_cloture=NULL"; + $sql .= " WHERE rowid = ".$this->id; + + $this->db->begin(); + + dol_syslog(get_class($this)."::reopen", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } + if (!$error) + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('PROPOSAL_SUPPLIER_REOPEN', $user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + if (!empty($this->errors)) + { + 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; + } + } + + + /** + * Close the askprice + * + * @param User $user Object user that close + * @param int $status Status + * @param string $note Comment + * @return int <0 if KO, >0 if OK + */ + public function cloture($user, $status, $note) + { + global $langs, $conf; + + $this->statut = $status; + $error = 0; + $now = dol_now(); + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; + $sql .= " SET fk_statut = ".$status.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; + $sql .= " WHERE rowid = ".$this->id; + + $resql = $this->db->query($sql); + if ($resql) + { + $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : $this->modelpdf; + $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED'; + + if ($status == 2) + { + $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED'; + $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : $this->modelpdf; + + if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists + { + $result = $this->updateOrCreatePriceFournisseur($user); + } + } + if ($status == 4) + { + $triggerName = 'PROPOSAL_SUPPLIER_CLASSIFY_BILLED'; + } + + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + // Define output language + $outputlangs = $langs; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $outputlangs = new Translate("", $conf); + $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); + $outputlangs->setDefaultLang($newlang); + } + //$ret=$object->fetch($id); // Reload to get new records + $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + + // Call trigger + $result = $this->call_trigger($triggerName, $user); + if ($result < 0) { $error++; } + // End call triggers + + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + + /** + * Add or update supplier price according to result of proposal + * + * @param User $user Object user + * @return int > 0 if OK + */ + public function updateOrCreatePriceFournisseur($user) + { + global $conf; + + dol_syslog(get_class($this)."::updateOrCreatePriceFournisseur", LOG_DEBUG); + foreach ($this->lines as $product) + { + if ($product->subprice <= 0) continue; + $productsupplier = new ProductFournisseur($this->db); + + $multicurrency_tx = 1; + $fk_multicurrency = 0; + + if (empty($this->thirdparty)) $this->fetch_thirdparty(); + + $ref_fourn = $product->ref_fourn; + if (empty($ref_fourn)) $ref_fourn = $product->ref_supplier; + if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code); + $productsupplier->id = $product->fk_product; + + $productsupplier->update_buyprice($product->qty, $product->total_ht, $user, 'HT', $this->thirdparty, '', $ref_fourn, $product->tva_tx, 0, 0, 0, $product->info_bits, '', '', array(), '', $product->multicurrency_total_ht, 'HT', $multicurrency_tx, $product->multicurrency_code, '', '', ''); + } + + return 1; + } + + /** + * Upate ProductFournisseur + * + * @param int $idProductFournPrice id of llx_product_fournisseur_price + * @param Product $product contain informations to update + * @param User $user Object user + * @return int <0 if KO, >0 if OK + */ + public function updatePriceFournisseur($idProductFournPrice, $product, $user) + { + $price = price2num($product->subprice * $product->qty, 'MU'); + $unitPrice = price2num($product->subprice, 'MU'); + + $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_fournisseur_price SET '.(!empty($product->ref_fourn) ? 'ref_fourn = "'.$product->ref_fourn.'", ' : '').' price ='.$price.', unitprice ='.$unitPrice.' WHERE rowid = '.$idProductFournPrice; + + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } + + /** + * Create ProductFournisseur + * + * @param Product $product Object Product + * @param User $user Object user + * @return int <0 if KO, >0 if OK + */ + public function createPriceFournisseur($product, $user) + { + global $conf; + + $price = price2num($product->subprice * $product->qty, 'MU'); + $qty = price2num($product->qty); + $unitPrice = price2num($product->subprice, 'MU'); + + $now = dol_now(); + + $values = array( + "'".$this->db->idate($now)."'", + $product->fk_product, + $this->thirdparty->id, + "'".$product->ref_fourn."'", + $price, + $qty, + $unitPrice, + $product->tva_tx, + $user->id + ); + if (!empty($conf->multicurrency->enabled)) { + if (!empty($product->multicurrency_code)) { include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; - $multicurrency = new MultiCurrency($this->db); //need to fetch because empty fk_multicurrency and rate - $multicurrency->fetch(0, $product->multicurrency_code); - if (!empty($multicurrency->id)) { - $values[] = $multicurrency->id; - $values[] = "'".$product->multicurrency_code."'"; - $values[] = $product->multicurrency_subprice; - $values[] = $product->multicurrency_total_ht; - $values[] = $multicurrency->rate->rate; - } else { - for ($i = 0; $i < 5; $i++) $values[] = 'NULL'; - } - } - } + $multicurrency = new MultiCurrency($this->db); //need to fetch because empty fk_multicurrency and rate + $multicurrency->fetch(0, $product->multicurrency_code); + if (!empty($multicurrency->id)) { + $values[] = $multicurrency->id; + $values[] = "'".$product->multicurrency_code."'"; + $values[] = $product->multicurrency_subprice; + $values[] = $product->multicurrency_total_ht; + $values[] = $multicurrency->rate->rate; + } else { + for ($i = 0; $i < 5; $i++) $values[] = 'NULL'; + } + } + } - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_fournisseur_price '; - $sql .= '(datec, fk_product, fk_soc, ref_fourn, price, quantity, unitprice, tva_tx, fk_user'; - if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx'; - $sql .= ') VALUES ('.implode(',', $values).')'; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_fournisseur_price '; + $sql .= '(datec, fk_product, fk_soc, ref_fourn, price, quantity, unitprice, tva_tx, fk_user'; + if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx'; + $sql .= ') VALUES ('.implode(',', $values).')'; - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set draft status - * - * @param User $user Object user that modify - * @return int <0 if KO, >0 if OK - */ - public function setDraft($user) - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Set draft status + * + * @param User $user Object user that modify + * @return int <0 if KO, >0 if OK + */ + public function setDraft($user) + { + // phpcs:enable + global $conf, $langs; - $error = 0; + $error = 0; - if ($this->statut == self::STATUS_DRAFT) - { - dol_syslog(get_class($this)."::setDraft already draft status", LOG_WARNING); - return 0; - } + if ($this->statut == self::STATUS_DRAFT) + { + dol_syslog(get_class($this)."::setDraft already draft status", LOG_WARNING); + return 0; + } - $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql .= " SET fk_statut = ".self::STATUS_DRAFT; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; + $sql .= " SET fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - if (!$error) { - $this->oldcopy = clone $this; - } + if ($this->db->query($sql)) + { + if (!$error) { + $this->oldcopy = clone $this; + } - if (!$error) { - // Call trigger - $result = $this->call_trigger('PROPOSAL_SUPPLIER_UNVALIDATE', $user); - if ($result < 0) $error++; - } + if (!$error) { + // Call trigger + $result = $this->call_trigger('PROPOSAL_SUPPLIER_UNVALIDATE', $user); + if ($result < 0) $error++; + } - if (!$error) { - $this->statut = self::STATUS_DRAFT; - $this->brouillon = 1; - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - return -1; - } - } + if (!$error) { + $this->statut = self::STATUS_DRAFT; + $this->brouillon = 1; + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of askprice (eventually filtered on user) into an array - * - * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name) - * @param int $draft 0=not draft, 1=draft - * @param int $notcurrentuser 0=all user, 1=not current user - * @param int $socid Id third pary - * @param int $limit For pagination - * @param int $offset For pagination - * @param string $sortfield Sort criteria - * @param string $sortorder Sort order - * @return int -1 if KO, array with result if OK - */ - public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datec', $sortorder = 'DESC') - { - // phpcs:enable - global $conf, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of askprice (eventually filtered on user) into an array + * + * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name) + * @param int $draft 0=not draft, 1=draft + * @param int $notcurrentuser 0=all user, 1=not current user + * @param int $socid Id third pary + * @param int $limit For pagination + * @param int $offset For pagination + * @param string $sortfield Sort criteria + * @param string $sortorder Sort order + * @return int -1 if KO, array with result if OK + */ + public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datec', $sortorder = 'DESC') + { + // phpcs:enable + global $conf, $user; - $ga = array(); + $ga = array(); - $sql = "SELECT s.rowid, s.nom as name, s.client,"; - $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; - $sql .= " p.datep as dp, p.fin_validite as datelimite"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")"; - $sql .= " AND p.fk_soc = s.rowid"; - $sql .= " AND p.fk_statut = c.id"; - if (!$user->rights->societe->client->voir && !$socid) //restriction - { - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - } - if ($socid) $sql .= " AND s.rowid = ".$socid; - if ($draft) $sql .= " AND p.fk_statut = 0"; - if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id; - $sql .= $this->db->order($sortfield, $sortorder); - $sql .= $this->db->plimit($limit, $offset); + $sql = "SELECT s.rowid, s.nom as name, s.client,"; + $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; + $sql .= " p.datep as dp, p.fin_validite as datelimite"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.fk_statut = c.id"; + if (!$user->rights->societe->client->voir && !$socid) //restriction + { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($draft) $sql .= " AND p.fk_statut = 0"; + if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id; + $sql .= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->plimit($limit, $offset); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - if ($num) - { - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + if ($num) + { + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); - if ($shortlist == 1) - { - $ga[$obj->supplier_proposalid] = $obj->ref; - } elseif ($shortlist == 2) - { - $ga[$obj->supplier_proposalid] = $obj->ref.' ('.$obj->name.')'; - } else { - $ga[$i]['id'] = $obj->supplier_proposalid; - $ga[$i]['ref'] = $obj->ref; - $ga[$i]['name'] = $obj->name; - } + if ($shortlist == 1) + { + $ga[$obj->supplier_proposalid] = $obj->ref; + } elseif ($shortlist == 2) + { + $ga[$obj->supplier_proposalid] = $obj->ref.' ('.$obj->name.')'; + } else { + $ga[$i]['id'] = $obj->supplier_proposalid; + $ga[$i]['ref'] = $obj->ref; + $ga[$i]['name'] = $obj->name; + } - $i++; - } - } - return $ga; - } else { - dol_print_error($this->db); - return -1; - } - } + $i++; + } + } + return $ga; + } else { + dol_print_error($this->db); + return -1; + } + } - /** - * Delete askprice - * - * @param User $user Object user that delete - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int 1 if ok, otherwise if error - */ - public function delete($user, $notrigger = 0) - { - global $conf, $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Delete askprice + * + * @param User $user Object user that delete + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int 1 if ok, otherwise if error + */ + public function delete($user, $notrigger = 0) + { + global $conf, $langs; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error = 0; + $error = 0; - $this->db->begin(); + $this->db->begin(); - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('PROPOSAL_SUPPLIER_DELETE', $user); - if ($result < 0) { $error++; } - // End call triggers - } + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('PROPOSAL_SUPPLIER_DELETE', $user); + if ($result < 0) { $error++; } + // End call triggers + } - if (!$error) - { - $main = MAIN_DB_PREFIX.'supplier_proposaldet'; - $ef = $main."_extrafields"; - $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_supplier_proposal = ".$this->id.")"; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".$this->id; - if ($this->db->query($sql)) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE rowid = ".$this->id; - if ($this->db->query($sqlef) && $this->db->query($sql)) - { - // Delete linked object - $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if (!$error) + { + $main = MAIN_DB_PREFIX.'supplier_proposaldet'; + $ef = $main."_extrafields"; + $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_supplier_proposal = ".$this->id.")"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".$this->id; + if ($this->db->query($sql)) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE rowid = ".$this->id; + if ($this->db->query($sqlef) && $this->db->query($sql)) + { + // Delete linked object + $res = $this->deleteObjectLinked(); + if ($res < 0) $error++; - if (!$error) - { - // We remove directory - $ref = dol_sanitizeFileName($this->ref); - if ($conf->supplier_proposal->dir_output && !empty($this->ref)) - { - $dir = $conf->supplier_proposal->dir_output."/".$ref; - $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) - { - dol_delete_preview($this); + if (!$error) + { + // We remove directory + $ref = dol_sanitizeFileName($this->ref); + if ($conf->supplier_proposal->dir_output && !empty($this->ref)) + { + $dir = $conf->supplier_proposal->dir_output."/".$ref; + $file = $dir."/".$ref.".pdf"; + if (file_exists($file)) + { + dol_delete_preview($this); - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { - $this->error = 'ErrorFailToDeleteFile'; - $this->errors = array('ErrorFailToDeleteFile'); - $this->db->rollback(); - return 0; - } - } - if (file_exists($dir)) - { - $res = @dol_delete_dir_recursive($dir); - if (!$res) - { - $this->error = 'ErrorFailToDeleteDir'; - $this->errors = array('ErrorFailToDeleteDir'); - $this->db->rollback(); - return 0; - } - } - } - } + if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers + { + $this->error = 'ErrorFailToDeleteFile'; + $this->errors = array('ErrorFailToDeleteFile'); + $this->db->rollback(); + return 0; + } + } + if (file_exists($dir)) + { + $res = @dol_delete_dir_recursive($dir); + if (!$res) + { + $this->error = 'ErrorFailToDeleteDir'; + $this->errors = array('ErrorFailToDeleteDir'); + $this->db->rollback(); + return 0; + } + } + } + } - // Removed extrafields - if (!$error) - { - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $error++; - $errorflag = -4; - dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); - } - } + // Removed extrafields + if (!$error) + { + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $error++; + $errorflag = -4; + dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); + } + } - if (!$error) - { - dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return 0; - } - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -3; - } - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } else { - $this->db->rollback(); - return -1; - } - } + if (!$error) + { + dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return 0; + } + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -3; + } + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Object SupplierProposal Information - * - * @param int $id Proposal id - * @return void - */ - public function info($id) - { - $sql = "SELECT c.rowid, "; - $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; - $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; - $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c"; - $sql .= " WHERE c.rowid = ".$id; + /** + * Object SupplierProposal Information + * + * @param int $id Proposal id + * @return void + */ + public function info($id) + { + $sql = "SELECT c.rowid, "; + $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; + $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c"; + $sql .= " WHERE c.rowid = ".$id; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; + $this->id = $obj->rowid; - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_validation = $this->db->jdate($obj->datev); - $this->date_cloture = $this->db->jdate($obj->dateo); + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_validation = $this->db->jdate($obj->datev); + $this->date_cloture = $this->db->jdate($obj->dateo); - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; - 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; + } - if ($obj->fk_user_cloture) - { - $cluser = new User($this->db); - $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; - } - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - /** - * Return label of status of proposal (draft, validated, ...) - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * @return string Label - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut((isset($this->statut) ? $this->statut : $this->status), $mode); - } + /** + * Return label of status of proposal (draft, validated, ...) + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut((isset($this->statut) ? $this->statut : $this->status), $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return label of a status (draft, validated, ...) - * - * @param int $status Id status + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return label of a status (draft, validated, ...) + * + * @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 - * @return string Label - */ - public function LibStatut($status, $mode = 1) - { - // phpcs:enable + * @return string Label + */ + public function LibStatut($status, $mode = 1) + { + // phpcs:enable - // Init/load array of translation of status - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { - global $langs; - $langs->load("supplier_proposal"); - $this->labelStatus[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraft"); - $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans("SupplierProposalStatusValidated"); - $this->labelStatus[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSigned"); - $this->labelStatus[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSigned"); - $this->labelStatus[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosed"); - $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraftShort"); - $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans("Opened"); - $this->labelStatusShort[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSignedShort"); - $this->labelStatusShort[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSignedShort"); - $this->labelStatusShort[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosedShort"); - } + // Init/load array of translation of status + if (empty($this->labelStatus) || empty($this->labelStatusShort)) + { + global $langs; + $langs->load("supplier_proposal"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraft"); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans("SupplierProposalStatusValidated"); + $this->labelStatus[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSigned"); + $this->labelStatus[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSigned"); + $this->labelStatus[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosed"); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraftShort"); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans("Opened"); + $this->labelStatusShort[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSignedShort"); + $this->labelStatusShort[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSignedShort"); + $this->labelStatusShort[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosedShort"); + } - $statusnew = ''; - if ($status == self::STATUS_DRAFT) $statusnew = 'status0'; - elseif ($status == self::STATUS_VALIDATED) $statusnew = 'status1'; - elseif ($status == self::STATUS_SIGNED) $statusnew = 'status4'; - elseif ($status == self::STATUS_NOTSIGNED) $statusnew = 'status9'; - elseif ($status == self::STATUS_CLOSE) $statusnew = 'status6'; + $statusnew = ''; + if ($status == self::STATUS_DRAFT) $statusnew = 'status0'; + elseif ($status == self::STATUS_VALIDATED) $statusnew = 'status1'; + elseif ($status == self::STATUS_SIGNED) $statusnew = 'status4'; + elseif ($status == self::STATUS_NOTSIGNED) $statusnew = 'status9'; + elseif ($status == self::STATUS_CLOSE) $statusnew = 'status6'; - return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode); - } + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Object user - * @param int $mode "opened" for askprice to close, "signed" for proposal to invoice - * @return int <0 if KO, >0 if OK - */ - public function load_board($user, $mode) - { - // phpcs:enable - global $conf, $user, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Object user + * @param int $mode "opened" for askprice to close, "signed" for proposal to invoice + * @return int <0 if KO, >0 if OK + */ + public function load_board($user, $mode) + { + // phpcs:enable + global $conf, $user, $langs; - $now = dol_now(); + $now = dol_now(); - $this->nbtodo = $this->nbtodolate = 0; - $clause = " WHERE"; + $this->nbtodo = $this->nbtodolate = 0; + $clause = " WHERE"; - $sql = "SELECT p.rowid, p.ref, p.datec as datec"; - $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; - if (!$user->rights->societe->client->voir && !$user->socid) - { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; - $sql .= " WHERE sc.fk_user = ".$user->id; - $clause = " AND"; - } - $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")"; - if ($mode == 'opened') $sql .= " AND p.fk_statut = 1"; - if ($mode == 'signed') $sql .= " AND p.fk_statut = 2"; - if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid; + $sql = "SELECT p.rowid, p.ref, p.datec as datec"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; + if (!$user->rights->societe->client->voir && !$user->socid) + { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; + $sql .= " WHERE sc.fk_user = ".$user->id; + $clause = " AND"; + } + $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")"; + if ($mode == 'opened') $sql .= " AND p.fk_statut = 1"; + if ($mode == 'signed') $sql .= " AND p.fk_statut = 2"; + if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid; - $resql = $this->db->query($sql); - if ($resql) - { + $resql = $this->db->query($sql); + if ($resql) + { $label = $labelShort = ''; $status = ''; - if ($mode == 'opened') { - $delay_warning = $conf->supplier_proposal->cloture->warning_delay; - $status = self::STATUS_VALIDATED; - $label = $langs->trans("SupplierProposalsToClose"); - $labelShort = $langs->trans("ToAcceptRefuse"); - } - if ($mode == 'signed') { - $delay_warning = $conf->supplier_proposal->facturation->warning_delay; - $status = self::STATUS_SIGNED; - $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered + if ($mode == 'opened') { + $delay_warning = $conf->supplier_proposal->cloture->warning_delay; + $status = self::STATUS_VALIDATED; + $label = $langs->trans("SupplierProposalsToClose"); + $labelShort = $langs->trans("ToAcceptRefuse"); + } + if ($mode == 'signed') { + $delay_warning = $conf->supplier_proposal->facturation->warning_delay; + $status = self::STATUS_SIGNED; + $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered $labelShort = $langs->trans("ToClose"); - } + } - $response = new WorkboardResponse(); - $response->warning_delay = $delay_warning / 60 / 60 / 24; - $response->label = $label; - $response->labelShort = $labelShort; - $response->url = DOL_URL_ROOT.'/supplier_proposal/list.php?search_status='.$status; - $response->img = img_object('', "propal"); + $response = new WorkboardResponse(); + $response->warning_delay = $delay_warning / 60 / 60 / 24; + $response->label = $label; + $response->labelShort = $labelShort; + $response->url = DOL_URL_ROOT.'/supplier_proposal/list.php?search_status='.$status; + $response->img = img_object('', "propal"); - // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { - $response->nbtodo++; - if ($mode == 'opened') - { - $datelimit = $this->db->jdate($obj->datefin); - if ($datelimit < ($now - $delay_warning)) - { - $response->nbtodolate++; - } - } - // TODO Definir regle des propales a facturer en retard - // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++; - } - return $response; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + // This assignment in condition is not a bug. It allows walking the results. + while ($obj = $this->db->fetch_object($resql)) + { + $response->nbtodo++; + if ($mode == 'opened') + { + $datelimit = $this->db->jdate($obj->datefin); + if ($datelimit < ($now - $delay_warning)) + { + $response->nbtodolate++; + } + } + // TODO Definir regle des propales a facturer en retard + // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++; + } + return $response; + } else { + $this->error = $this->db->lasterror(); + 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() - { - global $user, $langs, $conf; + /** + * 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; - // Load array of products prodids - $num_prods = 0; - $prodids = array(); - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."product"; - $sql .= " WHERE entity IN (".getEntity('product').")"; - $sql .= $this->db->plimit(100); + // Load array of products prodids + $num_prods = 0; + $prodids = array(); + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; + $sql .= $this->db->plimit(100); - $resql = $this->db->query($sql); - if ($resql) - { - $num_prods = $this->db->num_rows($resql); - $i = 0; - while ($i < $num_prods) - { - $i++; - $row = $this->db->fetch_row($resql); - $prodids[$i] = $row[0]; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + $num_prods = $this->db->num_rows($resql); + $i = 0; + while ($i < $num_prods) + { + $i++; + $row = $this->db->fetch_row($resql); + $prodids[$i] = $row[0]; + } + } - // Initialise parametres - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->specimen = 1; - $this->socid = 1; - $this->date = time(); - $this->cond_reglement_id = 1; - $this->cond_reglement_code = 'RECEP'; - $this->mode_reglement_id = 7; - $this->mode_reglement_code = 'CHQ'; - $this->note_public = 'This is a comment (public)'; - $this->note_private = 'This is a comment (private)'; - // Lines - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) - { - $line = new SupplierProposalLine($this->db); - $line->desc = $langs->trans("Description")." ".$xnbp; - $line->qty = 1; - $line->subprice = 100; - $line->tva_tx = 19.6; - $line->localtax1_tx = 0; - $line->localtax2_tx = 0; - if ($xnbp == 2) - { - $line->total_ht = 50; - $line->total_ttc = 59.8; - $line->total_tva = 9.8; - $line->remise_percent = 50; - } else { - $line->total_ht = 100; - $line->total_ttc = 119.6; - $line->total_tva = 19.6; - $line->remise_percent = 00; - } + // Initialise parametres + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->specimen = 1; + $this->socid = 1; + $this->date = time(); + $this->cond_reglement_id = 1; + $this->cond_reglement_code = 'RECEP'; + $this->mode_reglement_id = 7; + $this->mode_reglement_code = 'CHQ'; + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; + // Lines + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) + { + $line = new SupplierProposalLine($this->db); + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 100; + $line->tva_tx = 19.6; + $line->localtax1_tx = 0; + $line->localtax2_tx = 0; + if ($xnbp == 2) + { + $line->total_ht = 50; + $line->total_ttc = 59.8; + $line->total_tva = 9.8; + $line->remise_percent = 50; + } else { + $line->total_ht = 100; + $line->total_ttc = 119.6; + $line->total_tva = 19.6; + $line->remise_percent = 00; + } - if ($num_prods > 0) - { - $prodid = mt_rand(1, $num_prods); - $line->fk_product = $prodids[$prodid]; - } + if ($num_prods > 0) + { + $prodid = mt_rand(1, $num_prods); + $line->fk_product = $prodids[$prodid]; + } - $this->lines[$xnbp] = $line; + $this->lines[$xnbp] = $line; - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; - $xnbp++; - } - } + $xnbp++; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicator this->nb of global stats widget - * - * @return int <0 if ko, >0 if ok - */ - public function load_state_board() - { - // phpcs:enable - global $conf, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicator this->nb of global stats widget + * + * @return int <0 if ko, >0 if ok + */ + public function load_state_board() + { + // phpcs:enable + global $conf, $user; - $this->nb = array(); - $clause = "WHERE"; + $this->nb = array(); + $clause = "WHERE"; - $sql = "SELECT count(p.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; - $sql .= " WHERE sc.fk_user = ".$user->id; - $clause = "AND"; - } - $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")"; + $sql = "SELECT count(p.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->socid) + { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + $sql .= " WHERE sc.fk_user = ".$user->id; + $clause = "AND"; + } + $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")"; - $resql = $this->db->query($sql); - if ($resql) - { - // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { - $this->nb["supplier_proposals"] = $obj->nb; - } - $this->db->free($resql); - return 1; - } else { - dol_print_error($this->db); - $this->error = $this->db->lasterror(); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + // This assignment in condition is not a bug. It allows walking the results. + while ($obj = $this->db->fetch_object($resql)) + { + $this->nb["supplier_proposals"] = $obj->nb; + } + $this->db->free($resql); + return 1; + } else { + dol_print_error($this->db); + $this->error = $this->db->lasterror(); + return -1; + } + } - /** - * Returns the reference to the following non used Proposal used depending on the active numbering module - * defined into SUPPLIER_PROPOSAL_ADDON - * - * @param Societe $soc Object thirdparty - * @return string Reference libre pour la propale - */ - public function getNextNumRef($soc) - { - global $conf, $db, $langs; - $langs->load("supplier_proposal"); + /** + * Returns the reference to the following non used Proposal used depending on the active numbering module + * defined into SUPPLIER_PROPOSAL_ADDON + * + * @param Societe $soc Object thirdparty + * @return string Reference libre pour la propale + */ + public function getNextNumRef($soc) + { + global $conf, $db, $langs; + $langs->load("supplier_proposal"); - if (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON)) - { - $mybool = false; + if (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON)) + { + $mybool = false; - $file = $conf->global->SUPPLIER_PROPOSAL_ADDON.".php"; - $classname = $conf->global->SUPPLIER_PROPOSAL_ADDON; + $file = $conf->global->SUPPLIER_PROPOSAL_ADDON.".php"; + $classname = $conf->global->SUPPLIER_PROPOSAL_ADDON; - // Include file with class - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_proposal/"); + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/supplier_proposal/"); - // Load file with numbering class (if found) - $mybool |= @include_once $dir.$file; - } + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } - if (!$mybool) - { - dol_print_error('', "Failed to include file ".$file); - return ''; - } + if (!$mybool) + { + dol_print_error('', "Failed to include file ".$file); + return ''; + } - $obj = new $classname(); - $numref = ""; - $numref = $obj->getNextValue($soc, $this); + $obj = new $classname(); + $numref = ""; + $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { - return $numref; - } else { - $this->error = $obj->error; - return ""; - } - } else { - $langs->load("errors"); - print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("SupplierProposal")); - return ""; - } - } + if ($numref != "") + { + return $numref; + } else { + $this->error = $obj->error; + return ""; + } + } else { + $langs->load("errors"); + print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("SupplierProposal")); + return ""; + } + } - /** - * 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 int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @param int $addlinktonotes Add link to show notes - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0) - { - global $langs, $conf, $user; + /** + * 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 int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param int $addlinktonotes Add link to show notes + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0) + { + global $langs, $conf, $user; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - $url = ''; - $result = ''; + $url = ''; + $result = ''; - $label = ''.$langs->trans("SupplierProposal").''; - if (!empty($this->ref)) $label .= '
'.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->ref_fourn)) $label .= '
'.$langs->trans('RefSupplier').': '.$this->ref_fourn; - if (!empty($this->total_ht)) $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_tva)) $label .= '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if (isset($this->status)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); - } + $label = ''.$langs->trans("SupplierProposal").''; + if (!empty($this->ref)) $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_fourn)) $label .= '
'.$langs->trans('RefSupplier').': '.$this->ref_fourn; + if (!empty($this->total_ht)) $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_tva)) $label .= '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_ttc)) $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if (isset($this->status)) { + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); + } - if ($option == '') { - $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params; - } - if ($option == 'document') { - $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params; - } + if ($option == '') { + $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params; + } + if ($option == 'document') { + $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params; + } - 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) && $user->rights->propal->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowSupplierProposal"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; - } + $linkclose = ''; + if (empty($notooltip) && $user->rights->propal->lire) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowSupplierProposal"); + $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, ($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, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= $this->ref; + $result .= $linkend; - if ($addlinktonotes) - { - $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { - $notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); - $result .= ' '; - $result .= ''; - $result .= img_picto('', 'note'); - $result .= ''; - //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); - //$result.=''; - $result .= ''; - } - } + if ($addlinktonotes) + { + $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); + if ($txttoshow) + { + $notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); + $result .= ' '; + $result .= ''; + $result .= img_picto('', 'note'); + $result .= ''; + //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); + //$result.=''; + $result .= ''; + } + } - return $result; - } + return $result; + } - /** - * Retrieve an array of supplier proposal lines - * - * @return int >0 if OK, <0 if KO - */ - public function getLinesArray() - { - // For other object, here we call fetch_lines. But fetch_lines does not exists on supplier proposal + /** + * Retrieve an array of supplier proposal lines + * + * @return int >0 if OK, <0 if KO + */ + public function getLinesArray() + { + // For other object, here we call fetch_lines. But fetch_lines does not exists on supplier proposal - $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; - $sql .= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; - $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,'; - $sql .= ' pt.product_type, pt.rang, pt.fk_parent_line,'; - $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,'; - $sql .= ' p.description as product_desc, pt.ref_fourn as ref_supplier,'; - $sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; - $sql .= ' WHERE pt.fk_supplier_proposal = '.$this->id; - $sql .= ' ORDER BY pt.rang ASC, pt.rowid'; + $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; + $sql .= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; + $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,'; + $sql .= ' pt.product_type, pt.rang, pt.fk_parent_line,'; + $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,'; + $sql .= ' p.description as product_desc, pt.ref_fourn as ref_supplier,'; + $sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; + $sql .= ' WHERE pt.fk_supplier_proposal = '.$this->id; + $sql .= ' ORDER BY pt.rang ASC, pt.rowid'; - dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; + dol_syslog(get_class($this).'::getLinesArray', 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); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $this->lines[$i] = new SupplierProposalLine($this->db); - $this->lines[$i]->id = $obj->rowid; // for backward compatibility - $this->lines[$i]->rowid = $obj->rowid; - $this->lines[$i]->label = $obj->custom_label; - $this->lines[$i]->description = $obj->description; - $this->lines[$i]->fk_product = $obj->fk_product; - $this->lines[$i]->ref = $obj->ref; - $this->lines[$i]->product_label = $obj->product_label; - $this->lines[$i]->product_desc = $obj->product_desc; - $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated - $this->lines[$i]->product_type = $obj->product_type; - $this->lines[$i]->qty = $obj->qty; - $this->lines[$i]->subprice = $obj->subprice; - $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; - $this->lines[$i]->remise_percent = $obj->remise_percent; - $this->lines[$i]->tva_tx = $obj->tva_tx; - $this->lines[$i]->info_bits = $obj->info_bits; - $this->lines[$i]->total_ht = $obj->total_ht; - $this->lines[$i]->total_tva = $obj->total_tva; - $this->lines[$i]->total_ttc = $obj->total_ttc; - $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; - $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht); - $this->lines[$i]->pa_ht = $marginInfos[0]; - $this->lines[$i]->marge_tx = $marginInfos[1]; - $this->lines[$i]->marque_tx = $marginInfos[2]; - $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; - $this->lines[$i]->special_code = $obj->special_code; - $this->lines[$i]->rang = $obj->rang; + $this->lines[$i] = new SupplierProposalLine($this->db); + $this->lines[$i]->id = $obj->rowid; // for backward compatibility + $this->lines[$i]->rowid = $obj->rowid; + $this->lines[$i]->label = $obj->custom_label; + $this->lines[$i]->description = $obj->description; + $this->lines[$i]->fk_product = $obj->fk_product; + $this->lines[$i]->ref = $obj->ref; + $this->lines[$i]->product_label = $obj->product_label; + $this->lines[$i]->product_desc = $obj->product_desc; + $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated + $this->lines[$i]->product_type = $obj->product_type; + $this->lines[$i]->qty = $obj->qty; + $this->lines[$i]->subprice = $obj->subprice; + $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; + $this->lines[$i]->remise_percent = $obj->remise_percent; + $this->lines[$i]->tva_tx = $obj->tva_tx; + $this->lines[$i]->info_bits = $obj->info_bits; + $this->lines[$i]->total_ht = $obj->total_ht; + $this->lines[$i]->total_tva = $obj->total_tva; + $this->lines[$i]->total_ttc = $obj->total_ttc; + $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; + $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht); + $this->lines[$i]->pa_ht = $marginInfos[0]; + $this->lines[$i]->marge_tx = $marginInfos[1]; + $this->lines[$i]->marque_tx = $marginInfos[2]; + $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; + $this->lines[$i]->special_code = $obj->special_code; + $this->lines[$i]->rang = $obj->rang; - $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated - $this->lines[$i]->ref_supplier = $obj->ref_supplier; + $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated + $this->lines[$i]->ref_supplier = $obj->ref_supplier; - // Multicurrency - $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency; - $this->lines[$i]->multicurrency_code = $obj->multicurrency_code; - $this->lines[$i]->multicurrency_subprice = $obj->multicurrency_subprice; - $this->lines[$i]->multicurrency_total_ht = $obj->multicurrency_total_ht; - $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva; - $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $this->lines[$i]->fk_unit = $obj->fk_unit; + // Multicurrency + $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency; + $this->lines[$i]->multicurrency_code = $obj->multicurrency_code; + $this->lines[$i]->multicurrency_subprice = $obj->multicurrency_subprice; + $this->lines[$i]->multicurrency_total_ht = $obj->multicurrency_total_ht; + $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva; + $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc; + $this->lines[$i]->fk_unit = $obj->fk_unit; - $i++; - } - $this->db->free($resql); + $i++; + } + $this->db->free($resql); - return 1; - } else { - $this->error = $this->db->error(); - return -1; - } - } + return 1; + } else { + $this->error = $this->db->error(); + return -1; + } + } - /** - * Create a document onto disk according to template module. - * - * @param string $modele Force model to use ('' to not force) - * @param Translate $outputlangs Object langs to use for output - * @param int $hidedetails Hide details of lines - * @param int $hidedesc Hide description - * @param int $hideref Hide ref - * @param null|array $moreparams Array to provide more information - * @return int 0 if KO, 1 if OK - */ - public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) - { - global $conf, $langs; + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force model to use ('' to not force) + * @param Translate $outputlangs Object langs to use for output + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; - $langs->load("supplier_proposal"); + $langs->load("supplier_proposal"); $outputlangs->load("products"); - if (!dol_strlen($modele)) { - $modele = 'aurore'; + if (!dol_strlen($modele)) { + $modele = 'aurore'; - if ($this->modelpdf) { - $modele = $this->modelpdf; - } elseif (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON_PDF)) { - $modele = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF; - } - } + if ($this->modelpdf) { + $modele = $this->modelpdf; + } elseif (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON_PDF)) { + $modele = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF; + } + } - $modelpath = "core/modules/supplier_proposal/doc/"; + $modelpath = "core/modules/supplier_proposal/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - } + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } - /** - * Function used to replace a thirdparty id with another one. - * - * @param DoliDB $db Database handler - * @param int $origin_id Old thirdparty id - * @param int $dest_id New thirdparty id - * @return bool - */ - public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) - { - $tables = array( - 'supplier_proposal' - ); + /** + * Function used to replace a thirdparty id with another one. + * + * @param DoliDB $db Database handler + * @param int $origin_id Old thirdparty id + * @param int $dest_id New thirdparty id + * @return bool + */ + public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) + { + $tables = array( + 'supplier_proposal' + ); - return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); - } + return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); + } } diff --git a/htdocs/takepos/invoice.php b/htdocs/takepos/invoice.php index aaffdd7e01a..2f45d24c401 100644 --- a/htdocs/takepos/invoice.php +++ b/htdocs/takepos/invoice.php @@ -369,38 +369,38 @@ if ($action == "freezone") { $tva_tx = get_default_tva($mysoc, $customer); } - // Local Taxes - $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr); - $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr); + // Local Taxes + $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr); + $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr); - $invoice->addline($desc, $number, 1, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', 0, 0, 0, '', 'TTC', $number, 0, -1, 0, '', 0, 0, null, '', '', 0, 100, '', null, 0); - $invoice->fetch($placeid); + $invoice->addline($desc, $number, 1, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', 0, 0, 0, '', 'TTC', $number, 0, -1, 0, '', 0, 0, null, '', '', 0, 100, '', null, 0); + $invoice->fetch($placeid); } if ($action == "addnote") { - foreach ($invoice->lines as $line) - { - if ($line->id == $number) + foreach ($invoice->lines as $line) + { + if ($line->id == $number) { $line->array_options['order_notes'] = $desc; $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); - } - } - $invoice->fetch($placeid); + } + } + $invoice->fetch($placeid); } if ($action == "deleteline") { - if ($idline > 0 and $placeid > 0) { // If invoice exists and line selected. To avoid errors if deleted from another device or no line selected. - $invoice->deleteline($idline); - $invoice->fetch($placeid); - } elseif ($placeid > 0) { // If invoice exists but no line selected, proceed to delete last line. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facturedet where fk_facture='".$placeid."' order by rowid DESC"; - $resql = $db->query($sql); - $row = $db->fetch_array($resql); - $deletelineid = $row[0]; - $invoice->deleteline($deletelineid); - $invoice->fetch($placeid); - } + if ($idline > 0 and $placeid > 0) { // If invoice exists and line selected. To avoid errors if deleted from another device or no line selected. + $invoice->deleteline($idline); + $invoice->fetch($placeid); + } elseif ($placeid > 0) { // If invoice exists but no line selected, proceed to delete last line. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facturedet where fk_facture='".$placeid."' order by rowid DESC"; + $resql = $db->query($sql); + $row = $db->fetch_array($resql); + $deletelineid = $row[0]; + $invoice->deleteline($deletelineid); + $invoice->fetch($placeid); + } if (count($invoice->lines) == 0) $invoice->delete($user); } @@ -830,7 +830,7 @@ $( document ).ready(function() { $s .= '
'.$langs->trans("SubscriptionNotReceived"); if ($adh->statut > 0) $s .= " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated } - if (empty($adh->statut)) { $s .= ""; } + if (empty($adh->statut)) { $s .= ""; } } else { $s .= '
'.$langs->trans("ThirdpartyNotLinkedToMember"); } @@ -1011,47 +1011,47 @@ if ($placeid > 0) $htmlsupplements[$line->fk_parent_line] .= ''."\n"; continue; } - $htmlforlines = ''; + $htmlforlines = ''; - $htmlforlines .= 'id.'">'; - $htmlforlines .= ''; + $htmlforlines .= 'id.'">'; + $htmlforlines .= ''; if ($_SESSION["basiclayout"] == 1) $htmlforlines .= ''.$line->qty." x "; - if (isset($line->product_type)) - { - if (empty($line->product_type)) $htmlforlines .= img_object('', 'product').' '; - else $htmlforlines .= img_object('', 'service').' '; - } - if (empty($conf->global->TAKEPOS_SHOW_N_FIRST_LINES)) { - $tooltiptext = ''; - if ($line->product_ref) { - $tooltiptext .= ''.$langs->trans("Ref").' : '.$line->product_ref.'
'; - $tooltiptext .= ''.$langs->trans("Label").' : '.$line->product_label.'
'; - if ($line->product_label != $line->desc) { - if ($line->desc) $tooltiptext .= '
'; - $tooltiptext .= $line->desc; - } - } - $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext); - } else { - if ($line->product_label) $htmlforlines .= $line->product_label; - if ($line->product_label != $line->desc) - { - if ($line->product_label && $line->desc) $htmlforlines .= '
'; - $firstline = dolGetFirstLineOfText($line->desc, $conf->global->TAKEPOS_SHOW_N_FIRST_LINES); - if ($firstline != $line->desc) - { - $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); - } else { - $htmlforlines .= $line->desc; - } - } - } - if (!empty($line->array_options['options_order_notes'])) $htmlforlines .= "
(".$line->array_options['options_order_notes'].")"; - if ($_SESSION["basiclayout"] == 1) $htmlforlines .= '  '; + if (isset($line->product_type)) + { + if (empty($line->product_type)) $htmlforlines .= img_object('', 'product').' '; + else $htmlforlines .= img_object('', 'service').' '; + } + if (empty($conf->global->TAKEPOS_SHOW_N_FIRST_LINES)) { + $tooltiptext = ''; + if ($line->product_ref) { + $tooltiptext .= ''.$langs->trans("Ref").' : '.$line->product_ref.'
'; + $tooltiptext .= ''.$langs->trans("Label").' : '.$line->product_label.'
'; + if ($line->product_label != $line->desc) { + if ($line->desc) $tooltiptext .= '
'; + $tooltiptext .= $line->desc; + } + } + $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext); + } else { + if ($line->product_label) $htmlforlines .= $line->product_label; + if ($line->product_label != $line->desc) + { + if ($line->product_label && $line->desc) $htmlforlines .= '
'; + $firstline = dolGetFirstLineOfText($line->desc, $conf->global->TAKEPOS_SHOW_N_FIRST_LINES); + if ($firstline != $line->desc) + { + $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); + } else { + $htmlforlines .= $line->desc; + } + } + } + if (!empty($line->array_options['options_order_notes'])) $htmlforlines .= "
(".$line->array_options['options_order_notes'].")"; + if ($_SESSION["basiclayout"] == 1) $htmlforlines .= '  '; if ($_SESSION["basiclayout"] != 1) { $moreinfo = ''; diff --git a/htdocs/ticket/card.php b/htdocs/ticket/card.php index f521076e640..6c7a1278c99 100644 --- a/htdocs/ticket/card.php +++ b/htdocs/ticket/card.php @@ -138,7 +138,7 @@ if (empty($reshook)) { if ($cancel) { if (!empty($backtopage)) { - header("Location: " . $backtopage); + header("Location: ".$backtopage); exit; } @@ -254,10 +254,10 @@ if (empty($reshook)) { if (!empty($backtopage)) { $url = $backtopage; } else { - $url = 'card.php?track_id=' . $object->track_id; + $url = 'card.php?track_id='.$object->track_id; } - header("Location: " . $url); + header("Location: ".$url); exit; } else { $db->rollback(); @@ -325,7 +325,7 @@ if (empty($reshook)) { if ($object->markAsRead($user) > 0) { setEventMessages($langs->trans('TicketMarkedAsRead'), null, 'mesgs'); - header("Location: card.php?track_id=" . $object->track_id . "&action=view"); + header("Location: card.php?track_id=".$object->track_id."&action=view"); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -376,7 +376,7 @@ if (empty($reshook)) { setEventMessages($langs->trans('TicketAssigned'), null, 'mesgs'); - header("Location: card.php?track_id=" . $object->track_id . "&action=view"); + header("Location: card.php?track_id=".$object->track_id."&action=view"); exit; } else { array_push($object->errors, $object->error); @@ -392,10 +392,10 @@ if (empty($reshook)) { if (!empty($backtopage)) { $url = $backtopage; } else { - $url = 'card.php?action=view&track_id=' . $object->track_id; + $url = 'card.php?action=view&track_id='.$object->track_id; } - header("Location: " . $url); + header("Location: ".$url); exit; } else { setEventMessages($object->error, null, 'errors'); @@ -409,8 +409,8 @@ if (empty($reshook)) { if ($object->close($user)) { setEventMessages($langs->trans('TicketMarkedAsClosed'), null, 'mesgs'); - $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha'); - header("Location: " . $url); + $url = 'card.php?action=view&track_id='.GETPOST('track_id', 'alpha'); + header("Location: ".$url); } else { $action = ''; setEventMessages($object->error, $object->errors, 'errors'); @@ -425,10 +425,10 @@ if (empty($reshook)) { // Log action in ticket logs table $log_action = $langs->trans('TicketLogClosedBy', $_SESSION['email_customer']); - setEventMessages('
' . $langs->trans('TicketMarkedAsClosed') . '
', null, 'mesgs'); + setEventMessages('
'.$langs->trans('TicketMarkedAsClosed').'
', null, 'mesgs'); - $url = 'card.php?action=view_ticket&track_id=' . GETPOST('track_id', 'alpha'); - header("Location: " . $url); + $url = 'card.php?action=view_ticket&track_id='.GETPOST('track_id', 'alpha'); + header("Location: ".$url); } else { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; @@ -438,12 +438,12 @@ if (empty($reshook)) { if ($action == 'confirm_delete_ticket' && GETPOST('confirm', 'alpha') == "yes" && $user->rights->ticket->delete) { if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) { if ($object->delete($user) > 0) { - setEventMessages('
' . $langs->trans('TicketDeletedSuccess') . '
', null, 'mesgs'); - Header("Location: " . DOL_URL_ROOT . "/ticket/list.php"); + setEventMessages('
'.$langs->trans('TicketDeletedSuccess').'
', null, 'mesgs'); + Header("Location: ".DOL_URL_ROOT."/ticket/list.php"); exit; } else { $langs->load("errors"); - $mesg = '
' . $langs->trans($object->error) . '
'; + $mesg = '
'.$langs->trans($object->error).'
'; $action = ''; } } @@ -453,8 +453,8 @@ if (empty($reshook)) { if ($action == 'set_thirdparty' && $user->rights->societe->creer) { if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) { $result = $object->setCustomer(GETPOST('editcustomer', 'int')); - $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha'); - header("Location: " . $url); + $url = 'card.php?action=view&track_id='.GETPOST('track_id', 'alpha'); + header("Location: ".$url); exit(); } } @@ -463,8 +463,8 @@ if (empty($reshook)) { if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) { $result = $object->setProgression(GETPOST('progress', 'alpha')); - $url = 'card.php?action=view&track_id=' . $object->track_id; - header("Location: " . $url); + $url = 'card.php?action=view&track_id='.$object->track_id; + header("Location: ".$url); exit(); } } @@ -476,12 +476,12 @@ if (empty($reshook)) { } if ($action == 'setsubject' && empty($object->subject)) { - $mesg .= ($mesg ? '
' : '') . $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject")); + $mesg .= ($mesg ? '
' : '').$langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject")); } if (!$mesg) { if ($object->update($user) >= 0) { - header("Location: " . $_SERVER['PHP_SELF'] . "?track_id=" . $object->track_id); + header("Location: ".$_SERVER['PHP_SELF']."?track_id=".$object->track_id); exit; } $mesg = $object->error; @@ -498,8 +498,8 @@ if (empty($reshook)) { // Log action in ticket logs table $log_action = $langs->trans('TicketLogReopen'); - $url = 'card.php?action=view&track_id=' . $object->track_id; - header("Location: " . $url); + $url = 'card.php?action=view&track_id='.$object->track_id; + header("Location: ".$url); exit(); } } @@ -508,16 +508,16 @@ if (empty($reshook)) { elseif ($action == 'classin' && $user->rights->ticket->write) { if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) { $object->setProject(GETPOST('projectid', 'int')); - $url = 'card.php?action=view&track_id=' . $object->track_id; - header("Location: " . $url); + $url = 'card.php?action=view&track_id='.$object->track_id; + header("Location: ".$url); exit(); } } // Categorisation dans contrat elseif ($action == 'setcontract' && $user->rights->ticket->write) { if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) { $object->setContract(GETPOST('contractid', 'int')); - $url = 'card.php?action=view&track_id=' . $object->track_id; - header("Location: " . $url); + $url = 'card.php?action=view&track_id='.$object->track_id; + header("Location: ".$url); exit(); } } elseif ($action == "set_message" && $user->rights->ticket->manage) { @@ -530,7 +530,7 @@ if (empty($reshook)) { $object->message = $fieldtomodify; $ret = $object->update($user); if ($ret > 0) { - $log_action = $langs->trans('TicketInitialMessageModified') . " \n"; + $log_action = $langs->trans('TicketInitialMessageModified')." \n"; // include the Diff class dol_include_once('/ticket/class/utils_diff.class.php'); // output the result of comparing two files as plain text @@ -551,8 +551,8 @@ if (empty($reshook)) { // Log action in ticket logs table $log_action = $langs->trans('TicketLogStatusChanged', $langs->transnoentities($object->statuts_short[$old_status]), $langs->transnoentities($object->statuts_short[$new_status])); - $url = 'card.php?action=view&track_id=' . $object->track_id; - header("Location: " . $url); + $url = 'card.php?action=view&track_id='.$object->track_id; + header("Location: ".$url); exit(); } } @@ -597,19 +597,19 @@ if (empty($reshook)) { $permissiondellink = $user->rights->ticket->write; - include DOL_DOCUMENT_ROOT . '/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once // Actions to build doc $upload_dir = $conf->ticket->dir_output; $permissiontoadd = $user->rights->ticket->write; - include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Actions to send emails $triggersendname = 'TICKET_SENTBYMAIL'; $paramname = 'id'; $autocopy = 'MAIN_MAIL_AUTOCOPY_TICKET_TO'; // used to know the automatic BCC to add - $trackid = 'tic' . $object->id; - include DOL_DOCUMENT_ROOT . '/core/actions_sendmails.inc.php'; + $trackid = 'tic'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Set $action to correct value for the case we used presend action to add a message if (GETPOSTISSET('actionbis') && $action == 'presend') $action = 'presend_addmessage'; @@ -1027,15 +1027,15 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd } else { // Type print ''.$langs->trans("Type").''; - print $langs->getLabelFromKey($db, 'TicketTypeShort' . $object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code); + print $langs->getLabelFromKey($db, 'TicketTypeShort'.$object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code); print ''; // Group print ''.$langs->trans("TicketCategory").''; - print $langs->getLabelFromKey($db, 'TicketCategoryShort' . $object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code); + print $langs->getLabelFromKey($db, 'TicketCategoryShort'.$object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code); print ''; // Severity print ''.$langs->trans("TicketSeverity").''; - print $langs->getLabelFromKey($db, 'TicketSeverityShort' . $object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code); + print $langs->getLabelFromKey($db, 'TicketSeverityShort'.$object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code); print ''; } print ''; // End table actions @@ -1299,7 +1299,7 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd } // Show messages on card (Note: this is a duplicate of the view Events/Agenda but on the main tab) - if (! empty($conf->global->TICKET_SHOW_MESSAGES_ON_CARD)) { + if (!empty($conf->global->TICKET_SHOW_MESSAGES_ON_CARD)) { $param = '&id='.$object->id; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; @@ -1308,17 +1308,17 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd $morehtmlright = ''; - $messagingUrl = DOL_URL_ROOT . '/ticket/agenda.php?track_id=' . $object->track_id; + $messagingUrl = DOL_URL_ROOT.'/ticket/agenda.php?track_id='.$object->track_id; $morehtmlright .= dolGetButtonTitle($langs->trans('MessageListViewType'), '', 'fal fa-list-alt imgforviewmode', $messagingUrl, '', 1); // Show link to add a message (if read and not closed) $btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage" && $action != "add_message"; - $url = 'card.php?track_id=' . $object->track_id . '&action=presend_addmessage&mode=init'; + $url = 'card.php?track_id='.$object->track_id.'&action=presend_addmessage&mode=init'; $morehtmlright .= dolGetButtonTitle($langs->trans('TicketAddMessage'), '', 'fal fa-comment-dots', $url, 'add-new-ticket-title-button', $btnstatus); // Show link to add event (if read and not closed) - $btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage" && $action != "add_message";; - $url = dol_buildpath('/comm/action/card.php', 1) . '?action=create&datep=' . date('YmdHi') . '&origin=ticket&originid=' . $object->id . '&projectid=' . $object->fk_project . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?track_id=' . $object->track_id); + $btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage" && $action != "add_message"; ; + $url = dol_buildpath('/comm/action/card.php', 1).'?action=create&datep='.date('YmdHi').'&origin=ticket&originid='.$object->id.'&projectid='.$object->fk_project.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?track_id='.$object->track_id); $morehtmlright .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fal fa-plus-circle', $url, 'add-new-ticket-even-button', $btnstatus); print_barre_liste($langs->trans("ActionsOnTicket"), 0, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlright, '', 0, 1, 1); @@ -1352,7 +1352,7 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd $morehtmlcenter .= dolGetButtonTitle($langs->trans('FullList'), '', 'fa fa-list-alt imgforviewmode', DOL_URL_ROOT.'/ticket/agenda.php?id='.$object->id); // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'ticket', $socid, 1, 'listactions', $MAXEVENT, '', $morehtmlcenter); diff --git a/htdocs/ticket/class/ticket.class.php b/htdocs/ticket/class/ticket.class.php index 6b3b1ea8fd4..bf24fa83626 100644 --- a/htdocs/ticket/class/ticket.class.php +++ b/htdocs/ticket/class/ticket.class.php @@ -1701,7 +1701,7 @@ class Ticket extends CommonObject $error = 0; // Valid and close fichinter linked - if (!empty($conf->ficheinter->enabled) && ! empty($conf->global->WORKFLOW_TICKET_CLOSE_INTERVENTION)) { + if (!empty($conf->ficheinter->enabled) && !empty($conf->global->WORKFLOW_TICKET_CLOSE_INTERVENTION)) { dol_syslog("We have closed the ticket, so we close all linked interventions"); $this->fetchObjectLinked($this->id, $this->element, null, 'fichinter'); if ($this->linkedObjectsIds) @@ -2549,23 +2549,23 @@ class Ticket extends CommonObject // Customer company infos $message .= '

'; $message .= "=============================================="; - $message .= !empty($object->thirdparty->name) ? '
' . $langs->trans('Thirdparty') . " : " . $object->thirdparty->name : ''; - $message .= !empty($object->thirdparty->town) ? '
' . $langs->trans('Town') . " : " . $object->thirdparty->town : ''; - $message .= !empty($object->thirdparty->phone) ? '
' . $langs->trans('Phone') . " : " . $object->thirdparty->phone : ''; + $message .= !empty($object->thirdparty->name) ? '
'.$langs->trans('Thirdparty')." : ".$object->thirdparty->name : ''; + $message .= !empty($object->thirdparty->town) ? '
'.$langs->trans('Town')." : ".$object->thirdparty->town : ''; + $message .= !empty($object->thirdparty->phone) ? '
'.$langs->trans('Phone')." : ".$object->thirdparty->phone : ''; // Email send to $message .= '

'; if (!empty($assigned_user_dont_have_email)) { - $message .= '
' . $langs->trans('NoEMail') . ' : ' . $assigned_user_dont_have_email; + $message .= '
'.$langs->trans('NoEMail').' : '.$assigned_user_dont_have_email; } foreach ($sendto as $val) { - $message .= '
' . $langs->trans('TicketNotificationRecipient') . ' : ' . $val; + $message .= '
'.$langs->trans('TicketNotificationRecipient').' : '.$val; } // URL ticket - $url_internal_ticket = dol_buildpath('/ticket/card.php', 2) . '?track_id=' . $object->track_id; + $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id; $message .= '

'; - $message .= $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . $object->track_id . ''; + $message .= $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : '.$object->track_id.''; $this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames); } @@ -2602,9 +2602,9 @@ class Ticket extends CommonObject // Coordonnées client $message .= '

'; $message .= "==============================================
"; - $message .= !empty($object->thirdparty->name) ? $langs->trans('Thirdparty') . " : " . $object->thirdparty->name : ''; - $message .= !empty($object->thirdparty->town) ? '
' . $langs->trans('Town') . " : " . $object->thirdparty->town : ''; - $message .= !empty($object->thirdparty->phone) ? '
' . $langs->trans('Phone') . " : " . $object->thirdparty->phone : ''; + $message .= !empty($object->thirdparty->name) ? $langs->trans('Thirdparty')." : ".$object->thirdparty->name : ''; + $message .= !empty($object->thirdparty->town) ? '
'.$langs->trans('Town')." : ".$object->thirdparty->town : ''; + $message .= !empty($object->thirdparty->phone) ? '
'.$langs->trans('Phone')." : ".$object->thirdparty->phone : ''; // Build array to display recipient list foreach ($internal_contacts as $key => $info_sendto) { @@ -2614,19 +2614,19 @@ class Ticket extends CommonObject } if ($info_sendto['email'] != '') { - if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">"; + if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">"; //Contact type - $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')'; - $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . '
' : ''); + $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')'; + $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient.'
' : ''); } } $message .= '
'; // URL ticket - $url_internal_ticket = dol_buildpath('/ticket/card.php', 2) . '?track_id=' . $object->track_id; + $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id; // altairis: make html link on url - $message .= '
' . $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . $object->track_id . '
'; + $message .= '
'.$langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : '.$object->track_id.'
'; // Add global email address recipient if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) { @@ -2688,23 +2688,23 @@ class Ticket extends CommonObject } if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) { - if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">"; + if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">"; - $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')'; - $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . '
' : ''); + $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')'; + $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient.'
' : ''); } } // If public interface is not enable, use link to internal page into mail $url_public_ticket = (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE) ? - (!empty($conf->global->TICKET_URL_PUBLIC_INTERFACE) ? $conf->global->TICKET_URL_PUBLIC_INTERFACE . '/view.php' : dol_buildpath('/public/ticket/view.php', 2)) : dol_buildpath('/ticket/card.php', 2)) . '?track_id=' . $object->track_id; - $message .= '
' . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . $object->track_id . '
'; + (!empty($conf->global->TICKET_URL_PUBLIC_INTERFACE) ? $conf->global->TICKET_URL_PUBLIC_INTERFACE.'/view.php' : dol_buildpath('/public/ticket/view.php', 2)) : dol_buildpath('/ticket/card.php', 2)).'?track_id='.$object->track_id; + $message .= '
'.$langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer').' : '.$object->track_id.'
'; // Build final message - $message = $message_intro . '

' . $message; + $message = $message_intro.'

'.$message; // Add signature - $message .= '
' . $message_signature; + $message .= '
'.$message_signature; if (!empty($object->origin_email)) { $sendto[] = $object->origin_email; diff --git a/htdocs/ticket/list.php b/htdocs/ticket/list.php index 184216ea47e..c4c1cbadcc9 100644 --- a/htdocs/ticket/list.php +++ b/htdocs/ticket/list.php @@ -100,9 +100,9 @@ foreach ($object->fields as $key => $val) { if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } -$fieldstosearchall['s.name_alias']="AliasNameShort"; -$fieldstosearchall['s.zip']="Zip"; -$fieldstosearchall['s.town']="Town"; +$fieldstosearchall['s.name_alias'] = "AliasNameShort"; +$fieldstosearchall['s.zip'] = "Zip"; +$fieldstosearchall['s.town'] = "Town"; // Definition of fields for list $arrayfields = array(); @@ -755,13 +755,13 @@ while ($i < min($num, $limit)) print '>'; if ($key == 'fk_statut') print $object->getLibStatut(5); elseif ($key == 'type_code') { - $s = $langs->getLabelFromKey($db, 'TicketTypeShort' . $object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code); + $s = $langs->getLabelFromKey($db, 'TicketTypeShort'.$object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code); print ''; print $s; print ''; } - elseif ($key == 'category_code') print $langs->getLabelFromKey($db, 'TicketCategoryShort' . $object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code); - elseif ($key == 'severity_code') print $langs->getLabelFromKey($db, 'TicketSeverityShort' . $object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code); + elseif ($key == 'category_code') print $langs->getLabelFromKey($db, 'TicketCategoryShort'.$object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code); + elseif ($key == 'severity_code') print $langs->getLabelFromKey($db, 'TicketSeverityShort'.$object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code); elseif ($key == 'tms') print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser'); elseif ($key == 'fk_user_create') { if ($object->fk_user_create > 0) { diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index f6a3862d0bb..1dfd090eb5c 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -3233,9 +3233,9 @@ class User extends CommonObject } return $num; } else { - $this->errors[] = $this->db->lasterror(); - return -1; - } + $this->errors[] = $this->db->lasterror(); + return -1; + } } /** diff --git a/htdocs/user/group/perms.php b/htdocs/user/group/perms.php index d8d6c74f00b..b22dafce758 100644 --- a/htdocs/user/group/perms.php +++ b/htdocs/user/group/perms.php @@ -303,7 +303,7 @@ if ($object->id > 0) print ' '; // Module id - if ($user->admin) print ''. $objMod->numero.''; + if ($user->admin) print ''.$objMod->numero.''; print ''; } diff --git a/htdocs/user/perms.php b/htdocs/user/perms.php index 4b99cfb7e18..f87785da31f 100644 --- a/htdocs/user/perms.php +++ b/htdocs/user/perms.php @@ -365,7 +365,7 @@ if ($result) print ' '; // Module Id - if ($user->admin) print ''. $objMod->numero.''; + if ($user->admin) print ''.$objMod->numero.''; print ''."\n"; } diff --git a/htdocs/variants/class/ProductCombination.class.php b/htdocs/variants/class/ProductCombination.class.php index 52884afc875..f1b10559898 100644 --- a/htdocs/variants/class/ProductCombination.class.php +++ b/htdocs/variants/class/ProductCombination.class.php @@ -165,11 +165,11 @@ class ProductCombination /** * for auto retrocompatibility with last behavior */ - if ($fk_price_level>0){ + if ($fk_price_level > 0) { $combination_price_levels[$fk_price_level] = ProductCombinationLevel::createFromParent($this->db, $this, $fk_price_level); } else { - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++){ + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $combination_price_levels[$i] = ProductCombinationLevel::createFromParent($this->db, $this, $i); } } @@ -783,16 +783,16 @@ class ProductCombination $newcomb->variation_weight = $weight_impact; // Init price level - if ($conf->global->PRODUIT_MULTIPRICES){ - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++){ + if ($conf->global->PRODUIT_MULTIPRICES) { + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $productCombinationLevel = new ProductCombinationLevel($this->db); $productCombinationLevel->fk_product_attribute_combination = $newcomb->id; $productCombinationLevel->fk_price_level = $i; $productCombinationLevel->variation_price = $price_impact[$i]; - if (is_array($price_var_percent)){ + if (is_array($price_var_percent)) { $productCombinationLevel->variation_price_percentage = (empty($price_var_percent[$i]) ? false : $price_var_percent[$i]); - }else { + } else { $productCombinationLevel->variation_price_percentage = $price_var_percent; }