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

This commit is contained in:
Florian HENRY 2021-02-27 13:16:37 +01:00
commit 5e0ca7417e
1271 changed files with 102091 additions and 86257 deletions

View File

@ -21,6 +21,8 @@ Following changes may create regressions for some external modules, but were nec
* API /setup/shipment_methods has been replaced with API /setup/shipping_methods * API /setup/shipment_methods has been replaced with API /setup/shipping_methods
* Field "tva" renamed into "total_tva" in llx_propal, llx_supplier_proposal, llx_commande, llx_commande_fournisseur for better field name consistency * Field "tva" renamed into "total_tva" in llx_propal, llx_supplier_proposal, llx_commande, llx_commande_fournisseur for better field name consistency
* Field "total" renamed into "total_ttc" in llx_propal, llx_supplier_proposal for better field name consistency * Field "total" renamed into "total_ttc" in llx_propal, llx_supplier_proposal for better field name consistency
* If your database is PostgreSql, you must use version 9.1.0 or more (Dolibarr need the SQL function CONCAT)
* If your database is MySql or MariaDB, you need at least version 5.1
***** ChangeLog for 13.0.1 compared to 13.0.0 ***** ***** ChangeLog for 13.0.1 compared to 13.0.0 *****

View File

@ -1,135 +0,0 @@
<?php
/* Copyright (C) 2013-2014 Olivier Geffroy <jeff@jeffinfo.com>
* Copyright (C) 2013-2014 Alexandre Spangaro <aspangaro@open-dsi.fr>
* Copyright (C) 2014 Florian Henry <florian.henry@open-concept.pro>
* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
/**
* \file htdocs/accountancy/bookkeeping/balancebymonth.php
* \ingroup Accountancy (Double entries)
* \brief Balance by month
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
// Load translation files required by the page
$langs->loadLangs(array("bills", "compta", "accountancy", "other"));
// Filter
$year = GETPOST("year", 'int');
if ($year == 0) {
$year_current = strftime("%Y", time());
$year_start = $year_current;
} else {
$year_current = $year;
$year_start = $year;
}
/*
* View
*/
llxHeader('', $langs->trans("Bookkeeping"));
$textprevyear = '<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_current - 1).'">'.img_previous().'</a>';
$textnextyear = '&nbsp;<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_current + 1).'">'.img_next().'</a>';
print load_fiche_titre($langs->trans("AccountBalanceByMonth").' '.$textprevyear.' '.$langs->trans("Year").' '.$year_start.' '.$textnextyear);
$sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."facturedet as fd";
$sql .= " , ".MAIN_DB_PREFIX."facture as f";
$sql .= " WHERE fd.fk_code_ventilation = 0";
$sql .= " AND f.rowid = fd.fk_facture AND f.fk_statut = 1;";
dol_syslog('accountancy/bookkeeping/balancebymonth.php:: $sql='.$sql);
$result = $db->query($sql);
if ($result) {
$row = $db->fetch_row($result);
$nbfac = $row[0];
$db->free($result);
}
$y = $year_current;
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td width=150>'.$langs->trans("Label").'</td>';
for ($i = 1; $i <= 12; $i++) {
print '<td class="right">'.$langs->trans("MonthShort".sprintf("%02s", $i)).'</td>';
}
print '<td class="center"><strong>'.$langs->trans("Total").'</strong></td>';
print '</tr>';
$sql = "SELECT bk.numero_compte AS 'compte',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=1,bk.montant,0)),2) AS 'Janvier',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=2,bk.montant,0)),2) AS 'Fevrier',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=3,bk.montant,0)),2) AS 'Mars',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=4,bk.montant,0)),2) AS 'Avril',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=5,bk.montant,0)),2) AS 'Mai',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=6,bk.montant,0)),2) AS 'Juin',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=7,bk.montant,0)),2) AS 'Juillet',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=8,bk.montant,0)),2) AS 'Aout',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=9,bk.montant,0)),2) AS 'Septembre',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=10,bk.montant,0)),2) AS 'Octobre',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=11,bk.montant,0)),2) AS 'Novembre',";
$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=12,bk.montant,0)),2) AS 'Decembre',";
$sql .= " ROUND(SUM(bk.montant),2) as 'Total'";
$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk";
$sql .= " WHERE bk.doc_date >= '".$db->idate(dol_get_first_day($y, 1, false))."'";
$sql .= " AND bk.doc_date <= '".$db->idate(dol_get_last_day($y, 12, false))."'";
$sql .= " GROUP BY bk.numero_compte";
$resql = $db->query($sql);
if ($resql) {
$i = 0;
$num = $db->num_rows($resql);
while ($i < $num) {
$row = $db->fetch_row($resql);
print '<tr class="oddeven"><td width="14%">'.length_accountg($row[0]).'</td>';
print '<td class="right" width="6.5%">'.price($row[1]).'</td>';
print '<td class="right" width="6.5%">'.price($row[2]).'</td>';
print '<td class="right" width="6.5%">'.price($row[3]).'</td>';
print '<td class="right" width="6.5%">'.price($row[4]).'</td>';
print '<td class="right" width="6.5%">'.price($row[5]).'</td>';
print '<td class="right" width="6.5%">'.price($row[6]).'</td>';
print '<td class="right" width="6.5%">'.price($row[7]).'</td>';
print '<td class="right" width="6.5%">'.price($row[8]).'</td>';
print '<td class="right" width="6.5%">'.price($row[9]).'</td>';
print '<td class="right" width="6.5%">'.price($row[10]).'</td>';
print '<td class="right" width="6.5%">'.price($row[11]).'</td>';
print '<td class="right" width="6.5%">'.price($row[12]).'</td>';
print '<td class="right" width="8%"><strong>'.price($row[13]).'</strong></td>';
print '</tr>';
$i++;
}
$db->free($resql);
} else {
print $db->lasterror();
}
print "</table>\n";
// End of page
llxFooter();
$db->close();

View File

@ -359,7 +359,7 @@ class AccountancyExport
print length_accountg($line->numero_compte).$separator; print length_accountg($line->numero_compte).$separator;
print length_accounta($line->subledger_account).$separator; print length_accounta($line->subledger_account).$separator;
print $line->sens.$separator; print $line->sens.$separator;
print price2fec(abs($line->montant)).$separator; print price2fec(abs($line->debit - $line->credit)).$separator;
print dol_string_unaccent($line->label_operation).$separator; print dol_string_unaccent($line->label_operation).$separator;
print dol_string_unaccent($line->doc_ref); print dol_string_unaccent($line->doc_ref);
print $end_line; print $end_line;
@ -387,11 +387,11 @@ class AccountancyExport
print $line->label_operation.$separator; print $line->label_operation.$separator;
print $date.$separator; print $date.$separator;
if ($line->sens == 'D') { if ($line->sens == 'D') {
print price($line->montant).$separator; print price($line->debit).$separator;
print ''.$separator; print ''.$separator;
} elseif ($line->sens == 'C') { } elseif ($line->sens == 'C') {
print ''.$separator; print ''.$separator;
print price($line->montant).$separator; print price($line->credit).$separator;
} }
print $line->doc_ref.$separator; print $line->doc_ref.$separator;
print $line->label_operation.$separator; print $line->label_operation.$separator;
@ -493,7 +493,7 @@ class AccountancyExport
$Tab['num_piece'] = str_pad(self::trunc($data->piece_num, 12), 12); $Tab['num_piece'] = str_pad(self::trunc($data->piece_num, 12), 12);
$Tab['num_compte'] = str_pad(self::trunc($code_compta, 11), 11); $Tab['num_compte'] = str_pad(self::trunc($code_compta, 11), 11);
$Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).dol_string_unaccent($data->label_operation), 25), 25); $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).dol_string_unaccent($data->label_operation), 25), 25);
$Tab['montant'] = str_pad(abs($data->montant), 13, ' ', STR_PAD_LEFT); $Tab['montant'] = str_pad(abs($data->debit - $data->credit), 13, ' ', STR_PAD_LEFT);
$Tab['type_montant'] = str_pad($data->sens, 1); $Tab['type_montant'] = str_pad($data->sens, 1);
$Tab['vide'] = str_repeat(' ', 18); $Tab['vide'] = str_repeat(' ', 18);
$Tab['intitule_compte'] = str_pad(self::trunc(dol_string_unaccent($data->label_operation), 34), 34); $Tab['intitule_compte'] = str_pad(self::trunc(dol_string_unaccent($data->label_operation), 34), 34);
@ -541,6 +541,7 @@ class AccountancyExport
$Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).' '.dol_string_unaccent($data->label_operation), 20), 20); $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).' '.dol_string_unaccent($data->label_operation), 20), 20);
// Credit invoice - invert sens // Credit invoice - invert sens
/*
if ($data->montant < 0) { if ($data->montant < 0) {
if ($data->sens == 'C') { if ($data->sens == 'C') {
$Tab['sens'] = 'D'; $Tab['sens'] = 'D';
@ -551,10 +552,12 @@ class AccountancyExport
} else { } else {
$Tab['sens'] = $data->sens; // C or D $Tab['sens'] = $data->sens; // C or D
$Tab['signe_montant'] = '+'; $Tab['signe_montant'] = '+';
} }*/
$Tab['sens'] = $data->sens; // C or D
$Tab['signe_montant'] = '+';
// The amount must be in centimes without decimal points. // The amount must be in centimes without decimal points.
$Tab['montant'] = str_pad(abs($data->montant * 100), 12, '0', STR_PAD_LEFT); $Tab['montant'] = str_pad(abs(($data->debit - $abs->credit) * 100), 12, '0', STR_PAD_LEFT);
$Tab['contrepartie'] = str_repeat(' ', 8); $Tab['contrepartie'] = str_repeat(' ', 8);
// Force date format : %d%m%y // Force date format : %d%m%y
@ -640,13 +643,13 @@ class AccountancyExport
$Tab['num_compte'] = str_pad(self::trunc($code_compta, 6), 6, '0'); $Tab['num_compte'] = str_pad(self::trunc($code_compta, 6), 6, '0');
if ($data->sens == 'D') { if ($data->sens == 'D') {
$Tab['montant_debit'] = str_pad(number_format(abs($data->montant), 2, ',', ''), 13, ' ', STR_PAD_LEFT); $Tab['montant_debit'] = str_pad(number_format($data->debit, 2, ',', ''), 13, ' ', STR_PAD_LEFT);
$Tab['montant_crebit'] = str_pad(number_format(0, 2, ',', ''), 13, ' ', STR_PAD_LEFT); $Tab['montant_crebit'] = str_pad(number_format(0, 2, ',', ''), 13, ' ', STR_PAD_LEFT);
} else { } else {
$Tab['montant_debit'] = str_pad(number_format(0, 2, ',', ''), 13, ' ', STR_PAD_LEFT); $Tab['montant_debit'] = str_pad(number_format(0, 2, ',', ''), 13, ' ', STR_PAD_LEFT);
$Tab['montant_crebit'] = str_pad(number_format(abs($data->montant), 2, ',', ''), 13, ' ', STR_PAD_LEFT); $Tab['montant_crebit'] = str_pad(number_format($data->credit, 2, ',', ''), 13, ' ', STR_PAD_LEFT);
} }
$Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).' '.dol_string_unaccent($data->label_operation), 30), 30); $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).' '.dol_string_unaccent($data->label_operation), 30), 30);
@ -707,7 +710,7 @@ class AccountancyExport
//print substr(length_accountg($line->numero_compte), 0, 2) . $separator; //print substr(length_accountg($line->numero_compte), 0, 2) . $separator;
print '"'.dol_trunc($line->label_operation, 40, 'right', 'UTF-8', 1).'"'.$separator; print '"'.dol_trunc($line->label_operation, 40, 'right', 'UTF-8', 1).'"'.$separator;
print '"'.dol_trunc($line->piece_num, 15, 'right', 'UTF-8', 1).'"'.$separator; print '"'.dol_trunc($line->piece_num, 15, 'right', 'UTF-8', 1).'"'.$separator;
print price2num(abs($line->montant)).$separator; print price2num(abs($line->debit - $line->credit)).$separator;
print $line->sens.$separator; print $line->sens.$separator;
print $date.$separator; print $date.$separator;
//print 'EUR'; //print 'EUR';
@ -747,7 +750,7 @@ class AccountancyExport
print self::toAnsi($line->doc_ref).$separator; print self::toAnsi($line->doc_ref).$separator;
print price($line->debit).$separator; print price($line->debit).$separator;
print price($line->credit).$separator; print price($line->credit).$separator;
print price($line->montant).$separator; print price(abs($line->debit - $line->credit)).$separator;
print $line->sens.$separator; print $line->sens.$separator;
print $line->lettering_code.$separator; print $line->lettering_code.$separator;
print $line->code_journal; print $line->code_journal;
@ -810,7 +813,7 @@ class AccountancyExport
$tab[] = length_accounta($line->subledger_account); $tab[] = length_accounta($line->subledger_account);
$tab[] = price2num($line->debit); $tab[] = price2num($line->debit);
$tab[] = price2num($line->credit); $tab[] = price2num($line->credit);
$tab[] = price2num($line->montant); $tab[] = price2num($line->debit - $line->credit);
$tab[] = $line->code_journal; $tab[] = $line->code_journal;
print implode($separator, $tab).$this->end_line; print implode($separator, $tab).$this->end_line;
@ -853,7 +856,7 @@ class AccountancyExport
foreach ($objectLines as $line) { foreach ($objectLines as $line) {
if ($line->debit == 0 && $line->credit == 0) { if ($line->debit == 0 && $line->credit == 0) {
unset($array[$line]); //unset($array[$line]);
} else { } else {
$date_creation = dol_print_date($line->date_creation, '%Y%m%d'); $date_creation = dol_print_date($line->date_creation, '%Y%m%d');
$date_document = dol_print_date($line->doc_date, '%Y%m%d'); $date_document = dol_print_date($line->doc_date, '%Y%m%d');
@ -959,7 +962,7 @@ class AccountancyExport
foreach ($objectLines as $line) { foreach ($objectLines as $line) {
if ($line->debit == 0 && $line->credit == 0) { if ($line->debit == 0 && $line->credit == 0) {
unset($array[$line]); //unset($array[$line]);
} else { } else {
$date_creation = dol_print_date($line->date_creation, '%Y%m%d'); $date_creation = dol_print_date($line->date_creation, '%Y%m%d');
$date_document = dol_print_date($line->doc_date, '%Y%m%d'); $date_document = dol_print_date($line->doc_date, '%Y%m%d');
@ -1110,11 +1113,7 @@ class AccountancyExport
// Code // Code
print '""'.$this->separator; print '""'.$this->separator;
// Netto // Netto
if ($line->montant >= 0) { print abs($line->debit - $line->credit).$this->separator;
print $line->montant.$this->separator;
} else {
print ($line->montant * -1).$this->separator;
}
// Steuer // Steuer
print "0.00".$this->separator; print "0.00".$this->separator;
// FW-Betrag // FW-Betrag
@ -1190,13 +1189,13 @@ class AccountancyExport
print $date_lim_reglement.$separator; print $date_lim_reglement.$separator;
// CNPI // CNPI
if ($line->doc_type == 'supplier_invoice') { if ($line->doc_type == 'supplier_invoice') {
if ($line->montant < 0) { if (($line->debit - $line->credit) > 0) {
$nature_piece = 'AF'; $nature_piece = 'AF';
} else { } else {
$nature_piece = 'FF'; $nature_piece = 'FF';
} }
} elseif ($line->doc_type == 'customer_invoice') { } elseif ($line->doc_type == 'customer_invoice') {
if ($line->montant < 0) { if (($line->debit - $line->credit) < 0) {
$nature_piece = 'AC'; $nature_piece = 'AC';
} else { } else {
$nature_piece = 'FC'; $nature_piece = 'FC';
@ -1220,7 +1219,7 @@ class AccountancyExport
print $racine_subledger_account.$separator; // deprecated CPTG & CPTA use instead print $racine_subledger_account.$separator; // deprecated CPTG & CPTA use instead
// MONT // MONT
print price(abs($line->montant), 0, '', 1, 2, 2).$separator; print price(abs($line->debit - $line->credit), 0, '', 1, 2, 2).$separator;
// CODC // CODC
print $line->sens.$separator; print $line->sens.$separator;
// CPTG // CPTG
@ -1451,13 +1450,13 @@ class AccountancyExport
print $date_lim_reglement.$separator; print $date_lim_reglement.$separator;
// CNPI // CNPI
if ($line->doc_type == 'supplier_invoice') { if ($line->doc_type == 'supplier_invoice') {
if ($line->montant < 0) { if (($line->debit - $line->credit) > 0) {
$nature_piece = 'AF'; $nature_piece = 'AF';
} else { } else {
$nature_piece = 'FF'; $nature_piece = 'FF';
} }
} elseif ($line->doc_type == 'customer_invoice') { } elseif ($line->doc_type == 'customer_invoice') {
if ($line->montant < 0) { if (($line->debit - $line->credit) < 0) {
$nature_piece = 'AC'; $nature_piece = 'AC';
} else { } else {
$nature_piece = 'FC'; $nature_piece = 'FC';
@ -1481,7 +1480,7 @@ class AccountancyExport
print $racine_subledger_account.$separator; // deprecated CPTG & CPTA use instead print $racine_subledger_account.$separator; // deprecated CPTG & CPTA use instead
// MONT // MONT
print price(abs($line->montant), 0, '', 1, 2).$separator; print price(abs($line->debit - $line->credit), 0, '', 1, 2).$separator;
// CODC // CODC
print $line->sens.$separator; print $line->sens.$separator;
// CPTG // CPTG
@ -1602,7 +1601,7 @@ class AccountancyExport
print self::trunc($line->label_compte, 60).$separator; //Account label print self::trunc($line->label_compte, 60).$separator; //Account label
print self::trunc($line->doc_ref, 20).$separator; //Piece print self::trunc($line->doc_ref, 20).$separator; //Piece
print self::trunc($line->label_operation, 60).$separator; //Operation label print self::trunc($line->label_operation, 60).$separator; //Operation label
print price(abs($line->montant)).$separator; //Amount print price(abs($line->debit - $line->credit)).$separator; //Amount
print $line->sens.$separator; //Direction print $line->sens.$separator; //Direction
print $separator; //Analytic print $separator; //Analytic
print $separator; //Analytic print $separator; //Analytic
@ -1631,7 +1630,7 @@ class AccountancyExport
$supplier_invoices_infos = array(); $supplier_invoices_infos = array();
foreach ($objectLines as $line) { foreach ($objectLines as $line) {
if ($line->debit == 0 && $line->credit == 0) { if ($line->debit == 0 && $line->credit == 0) {
unset($array[$line]); //unset($array[$line]);
} else { } else {
$date = dol_print_date($line->doc_date, '%d/%m/%Y'); $date = dol_print_date($line->doc_date, '%d/%m/%Y');
@ -1699,8 +1698,8 @@ class AccountancyExport
print dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1) . $this->separator; print dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1) . $this->separator;
//Devise //Devise
print 'EUR' . $this->separator; print 'EUR' . $this->separator;
//Montant //Amount
print price2num(abs($line->montant)) . $this->separator; print price2num(abs($line->debit - $line->credit)) . $this->separator;
//Sens //Sens
print $line->sens . $this->separator; print $line->sens . $this->separator;
//Code lettrage //Code lettrage
@ -1726,14 +1725,14 @@ class AccountancyExport
foreach ($objectLines as $line) { foreach ($objectLines as $line) {
if ($line->debit == 0 && $line->credit == 0) { if ($line->debit == 0 && $line->credit == 0) {
unset($array[$line]); //unset($array[$line]);
} else { } else {
$date = dol_print_date($line->doc_date, '%d%m%Y'); $date = dol_print_date($line->doc_date, '%d%m%Y');
print $line->id . $this->separator; print $line->id . $this->separator;
print $date . $this->separator; print $date . $this->separator;
print substr($line->code_journal, 0, 4) . $this->separator; print substr($line->code_journal, 0, 4) . $this->separator;
if ((substr($line->numero_compte, 0, 3) == '411') || (substr($line->numero_compte, 0, 3) == '401')) { if ((substr($line->numero_compte, 0, 3) == '411') || (substr($line->numero_compte, 0, 3) == '401')) { // TODO No hard code value
print length_accountg($line->subledger_account) . $this->separator; print length_accountg($line->subledger_account) . $this->separator;
} else { } else {
print substr(length_accountg($line->numero_compte), 0, 15) . $this->separator; print substr(length_accountg($line->numero_compte), 0, 15) . $this->separator;
@ -1742,7 +1741,7 @@ class AccountancyExport
//print '"'.dol_trunc(str_replace('"', '', $line->label_operation),40,'right','UTF-8',1).'"' . $this->separator; //print '"'.dol_trunc(str_replace('"', '', $line->label_operation),40,'right','UTF-8',1).'"' . $this->separator;
print '"' . dol_trunc(str_replace('"', '', $line->doc_ref), 40, 'right', 'UTF-8', 1) . '"' . $this->separator; print '"' . dol_trunc(str_replace('"', '', $line->doc_ref), 40, 'right', 'UTF-8', 1) . '"' . $this->separator;
print '"' . dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1) . '"' . $this->separator; print '"' . dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1) . '"' . $this->separator;
print price2num($line->montant) . $this->separator; print price2num(abs($line->debit - $line->credit)) . $this->separator;
print $line->sens . $this->separator; print $line->sens . $this->separator;
print $date . $this->separator; print $date . $this->separator;
print $this->separator; print $this->separator;

View File

@ -135,6 +135,7 @@ class BookKeeping extends CommonObject
/** /**
* @var float FEC:Amount (Not necessary) * @var float FEC:Amount (Not necessary)
* @deprecated No more used
*/ */
public $amount; public $amount;
@ -239,6 +240,9 @@ class BookKeeping extends CommonObject
if (isset($this->montant)) { if (isset($this->montant)) {
$this->montant = (float) $this->montant; $this->montant = (float) $this->montant;
} }
if (isset($this->amount)) {
$this->amount = (float) $this->amount;
}
if (isset($this->sens)) { if (isset($this->sens)) {
$this->sens = trim($this->sens); $this->sens = trim($this->sens);
} }
@ -563,6 +567,9 @@ class BookKeeping extends CommonObject
if (isset($this->montant)) { if (isset($this->montant)) {
$this->montant = trim($this->montant); $this->montant = trim($this->montant);
} }
if (isset($this->amount)) {
$this->amount = trim($this->amount);
}
if (isset($this->sens)) { if (isset($this->sens)) {
$this->sens = trim($this->sens); $this->sens = trim($this->sens);
} }
@ -708,7 +715,7 @@ class BookKeeping extends CommonObject
$sql .= " t.label_operation,"; $sql .= " t.label_operation,";
$sql .= " t.debit,"; $sql .= " t.debit,";
$sql .= " t.credit,"; $sql .= " t.credit,";
$sql .= " t.montant,"; $sql .= " t.montant as amount,";
$sql .= " t.sens,"; $sql .= " t.sens,";
$sql .= " t.fk_user_author,"; $sql .= " t.fk_user_author,";
$sql .= " t.import_key,"; $sql .= " t.import_key,";
@ -747,7 +754,8 @@ class BookKeeping extends CommonObject
$this->label_operation = $obj->label_operation; $this->label_operation = $obj->label_operation;
$this->debit = $obj->debit; $this->debit = $obj->debit;
$this->credit = $obj->credit; $this->credit = $obj->credit;
$this->montant = $obj->montant; $this->montant = $obj->amount;
$this->amount = $obj->amount;
$this->sens = $obj->sens; $this->sens = $obj->sens;
$this->fk_user_author = $obj->fk_user_author; $this->fk_user_author = $obj->fk_user_author;
$this->import_key = $obj->import_key; $this->import_key = $obj->import_key;
@ -1207,8 +1215,8 @@ class BookKeeping extends CommonObject
if (isset($this->credit)) { if (isset($this->credit)) {
$this->credit = trim($this->credit); $this->credit = trim($this->credit);
} }
if (isset($this->montant)) { if (isset($this->amount)) {
$this->montant = trim($this->montant); $this->amount = trim($this->amount);
} }
if (isset($this->sens)) { if (isset($this->sens)) {
$this->sens = trim($this->sens); $this->sens = trim($this->sens);
@ -1655,7 +1663,7 @@ class BookKeeping extends CommonObject
$sql = "SELECT rowid, doc_date, doc_type,"; $sql = "SELECT rowid, doc_date, doc_type,";
$sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,"; $sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,";
$sql .= " numero_compte, label_compte, label_operation, debit, credit,"; $sql .= " numero_compte, label_compte, label_operation, debit, credit,";
$sql .= " montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num, date_creation"; $sql .= " montant as amount, sens, fk_user_author, import_key, code_journal, journal_label, piece_num, date_creation";
$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
$sql .= " WHERE piece_num = ".$piecenum; $sql .= " WHERE piece_num = ".$piecenum;
$sql .= " AND entity IN (".getEntity('accountancy').")"; $sql .= " AND entity IN (".getEntity('accountancy').")";
@ -1681,7 +1689,8 @@ class BookKeeping extends CommonObject
$line->label_operation = $obj->label_operation; $line->label_operation = $obj->label_operation;
$line->debit = $obj->debit; $line->debit = $obj->debit;
$line->credit = $obj->credit; $line->credit = $obj->credit;
$line->montant = $obj->montant; $line->montant = $obj->amount;
$line->amount = $obj->amount;
$line->sens = $obj->sens; $line->sens = $obj->sens;
$line->code_journal = $obj->code_journal; $line->code_journal = $obj->code_journal;
$line->journal_label = $obj->journal_label; $line->journal_label = $obj->journal_label;
@ -1714,7 +1723,7 @@ class BookKeeping extends CommonObject
$sql = "SELECT rowid, doc_date, doc_type,"; $sql = "SELECT rowid, doc_date, doc_type,";
$sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,"; $sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,";
$sql .= " numero_compte, label_compte, label_operation, debit, credit,"; $sql .= " numero_compte, label_compte, label_operation, debit, credit,";
$sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num"; $sql .= " montant as amount, sens, fk_user_author, import_key, code_journal, piece_num";
$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
$sql .= " WHERE entity IN (".getEntity('accountancy').")"; $sql .= " WHERE entity IN (".getEntity('accountancy').")";
@ -1744,7 +1753,8 @@ class BookKeeping extends CommonObject
$line->label_operation = $obj->label_operation; $line->label_operation = $obj->label_operation;
$line->debit = $obj->debit; $line->debit = $obj->debit;
$line->credit = $obj->credit; $line->credit = $obj->credit;
$line->montant = $obj->montant; $line->montant = $obj->amount;
$line->amount = $obj->amount;
$line->sens = $obj->sens; $line->sens = $obj->sens;
$line->code_journal = $obj->code_journal; $line->code_journal = $obj->code_journal;
$line->piece_num = $obj->piece_num; $line->piece_num = $obj->piece_num;

View File

@ -41,8 +41,7 @@ $langs->load("admin");
*/ */
// Enable and test if module Api is enabled // Enable and test if module Api is enabled
if (empty($conf->global->MAIN_MODULE_API)) if (empty($conf->global->MAIN_MODULE_API)) {
{
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
print $langs->trans("ToActivateModule"); print $langs->trans("ToActivateModule");
@ -59,20 +58,16 @@ $api->r->addAuthenticationClass('DolibarrApiAccess', '');
$listofapis = array(); $listofapis = array();
$modulesdir = dolGetModulesDirs(); $modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
/* /*
* Search available module * Search available module
*/ */
//dol_syslog("Scan directory ".$dir." for API modules"); //dol_syslog("Scan directory ".$dir." for API modules");
$handle = @opendir(dol_osencode($dir)); $handle = @opendir(dol_osencode($dir));
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
{
if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg))
{
$modulename = $reg[1]; $modulename = $reg[1];
// Defined if module is enabled // Defined if module is enabled
@ -96,7 +91,9 @@ foreach ($modulesdir as $dir)
$module = 'fichinter'; $module = 'fichinter';
} }
if (empty($conf->$module->enabled)) $enabled = false; if (empty($conf->$module->enabled)) {
$enabled = false;
}
if ($enabled) { if ($enabled) {
/* /*
@ -110,16 +107,12 @@ foreach ($modulesdir as $dir)
$dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/'; $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/';
$handle_part = @opendir(dol_osencode($dir_part)); $handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part)) if (is_resource($handle_part)) {
{ while (($file_searched = readdir($handle_part)) !== false) {
while (($file_searched = readdir($handle_part)) !== false) if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) {
{
if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg))
{
$classname = ucwords($reg[1]); $classname = ucwords($reg[1]);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname)) if (class_exists($classname)) {
{
dol_syslog("Found API classname=".$classname." into ".$dir); dol_syslog("Found API classname=".$classname." into ".$dir);
$listofapis[] = $classname; $listofapis[] = $classname;
} }
@ -186,21 +179,23 @@ print '<br>';
$oldclass = ''; $oldclass = '';
print $langs->trans("ListOfAvailableAPIs").':<br>'; print $langs->trans("ListOfAvailableAPIs").':<br>';
foreach ($listofapis['v1'] as $key => $val) foreach ($listofapis['v1'] as $key => $val) {
{ if ($key == 'login') {
if ($key == 'login') continue; continue;
if ($key == 'index') continue; }
if ($key == 'index') {
continue;
}
if ($key) if ($key) {
{ foreach ($val as $method => $val2) {
foreach ($val as $method => $val2)
{
$newclass = $val2['className']; $newclass = $val2['className'];
if (preg_match('/restler/i', $newclass)) continue; if (preg_match('/restler/i', $newclass)) {
continue;
}
if ($oldclass != $newclass) if ($oldclass != $newclass) {
{
print "\n<br>\n".$langs->trans("Class").': '.$newclass.'<br>'."\n"; print "\n<br>\n".$langs->trans("Class").': '.$newclass.'<br>'."\n";
$oldclass = $newclass; $oldclass = $newclass;
} }

View File

@ -51,7 +51,9 @@ class DolibarrApi
{ {
global $conf, $dolibarr_main_url_root; global $conf, $dolibarr_main_url_root;
if (empty($cachedir)) $cachedir = $conf->api->dir_temp; if (empty($cachedir)) {
$cachedir = $conf->api->dir_temp;
}
Defaults::$cacheDirectory = $cachedir; Defaults::$cacheDirectory = $cachedir;
$this->db = $db; $this->db = $db;
@ -191,8 +193,7 @@ class DolibarrApi
// If object has lines, remove $db property // If object has lines, remove $db property
if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
$nboflines = count($object->lines); $nboflines = count($object->lines);
for ($i = 0; $i < $nboflines; $i++) for ($i = 0; $i < $nboflines; $i++) {
{
$this->_cleanObjectDatas($object->lines[$i]); $this->_cleanObjectDatas($object->lines[$i]);
unset($object->lines[$i]->contact); unset($object->lines[$i]->contact);
@ -284,12 +285,14 @@ class DolibarrApi
$ok = 0; $ok = 0;
$i = 0; $nb = strlen($tmp); $i = 0; $nb = strlen($tmp);
$counter = 0; $counter = 0;
while ($i < $nb) while ($i < $nb) {
{ if ($tmp[$i] == '(') {
if ($tmp[$i] == '(') $counter++; $counter++;
if ($tmp[$i] == ')') $counter--; }
if ($counter < 0) if ($tmp[$i] == ')') {
{ $counter--;
}
if ($counter < 0) {
$error = "Bad sqlfilters=".$sqlfilters; $error = "Bad sqlfilters=".$sqlfilters;
dol_syslog($error, LOG_WARNING); dol_syslog($error, LOG_WARNING);
return false; return false;
@ -313,14 +316,17 @@ class DolibarrApi
global $db; global $db;
//dol_syslog("Convert matches ".$matches[1]); //dol_syslog("Convert matches ".$matches[1]);
if (empty($matches[1])) return ''; if (empty($matches[1])) {
return '';
}
$tmp = explode(':', $matches[1]); $tmp = explode(':', $matches[1]);
if (count($tmp) < 3) return ''; if (count($tmp) < 3) {
return '';
}
$tmpescaped = $tmp[2]; $tmpescaped = $tmp[2];
$regbis = array(); $regbis = array();
if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
{
$tmpescaped = "'".$db->escape($regbis[1])."'"; $tmpescaped = "'".$db->escape($regbis[1])."'";
} else { } else {
$tmpescaped = $db->escape($tmpescaped); $tmpescaped = $db->escape($tmpescaped);

View File

@ -35,7 +35,6 @@ use \Luracast\Restler\Resources;
use \Luracast\Restler\Defaults; use \Luracast\Restler\Defaults;
use \Luracast\Restler\RestException; use \Luracast\Restler\RestException;
/** /**
* Dolibarr API access class * Dolibarr API access class
* *
@ -95,23 +94,19 @@ class DolibarrApiAccess implements iAuthenticate
// api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
$api_key = ''; $api_key = '';
if (isset($_GET['api_key'])) // For backward compatibility if (isset($_GET['api_key'])) { // For backward compatibility
{
// TODO Add option to disable use of api key on url. Return errors if used. // TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['api_key']; $api_key = $_GET['api_key'];
} }
if (isset($_GET['DOLAPIKEY'])) if (isset($_GET['DOLAPIKEY'])) {
{
// TODO Add option to disable use of api key on url. Return errors if used. // TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['DOLAPIKEY']; // With GET method $api_key = $_GET['DOLAPIKEY']; // With GET method
} }
if (isset($_SERVER['HTTP_DOLAPIKEY'])) // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
{
$api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded) $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
} }
if ($api_key) if ($api_key) {
{
$userentity = 0; $userentity = 0;
$sql = "SELECT u.login, u.datec, u.api_key, "; $sql = "SELECT u.login, u.datec, u.api_key, ";
@ -121,17 +116,14 @@ class DolibarrApiAccess implements iAuthenticate
// TODO Check if 2 users has same API key. // TODO Check if 2 users has same API key.
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$login = $obj->login; $login = $obj->login;
$stored_key = $obj->api_key; $stored_key = $obj->api_key;
$userentity = $obj->entity; $userentity = $obj->entity;
if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) { // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user
{
$conf->entity = ($obj->entity ? $obj->entity : 1); $conf->entity = ($obj->entity ? $obj->entity : 1);
// We must also reload global conf to get params from the entity // We must also reload global conf to get params from the entity
dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING); dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING);
@ -147,8 +139,7 @@ class DolibarrApiAccess implements iAuthenticate
return false; return false;
} }
if (!$login) if (!$login) {
{
throw new RestException(503, 'Error when searching login user from api key'); throw new RestException(503, 'Error when searching login user from api key');
} }
$fuser = new User($this->db); $fuser = new User($this->db);
@ -173,7 +164,9 @@ class DolibarrApiAccess implements iAuthenticate
$userClass::setCacheIdentifier(static::$role); $userClass::setCacheIdentifier(static::$role);
Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess'; Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
$requirefortest = static::$requires; $requirefortest = static::$requires;
if (!is_array($requirefortest)) $requirefortest = explode(',', $requirefortest); if (!is_array($requirefortest)) {
$requirefortest = explode(',', $requirefortest);
}
return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin'; return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
} }

View File

@ -20,7 +20,6 @@
use Luracast\Restler\RestException; use Luracast\Restler\RestException;
use Luracast\Restler\Format\UploadFormat; use Luracast\Restler\Format\UploadFormat;
require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -36,7 +35,7 @@ class Documents extends DolibarrApi
/** /**
* @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object
*/ */
static $DOCUMENT_FIELDS = array( public static $DOCUMENT_FIELDS = array(
'modulepart' 'modulepart'
); );
@ -106,8 +105,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -148,8 +146,7 @@ class Documents extends DolibarrApi
} }
$outputlangs = $langs; $outputlangs = $langs;
if ($langcode && $langs->defaultlang != $langcode) if ($langcode && $langs->defaultlang != $langcode) {
{
$outputlangs = new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang($langcode); $outputlangs->setDefaultLang($langcode);
} }
@ -187,8 +184,7 @@ class Documents extends DolibarrApi
$templateused = ''; $templateused = '';
if ($modulepart == 'facture' || $modulepart == 'invoice') if ($modulepart == 'facture' || $modulepart == 'invoice') {
{
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$this->invoice = new Facture($this->db); $this->invoice = new Facture($this->db);
$result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -201,9 +197,7 @@ class Documents extends DolibarrApi
if ($result <= 0) { if ($result <= 0) {
throw new RestException(500, 'Error generating document'); throw new RestException(500, 'Error generating document');
} }
} } elseif ($modulepart == 'commande' || $modulepart == 'order') {
elseif ($modulepart == 'commande' || $modulepart == 'order')
{
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
$this->order = new Commande($this->db); $this->order = new Commande($this->db);
$result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -215,9 +209,7 @@ class Documents extends DolibarrApi
if ($result <= 0) { if ($result <= 0) {
throw new RestException(500, 'Error generating document'); throw new RestException(500, 'Error generating document');
} }
} } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
elseif ($modulepart == 'propal' || $modulepart == 'proposal')
{
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
$this->propal = new Propal($this->db); $this->propal = new Propal($this->db);
$result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -236,8 +228,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -278,8 +269,7 @@ class Documents extends DolibarrApi
$recursive = 0; $recursive = 0;
$type = 'files'; $type = 'files';
if ($modulepart == 'societe' || $modulepart == 'thirdparty') if ($modulepart == 'societe' || $modulepart == 'thirdparty') {
{
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
if (!DolibarrApiAccess::$user->rights->societe->lire) { if (!DolibarrApiAccess::$user->rights->societe->lire) {
@ -293,9 +283,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id;
} } elseif ($modulepart == 'user') {
elseif ($modulepart == 'user')
{
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
// Can get doc if has permission to read all user or if it is user itself // Can get doc if has permission to read all user or if it is user itself
@ -310,9 +298,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id; $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id;
} } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
if (!DolibarrApiAccess::$user->rights->adherent->lire) { if (!DolibarrApiAccess::$user->rights->adherent->lire) {
@ -326,9 +312,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member'); $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member');
} } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
elseif ($modulepart == 'propal' || $modulepart == 'proposal')
{
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) { if (!DolibarrApiAccess::$user->rights->propal->lire) {
@ -342,9 +326,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal'); $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
} } elseif ($modulepart == 'commande' || $modulepart == 'order') {
elseif ($modulepart == 'commande' || $modulepart == 'order')
{
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
if (!DolibarrApiAccess::$user->rights->commande->lire) { if (!DolibarrApiAccess::$user->rights->commande->lire) {
@ -358,9 +340,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande'); $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
} } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
elseif ($modulepart == 'shipment' || $modulepart == 'expedition')
{
require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
if (!DolibarrApiAccess::$user->rights->expedition->lire) { if (!DolibarrApiAccess::$user->rights->expedition->lire) {
@ -374,9 +354,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment'); $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
} } elseif ($modulepart == 'facture' || $modulepart == 'invoice') {
elseif ($modulepart == 'facture' || $modulepart == 'invoice')
{
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
if (!DolibarrApiAccess::$user->rights->facture->lire) { if (!DolibarrApiAccess::$user->rights->facture->lire) {
@ -390,9 +368,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice'); $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
} } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
$modulepart = 'supplier_invoice'; $modulepart = 'supplier_invoice';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
@ -408,9 +384,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref); $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'produit' || $modulepart == 'product') {
elseif ($modulepart == 'produit' || $modulepart == 'product')
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
if (!DolibarrApiAccess::$user->rights->produit->lire) { if (!DolibarrApiAccess::$user->rights->produit->lire) {
@ -426,9 +400,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
} } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') {
elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event')
{
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) { if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) {
@ -442,9 +414,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'expensereport') {
elseif ($modulepart == 'expensereport')
{
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) { if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) {
@ -458,9 +428,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'categorie' || $modulepart == 'category') {
elseif ($modulepart == 'categorie' || $modulepart == 'category')
{
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
if (!DolibarrApiAccess::$user->rights->categorie->lire) { if (!DolibarrApiAccess::$user->rights->categorie->lire) {
@ -561,8 +529,7 @@ class Documents extends DolibarrApi
var_dump($filecontent); var_dump($filecontent);
exit;*/ exit;*/
if (empty($modulepart)) if (empty($modulepart)) {
{
throw new RestException(400, 'Modulepart not provided.'); throw new RestException(400, 'Modulepart not provided.');
} }
@ -571,41 +538,39 @@ class Documents extends DolibarrApi
} }
$newfilecontent = ''; $newfilecontent = '';
if (empty($fileencoding)) $newfilecontent = $filecontent; if (empty($fileencoding)) {
if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); $newfilecontent = $filecontent;
}
if ($fileencoding == 'base64') {
$newfilecontent = base64_decode($filecontent);
}
$original_file = dol_sanitizeFileName($filename); $original_file = dol_sanitizeFileName($filename);
// Define $uploadir // Define $uploadir
$object = null; $object = null;
$entity = DolibarrApiAccess::$user->entity; $entity = DolibarrApiAccess::$user->entity;
if (empty($entity)) $entity = 1; if (empty($entity)) {
$entity = 1;
}
if ($ref) if ($ref) {
{
$tmpreldir = ''; $tmpreldir = '';
if ($modulepart == 'facture' || $modulepart == 'invoice') if ($modulepart == 'facture' || $modulepart == 'invoice') {
{
$modulepart = 'facture'; $modulepart = 'facture';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$object = new Facture($this->db); $object = new Facture($this->db);
} } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
$modulepart = 'supplier_invoice'; $modulepart = 'supplier_invoice';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
$object = new FactureFournisseur($this->db); $object = new FactureFournisseur($this->db);
} } elseif ($modulepart == 'project') {
elseif ($modulepart == 'project')
{
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$object = new Project($this->db); $object = new Project($this->db);
} } elseif ($modulepart == 'task' || $modulepart == 'project_task') {
elseif ($modulepart == 'task' || $modulepart == 'project_task')
{
$modulepart = 'project_task'; $modulepart = 'project_task';
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
@ -614,36 +579,26 @@ class Documents extends DolibarrApi
$task_result = $object->fetch('', $ref); $task_result = $object->fetch('', $ref);
// Fetching the tasks project is required because its out_dir might be a sub-directory of the project // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
if ($task_result > 0) if ($task_result > 0) {
{
$project_result = $object->fetch_projet(); $project_result = $object->fetch_projet();
if ($project_result >= 0) if ($project_result >= 0) {
{
$tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; $tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
} }
} else { } else {
throw new RestException(500, 'Error while fetching Task '.$ref); throw new RestException(500, 'Error while fetching Task '.$ref);
} }
} } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
$object = new Product($this->db); $object = new Product($this->db);
} } elseif ($modulepart == 'expensereport') {
elseif ($modulepart == 'expensereport')
{
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
$object = new ExpenseReport($this->db); $object = new ExpenseReport($this->db);
} } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
$modulepart = 'adherent'; $modulepart = 'adherent';
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
$object = new Adherent($this->db); $object = new Adherent($this->db);
} } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') {
elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale')
{
$modulepart = 'propale'; $modulepart = 'propale';
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
$object = new Propal($this->db); $object = new Propal($this->db);
@ -652,16 +607,12 @@ class Documents extends DolibarrApi
throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
} }
if (is_object($object)) if (is_object($object)) {
{
$result = $object->fetch('', $ref); $result = $object->fetch('', $ref);
if ($result == 0) if ($result == 0) {
{
throw new RestException(404, "Object with ref '".$ref."' was not found."); throw new RestException(404, "Object with ref '".$ref."' was not found.");
} } elseif ($result < 0) {
elseif ($result < 0)
{
throw new RestException(500, 'Error while fetching object: '.$object->error); throw new RestException(500, 'Error while fetching object: '.$object->error);
} }
} }
@ -681,13 +632,16 @@ class Documents extends DolibarrApi
$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write'); $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
$upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir $upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir
if (empty($upload_dir) || $upload_dir == '/') if (empty($upload_dir) || $upload_dir == '/') {
{
throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.');
} }
} else { } else {
if ($modulepart == 'invoice') $modulepart = 'facture'; if ($modulepart == 'invoice') {
if ($modulepart == 'member') $modulepart = 'adherent'; $modulepart = 'facture';
}
if ($modulepart == 'member') {
$modulepart = 'adherent';
}
$relativefile = $subdir; $relativefile = $subdir;
$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write'); $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
@ -794,8 +748,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -825,8 +778,9 @@ class Documents extends DolibarrApi
// phpcs:enable // phpcs:enable
$result = array(); $result = array();
foreach (Documents::$DOCUMENT_FIELDS as $field) { foreach (Documents::$DOCUMENT_FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$result[$field] = $data[$field]; $result[$field] = $data[$field];
} }
return $result; return $result;

View File

@ -61,14 +61,16 @@ class Login
// TODO Remove the API login. The token must be generated from backoffice only. // TODO Remove the API login. The token must be generated from backoffice only.
// Authentication mode // Authentication mode
if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'dolibarr'; if (empty($dolibarr_main_authentication)) {
$dolibarr_main_authentication = 'dolibarr';
}
// Authentication mode: forceuser // Authentication mode: forceuser
if ($dolibarr_main_authentication == 'forceuser') if ($dolibarr_main_authentication == 'forceuser') {
{ if (empty($dolibarr_auto_user)) {
if (empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; $dolibarr_auto_user = 'auto';
if ($dolibarr_auto_user != $login) }
{ if ($dolibarr_auto_user != $login) {
dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
} }
@ -77,16 +79,16 @@ class Login
// Set authmode // Set authmode
$authmode = explode(',', $dolibarr_main_authentication); $authmode = explode(',', $dolibarr_main_authentication);
if ($entity != '' && !is_numeric($entity)) if ($entity != '' && !is_numeric($entity)) {
{
throw new RestException(403, "Bad value for entity, must be the numeric ID of company."); throw new RestException(403, "Bad value for entity, must be the numeric ID of company.");
} }
if ($entity == '') $entity = 1; if ($entity == '') {
$entity = 1;
}
include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api');
if (empty($login)) if (empty($login)) {
{
throw new RestException(403, 'Access denied'); throw new RestException(403, 'Access denied');
} }
@ -94,17 +96,14 @@ class Login
$tmpuser = new User($this->db); $tmpuser = new User($this->db);
$tmpuser->fetch(0, $login, 0, 0, $entity); $tmpuser->fetch(0, $login, 0, 0, $entity);
if (empty($tmpuser->id)) if (empty($tmpuser->id)) {
{
throw new RestException(500, 'Failed to load user'); throw new RestException(500, 'Failed to load user');
} }
// Renew the hash // Renew the hash
if (empty($tmpuser->api_key) || $reset) if (empty($tmpuser->api_key) || $reset) {
{
$tmpuser->getrights(); $tmpuser->getrights();
if (empty($tmpuser->rights->user->self->creer)) if (empty($tmpuser->rights->user->self->creer)) {
{
throw new RestException(403, 'User need write permission on itself to reset its API token'); throw new RestException(403, 'User need write permission on itself to reset its API token');
} }
@ -118,8 +117,7 @@ class Login
dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
$result = $this->db->query($sql); $result = $this->db->query($sql);
if (!$result) if (!$result) {
{
throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror()); throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
} }
} else { } else {

View File

@ -26,22 +26,42 @@
use Luracast\Restler\Format\UploadFormat; use Luracast\Restler\Format\UploadFormat;
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test if (!defined('NOCSRFCHECK')) {
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu }
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test
if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) }
if (!defined("NOSESSION")) define("NOSESSION", '1'); if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library
}
if (!defined("NOLOGIN")) {
define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
}
if (!defined("NOSESSION")) {
define("NOSESSION", '1');
}
// Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used. // Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used.
if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']); if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) {
define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
}
$res = 0; $res = 0;
if (!$res && file_exists("../main.inc.php")) $res = include '../main.inc.php'; if (!$res && file_exists("../main.inc.php")) {
if (!$res) die("Include of main fails"); $res = include '../main.inc.php';
}
if (!$res) {
die("Include of main fails");
}
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php'; require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
@ -61,14 +81,12 @@ if (preg_match('/api\/index\.php$/', $url)) { // sometimes $_SERVER['PHP_SELF']
$url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO']; $url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO'];
} }
// Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases) // Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases)
if (!empty($conf->global->MAIN_NGINX_FIX)) if (!empty($conf->global->MAIN_NGINX_FIX)) {
{
$url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF']; $url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF'];
} }
// Enable and test if module Api is enabled // Enable and test if module Api is enabled
if (empty($conf->global->MAIN_MODULE_API)) if (empty($conf->global->MAIN_MODULE_API)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
@ -78,8 +96,7 @@ if (empty($conf->global->MAIN_MODULE_API))
} }
// Test if explorer is not disabled // Test if explorer is not disabled
if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>'; print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>';
@ -112,8 +129,7 @@ preg_match('/index\.php\/([^\/]+)(.*)$/', $url, $reg);
// using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned. // using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned.
// So we force refresh to each call. // So we force refresh to each call.
$refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false); $refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false);
if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
{
$refreshcache = true; $refreshcache = true;
} }
@ -132,12 +148,10 @@ UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain',
// Restrict API to some IPs // Restrict API to some IPs
if (!empty($conf->global->API_RESTRICT_ON_IP)) if (!empty($conf->global->API_RESTRICT_ON_IP)) {
{
$allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP); $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP);
$ipremote = getUserRemoteIP(); $ipremote = getUserRemoteIP();
if (!in_array($ipremote, $allowedip)) if (!in_array($ipremote, $allowedip)) {
{
dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP); dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP);
print 'APIs are not allowed from the IP '.$ipremote; print 'APIs are not allowed from the IP '.$ipremote;
header('HTTP/1.1 503 API not allowed from your IP '.$ipremote); header('HTTP/1.1 503 API not allowed from your IP '.$ipremote);
@ -148,65 +162,64 @@ if (!empty($conf->global->API_RESTRICT_ON_IP))
// Call Explorer file for all APIs definitions (this part is slow) // Call Explorer file for all APIs definitions (this part is slow)
if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
{
// Scan all API files to load them // Scan all API files to load them
$listofapis = array(); $listofapis = array();
$modulesdir = dolGetModulesDirs(); $modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
// Search available module // Search available module
dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files"); dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
$handle = @opendir(dol_osencode($dir)); $handle = @opendir(dol_osencode($dir));
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false)
{
$regmod = array(); $regmod = array();
if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) {
{
$module = strtolower($regmod[1]); $module = strtolower($regmod[1]);
$moduledirforclass = getModuleDirForApiClass($module); $moduledirforclass = getModuleDirForApiClass($module);
$modulenameforenabled = $module; $modulenameforenabled = $module;
if ($module == 'propale') { $modulenameforenabled = 'propal'; } if ($module == 'propale') {
if ($module == 'supplierproposal') { $modulenameforenabled = 'supplier_proposal'; } $modulenameforenabled = 'propal';
if ($module == 'ficheinter') { $modulenameforenabled = 'ficheinter'; } }
if ($module == 'supplierproposal') {
$modulenameforenabled = 'supplier_proposal';
}
if ($module == 'ficheinter') {
$modulenameforenabled = 'ficheinter';
}
dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass); dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
// Defined if module is enabled // Defined if module is enabled
$enabled = true; $enabled = true;
if (empty($conf->$modulenameforenabled->enabled)) $enabled = false; if (empty($conf->$modulenameforenabled->enabled)) {
$enabled = false;
}
if ($enabled) if ($enabled) {
{
// If exists, load the API class for enable module // If exists, load the API class for enable module
// Search files named api_<object>.class.php into /htdocs/<module>/class directory // Search files named api_<object>.class.php into /htdocs/<module>/class directory
// @todo : use getElementProperties() function ? // @todo : use getElementProperties() function ?
$dir_part = dol_buildpath('/'.$moduledirforclass.'/class/'); $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
$handle_part = @opendir(dol_osencode($dir_part)); $handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part)) if (is_resource($handle_part)) {
{ while (($file_searched = readdir($handle_part)) !== false) {
while (($file_searched = readdir($handle_part)) !== false) if ($file_searched == 'api_access.class.php') {
{ continue;
if ($file_searched == 'api_access.class.php') continue; }
$regapi = array(); $regapi = array();
if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
{
$classname = ucwords($regapi[1]); $classname = ucwords($regapi[1]);
$classname = str_replace('_', '', $classname); $classname = str_replace('_', '', $classname);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname.'Api')) if (class_exists($classname.'Api')) {
{
//dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched); //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
$listofapis[strtolower($classname.'Api')] = $classname.'Api'; $listofapis[strtolower($classname.'Api')] = $classname.'Api';
} elseif (class_exists($classname)) } elseif (class_exists($classname)) {
{
//dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched); //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
$listofapis[strtolower($classname)] = $classname; $listofapis[strtolower($classname)] = $classname;
} else { } else {
@ -224,8 +237,7 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $
// Sort the classes before adding them to Restler. // Sort the classes before adding them to Restler.
// The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
asort($listofapis); asort($listofapis);
foreach ($listofapis as $apiname => $classname) foreach ($listofapis as $apiname => $classname) {
{
$api->r->addAPIClass($classname, $apiname); $api->r->addAPIClass($classname, $apiname);
} }
//var_dump($api->r); //var_dump($api->r);
@ -233,11 +245,9 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $
// Call one APIs or one definition of an API // Call one APIs or one definition of an API
$regbis = array(); $regbis = array();
if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) {
{
$moduleobject = $reg[1]; $moduleobject = $reg[1];
if ($moduleobject == 'explorer') // If we call page to explore details of a service if ($moduleobject == 'explorer') { // If we call page to explore details of a service
{
$moduleobject = $regbis[2]; $moduleobject = $regbis[2];
} }
@ -248,21 +258,27 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass); dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass);
$tmpmodule = $moduleobject; $tmpmodule = $moduleobject;
if ($tmpmodule != 'api') if ($tmpmodule != 'api') {
$tmpmodule = preg_replace('/api$/i', '', $tmpmodule); $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
}
$classfile = str_replace('_', '', $tmpmodule); $classfile = str_replace('_', '', $tmpmodule);
// Special cases that does not match name rules conventions // Special cases that does not match name rules conventions
if ($moduleobject == 'supplierproposals') if ($moduleobject == 'supplierproposals') {
$classfile = 'supplier_proposals'; $classfile = 'supplier_proposals';
if ($moduleobject == 'supplierorders') }
if ($moduleobject == 'supplierorders') {
$classfile = 'supplier_orders'; $classfile = 'supplier_orders';
if ($moduleobject == 'supplierinvoices') }
if ($moduleobject == 'supplierinvoices') {
$classfile = 'supplier_invoices'; $classfile = 'supplier_invoices';
if ($moduleobject == 'ficheinter') }
if ($moduleobject == 'ficheinter') {
$classfile = 'interventions'; $classfile = 'interventions';
if ($moduleobject == 'interventions') }
if ($moduleobject == 'interventions') {
$classfile = 'interventions'; $classfile = 'interventions';
}
$dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2); $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2);
@ -271,8 +287,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname); dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname);
$res = false; $res = false;
if ($dir_part_file) if ($dir_part_file) {
$res = include_once $dir_part_file; $res = include_once $dir_part_file;
}
if (!$res) { if (!$res) {
dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING); dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
print 'API not found (failed to include API file)'; print 'API not found (failed to include API file)';
@ -281,9 +298,10 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
exit(0); exit(0);
} }
if (class_exists($classname)) if (class_exists($classname)) {
$api->r->addAPIClass($classname); $api->r->addAPIClass($classname);
} }
}
//var_dump($api->r->apiVersionMap); //var_dump($api->r->apiVersionMap);

View File

@ -41,10 +41,11 @@ $action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
if (GETPOST('actioncode', 'array')) if (GETPOST('actioncode', 'array')) {
{
$actioncode = GETPOST('actioncode', 'array', 3); $actioncode = GETPOST('actioncode', 'array', 3);
if (!count($actioncode)) $actioncode = '0'; if (!count($actioncode)) {
$actioncode = '0';
}
} else { } else {
$actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
} }
@ -59,12 +60,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = 'a.datep,a.id'; if (!$sortfield) {
if (!$sortorder) $sortorder = 'DESC'; $sortfield = 'a.datep,a.id';
}
if (!$sortorder) {
$sortorder = 'DESC';
}
// Initialize technical objects // Initialize technical objects
$object = new BOM($db); $object = new BOM($db);
@ -76,7 +83,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id;
}
@ -86,20 +95,19 @@ if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->
$parameters = array('id'=>$socid); $parameters = array('id'=>$socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Cancel // Cancel
if (GETPOST('cancel', 'alpha') && !empty($backtopage)) if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} }
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$actioncode = ''; $actioncode = '';
$search_agenda_label = ''; $search_agenda_label = '';
} }
@ -115,14 +123,15 @@ $contactstatic = new Contact($db);
$form = new Form($db); $form = new Form($db);
if ($object->id > 0) if ($object->id > 0) {
{
$title = $langs->trans("Agenda"); $title = $langs->trans("Agenda");
//if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title;
$help_url = ''; $help_url = '';
llxHeader('', $title, $help_url); llxHeader('', $title, $help_url);
if (!empty($conf->notification->enabled)) $langs->load("mails"); if (!empty($conf->notification->enabled)) {
$langs->load("mails");
}
$head = bomPrepareHead($object); $head = bomPrepareHead($object);
@ -196,10 +205,11 @@ if ($object->id > 0)
$out = '&origin='.$object->element.'&originid='.$object->id; $out = '&origin='.$object->element.'&originid='.$object->id;
$permok = $user->rights->agenda->myactions->create; $permok = $user->rights->agenda->myactions->create;
if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) {
{
//$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
if (get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id; if (get_class($objthirdparty) == 'Societe') {
$out .= '&amp;socid='.$objthirdparty->id;
}
$out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1';
//$out.=$langs->trans("AddAnAction").' '; //$out.=$langs->trans("AddAnAction").' ';
//$out.=img_picto($langs->trans("AddAnAction"),'filenew'); //$out.=img_picto($langs->trans("AddAnAction"),'filenew');
@ -209,10 +219,8 @@ if ($object->id > 0)
print '<div class="tabsAction">'; print '<div class="tabsAction">';
if (!empty($conf->agenda->enabled)) if (!empty($conf->agenda->enabled)) {
{ if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) {
if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create))
{
print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>'; print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>';
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>';
@ -221,11 +229,14 @@ if ($object->id > 0)
print '</div>'; print '</div>';
if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
{
$param = '&id='.$object->id.'&socid='.$socid; $param = '&id='.$object->id.'&socid='.$socid;
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
//print load_fiche_titre($langs->trans("ActionsOnBom"), '', ''); //print load_fiche_titre($langs->trans("ActionsOnBom"), '', '');

View File

@ -59,12 +59,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha')) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
if (empty($action) && empty($id) && empty($ref)) $action = 'view'; if (empty($action) && empty($id) && empty($ref)) {
$action = 'view';
}
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
@ -88,18 +91,22 @@ $upload_dir = $conf->bom->multidir_output[isset($object->entity) ? $object->enti
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
$error = 0; $error = 0;
$backurlforlist = DOL_URL_ROOT.'/bom/bom_list.php'; $backurlforlist = DOL_URL_ROOT.'/bom/bom_list.php';
if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && empty($id))) {
if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
else $backtopage = dol_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); $backtopage = $backurlforlist;
} else {
$backtopage = dol_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
}
} }
} }
@ -127,8 +134,7 @@ if (empty($reshook))
include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
// Add line // Add line
if ($action == 'addline' && $user->rights->bom->write) if ($action == 'addline' && $user->rights->bom->write) {
{
$langs->load('errors'); $langs->load('errors');
$error = 0; $error = 0;
@ -153,8 +159,7 @@ if (empty($reshook))
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$bomline = new BOMLine($db); $bomline = new BOMLine($db);
$bomline->fk_bom = $id; $bomline->fk_bom = $id;
$bomline->fk_product = $idprod; $bomline->fk_product = $idprod;
@ -187,8 +192,7 @@ if (empty($reshook))
} }
// Add line // Add line
if ($action == 'updateline' && $user->rights->bom->write) if ($action == 'updateline' && $user->rights->bom->write) {
{
$langs->load('errors'); $langs->load('errors');
$error = 0; $error = 0;
@ -211,8 +215,7 @@ if (empty($reshook))
$bomline->efficiency = $efficiency; $bomline->efficiency = $efficiency;
$result = $bomline->update($user); $result = $bomline->update($user);
if ($result <= 0) if ($result <= 0) {
{
setEventMessages($bomline->error, $bomline->errors, 'errors'); setEventMessages($bomline->error, $bomline->errors, 'errors');
$action = ''; $action = '';
} else { } else {
@ -255,8 +258,7 @@ jQuery(document).ready(function() {
// Part to create // Part to create
if ($action == 'create') if ($action == 'create') {
{
print load_fiche_titre($langs->trans("NewBOM"), '', 'bom'); print load_fiche_titre($langs->trans("NewBOM"), '', 'bom');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@ -288,8 +290,7 @@ if ($action == 'create')
} }
// Part to edit record // Part to edit record
if (($id || $ref) && $action == 'edit') if (($id || $ref) && $action == 'edit') {
{
print load_fiche_titre($langs->trans("BillOfMaterials"), '', 'cubes'); print load_fiche_titre($langs->trans("BillOfMaterials"), '', 'cubes');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@ -322,8 +323,7 @@ if (($id || $ref) && $action == 'edit')
} }
// Part to show record // Part to show record
if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
{
$res = $object->fetch_optionals(); $res = $object->fetch_optionals();
$head = bomPrepareHead($object); $head = bomPrepareHead($object);
@ -332,19 +332,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$formconfirm = ''; $formconfirm = '';
// Confirmation to delete // Confirmation to delete
if ($action == 'delete') if ($action == 'delete') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1);
} }
// Confirmation to delete line // Confirmation to delete line
if ($action == 'deleteline') if ($action == 'deleteline') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
} }
// Confirmation of validation // Confirmation of validation
if ($action == 'validate') if ($action == 'validate') {
{
// We check that object has a temporary ref // We check that object has a temporary ref
$ref = substr($object->ref, 1, 4); $ref = substr($object->ref, 1, 4);
if ($ref == 'PROV') { if ($ref == 'PROV') {
@ -364,13 +361,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->bom->enabled)) if (!empty($conf->bom->enabled)) {
{
$langs->load("mrp"); $langs->load("mrp");
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
$forcecombo = 0; $forcecombo = 0;
if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy if ($conf->browser->name == 'ie') {
$forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
}
$formquestion = array( $formquestion = array(
// 'text' => $langs->trans("ConfirmClone"), // 'text' => $langs->trans("ConfirmClone"),
// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
@ -382,8 +380,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of closing // Confirmation of closing
if ($action == 'close') if ($action == 'close') {
{
$text = $langs->trans('ConfirmCloseBom', $object->ref); $text = $langs->trans('ConfirmCloseBom', $object->ref);
/*if (! empty($conf->notification->enabled)) /*if (! empty($conf->notification->enabled))
{ {
@ -394,13 +391,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->bom->enabled)) if (!empty($conf->bom->enabled)) {
{
$langs->load("mrp"); $langs->load("mrp");
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
$forcecombo = 0; $forcecombo = 0;
if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy if ($conf->browser->name == 'ie') {
$forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
}
$formquestion = array( $formquestion = array(
// 'text' => $langs->trans("ConfirmClone"), // 'text' => $langs->trans("ConfirmClone"),
// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
@ -412,8 +410,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of reopen // Confirmation of reopen
if ($action == 'reopen') if ($action == 'reopen') {
{
$text = $langs->trans('ConfirmReopenBom', $object->ref); $text = $langs->trans('ConfirmReopenBom', $object->ref);
/*if (! empty($conf->notification->enabled)) /*if (! empty($conf->notification->enabled))
{ {
@ -424,13 +421,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->bom->enabled)) if (!empty($conf->bom->enabled)) {
{
$langs->load("mrp"); $langs->load("mrp");
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
$forcecombo = 0; $forcecombo = 0;
if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy if ($conf->browser->name == 'ie') {
$forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
}
$formquestion = array( $formquestion = array(
// 'text' => $langs->trans("ConfirmClone"), // 'text' => $langs->trans("ConfirmClone"),
// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
@ -449,8 +447,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of action xxxx // Confirmation of action xxxx
if ($action == 'setdraft') if ($action == 'setdraft') {
{
$text = $langs->trans('ConfirmSetToDraft', $object->ref); $text = $langs->trans('ConfirmSetToDraft', $object->ref);
$formquestion = array(); $formquestion = array();
@ -460,8 +457,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Call Hook formConfirm // Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; if (empty($reshook)) {
elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; $formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm // Print form confirm
print $formconfirm; print $formconfirm;
@ -544,8 +544,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
* Lines * Lines
*/ */
if (!empty($object->table_element_line)) if (!empty($object->table_element_line)) {
{
print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '').'" method="POST"> print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '').'" method="POST">
<input type="hidden" name="token" value="' . newToken().'"> <input type="hidden" name="token" value="' . newToken().'">
<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'"> <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
@ -558,21 +557,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
{
print '<table id="tablelines" class="noborder noshadow" width="100%">'; print '<table id="tablelines" class="noborder noshadow" width="100%">';
} }
if (!empty($object->lines)) if (!empty($object->lines)) {
{
$object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1, '/bom/tpl'); $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1, '/bom/tpl');
} }
// Form to add new line // Form to add new line
if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') {
{ if ($action != 'editline') {
if ($action != 'editline')
{
// Add products/services form // Add products/services form
$object->formAddObjectLine(1, $mysoc, null, '/bom/tpl'); $object->formAddObjectLine(1, $mysoc, null, '/bom/tpl');
@ -581,8 +576,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
} }
if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
{
print '</table>'; print '</table>';
} }
print '</div>'; print '</div>';
@ -597,29 +591,26 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<div class="tabsAction">'."\n"; print '<div class="tabsAction">'."\n";
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $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 ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Send // Send
//if (empty($user->socid)) { //if (empty($user->socid)) {
// print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n"; // print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n";
//} //}
// Back to draft // Back to draft
if ($object->status == $object::STATUS_VALIDATED) if ($object->status == $object::STATUS_VALIDATED) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=setdraft&token='.newToken().'">'.$langs->trans("SetToDraft").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=setdraft&token='.newToken().'">'.$langs->trans("SetToDraft").'</a>';
} }
} }
// Modify // Modify
if ($object->status == $object::STATUS_DRAFT) if ($object->status == $object::STATUS_DRAFT) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit&amp;token='.newToken().'">'.$langs->trans("Modify").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit&amp;token='.newToken().'">'.$langs->trans("Modify").'</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
@ -627,12 +618,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Validate // Validate
if ($object->status == $object::STATUS_DRAFT) if ($object->status == $object::STATUS_DRAFT) {
{ if ($permissiontoadd) {
if ($permissiontoadd) if (is_array($object->lines) && count($object->lines) > 0) {
{
if (is_array($object->lines) && count($object->lines) > 0)
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=validate&amp;token='.newToken().'">'.$langs->trans("Validate").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=validate&amp;token='.newToken().'">'.$langs->trans("Validate").'</a>';
} else { } else {
$langs->load("errors"); $langs->load("errors");
@ -642,29 +630,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Re-open // Re-open
if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) {
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen">'.$langs->trans("ReOpen").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen">'.$langs->trans("ReOpen").'</a>';
} }
// Create MO // Create MO
if ($conf->mrp->enabled) if ($conf->mrp->enabled) {
{ if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write)) {
if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write))
{
print '<a class="butAction" href="'.DOL_URL_ROOT.'/mrp/mo_card.php?action=create&fk_bom='.$object->id.'&backtopageforcancel='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id).'">'.$langs->trans("CreateMO").'</a>'; print '<a class="butAction" href="'.DOL_URL_ROOT.'/mrp/mo_card.php?action=create&fk_bom='.$object->id.'&backtopageforcancel='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id).'">'.$langs->trans("CreateMO").'</a>';
} }
} }
// Clone // Clone
if ($permissiontoadd) if ($permissiontoadd) {
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=clone&object=bom">'.$langs->trans("ToClone").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=clone&object=bom">'.$langs->trans("ToClone").'</a>';
} }
// Close / Cancel // Close / Cancel
if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) {
{
print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=close">'.$langs->trans("Disable").'</a>'; print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=close">'.$langs->trans("Disable").'</a>';
} }
@ -682,8 +665,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
*/ */
if ($permissiontodelete) if ($permissiontodelete) {
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
@ -698,8 +680,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$action = 'presend'; $action = 'presend';
} }
if ($action != 'presend') if ($action != 'presend') {
{
print '<div class="fichecenter"><div class="fichehalfleft">'; print '<div class="fichecenter"><div class="fichehalfleft">';
print '<a name="builddoc"></a>'; // ancre print '<a name="builddoc"></a>'; // ancre
@ -734,7 +715,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
//Select mail models is same action as presend //Select mail models is same action as presend
if (GETPOST('modelselected')) $action = 'presend'; if (GETPOST('modelselected')) {
$action = 'presend';
}
// Presend form // Presend form
$modelmail = 'bom'; $modelmail = 'bom';

View File

@ -50,12 +50,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "name";
}
//if (! $sortfield) $sortfield="position_name"; //if (! $sortfield) $sortfield="position_name";
// Initialize technical objects // Initialize technical objects
@ -69,7 +75,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object); if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object);
}
/* /*
@ -90,8 +98,7 @@ $help_url = '';
//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url); llxHeader('', $title, $help_url);
if ($object->id) if ($object->id) {
{
/* /*
* Show tabs * Show tabs
*/ */
@ -103,8 +110,7 @@ if ($object->id)
// Build file list // Build file list
$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
$totalsize = 0; $totalsize = 0;
foreach ($filearray as $key => $file) foreach ($filearray as $key => $file) {
{
$totalsize += $file['size']; $totalsize += $file['size'];
} }

View File

@ -48,7 +48,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@ -67,14 +69,20 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
}
if (!$sortorder) {
$sortorder = "ASC";
}
// Security check // Security check
if (empty($conf->bom->enabled)) accessforbidden('Module not enabled'); if (empty($conf->bom->enabled)) {
accessforbidden('Module not enabled');
}
$socid = 0; $socid = 0;
if ($user->socid > 0) // Protection if external user if ($user->socid > 0) {
{ // Protection if external user
//$socid = $user->socid; //$socid = $user->socid;
accessforbidden(); accessforbidden();
} }
@ -83,30 +91,31 @@ if ($user->socid > 0) // Protection if external user
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha') !== '') {
if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array(); $fieldstosearchall = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if ($val['searchall']) {
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; $fieldstosearchall['t.'.$key] = $val['label'];
}
} }
// Definition of fields for list // Definition of fields for list
$arrayfields = array(); $arrayfields = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
// If $val['visible']==0, then we never show the field // If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); if (!empty($val['visible'])) {
$arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']);
}
} }
// Extra fields // Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
{
if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
$arrayfields["ef.".$key] = array( $arrayfields["ef.".$key] = array(
'label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
@ -129,31 +138,33 @@ $permissiontodelete = $user->rights->bom->delete;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{ foreach ($object->fields as $key => $val) {
foreach ($object->fields as $key => $val)
{
$search[$key] = ''; $search[$key] = '';
} }
$toselect = ''; $toselect = '';
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@ -167,22 +178,17 @@ if (empty($reshook))
// Validate records // Validate records
if (!$error && $massaction == 'disable' && $permissiontoadd) if (!$error && $massaction == 'disable' && $permissiontoadd) {
{
$objecttmp = new $objectclass($db); $objecttmp = new $objectclass($db);
if (!$error) if (!$error) {
{
$db->begin(); $db->begin();
$nbok = 0; $nbok = 0;
foreach ($toselect as $toselectid) foreach ($toselect as $toselectid) {
{
$result = $objecttmp->fetch($toselectid); $result = $objecttmp->fetch($toselectid);
if ($result > 0) if ($result > 0) {
{ if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) {
if ($objecttmp->status != $objecttmp::STATUS_VALIDATED)
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorObjectMustHaveStatusActiveToBeDisabled", $objecttmp->ref), null, 'errors'); setEventMessages($langs->trans("ErrorObjectMustHaveStatusActiveToBeDisabled", $objecttmp->ref), null, 'errors');
$error++; $error++;
@ -191,12 +197,13 @@ if (empty($reshook))
// Can be 'cancel()' or 'close()' // Can be 'cancel()' or 'close()'
$result = $objecttmp->cancel($user); $result = $objecttmp->cancel($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
break; break;
} else $nbok++; } else {
$nbok++;
}
} else { } else {
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
@ -204,10 +211,12 @@ if (empty($reshook))
} }
} }
if (!$error) if (!$error) {
{ if ($nbok > 1) {
if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); } else {
setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
}
$db->commit(); $db->commit();
} else { } else {
$db->rollback(); $db->rollback();
@ -217,22 +226,17 @@ if (empty($reshook))
} }
// Validate records // Validate records
if (!$error && $massaction == 'enable' && $permissiontoadd) if (!$error && $massaction == 'enable' && $permissiontoadd) {
{
$objecttmp = new $objectclass($db); $objecttmp = new $objectclass($db);
if (!$error) if (!$error) {
{
$db->begin(); $db->begin();
$nbok = 0; $nbok = 0;
foreach ($toselect as $toselectid) foreach ($toselect as $toselectid) {
{
$result = $objecttmp->fetch($toselectid); $result = $objecttmp->fetch($toselectid);
if ($result > 0) if ($result > 0) {
{ if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED) {
if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED)
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated", $objecttmp->ref), null, 'errors'); setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated", $objecttmp->ref), null, 'errors');
$error++; $error++;
@ -241,12 +245,13 @@ if (empty($reshook))
// Can be 'cancel()' or 'close()' // Can be 'cancel()' or 'close()'
$result = $objecttmp->validate($user); $result = $objecttmp->validate($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
break; break;
} else $nbok++; } else {
$nbok++;
}
} else { } else {
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
@ -254,10 +259,12 @@ if (empty($reshook))
} }
} }
if (!$error) if (!$error) {
{ if ($nbok > 1) {
if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); } else {
setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
}
$db->commit(); $db->commit();
} else { } else {
$db->rollback(); $db->rollback();
@ -284,13 +291,14 @@ $title = $langs->trans('ListOfBOMs');
// Build and execute select // Build and execute select
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$sql = 'SELECT '; $sql = 'SELECT ';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$sql .= 't.'.$key.', '; $sql .= 't.'.$key.', ';
} }
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@ -298,21 +306,33 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje
$sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
$sql = preg_replace('/,\s*$/', '', $sql); $sql = preg_replace('/,\s*$/', '', $sql);
$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
else $sql .= " WHERE 1 = 1"; }
foreach ($search as $key => $val) if ($object->ismultientitymanaged == 1) {
{ $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
if ($key == 'status' && $search[$key] == -1) continue; } else {
$sql .= " WHERE 1 = 1";
}
foreach ($search as $key => $val) {
if ($key == 'status' && $search[$key] == -1) {
continue;
}
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if (strpos($object->fields[$key]['type'], 'integer:') === 0) { if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
if ($search[$key] == '-1') $search[$key] = ''; if ($search[$key] == '-1') {
$search[$key] = '';
}
$mode_search = 2; $mode_search = 2;
} }
if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); if ($search[$key] != '') {
$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
}
} }
if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); if ($search_all) {
$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
}
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks // Add where from hooks
@ -341,26 +361,24 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
if ($limit) $sql .= $db->plimit($limit + 1, $offset); if ($limit) {
$sql .= $db->plimit($limit + 1, $offset);
}
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -369,8 +387,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".DOL_URL_ROOT.'/bom/bom_card.php?id='.$id); header("Location: ".DOL_URL_ROOT.'/bom/bom_card.php?id='.$id);
@ -386,14 +403,24 @@ llxHeader('', $title, $help_url);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
foreach ($search as $key => $val) }
{ if ($limit > 0 && $limit != $conf->liste_limit) {
if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); $param .= '&limit='.urlencode($limit);
else $param .= '&search_'.$key.'='.urlencode($search[$key]); }
foreach ($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) {
foreach ($search[$key] as $skey) {
$param .= '&search_'.$key.'[]='.urlencode($skey);
}
} else {
$param .= '&search_'.$key.'='.urlencode($search[$key]);
}
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
} }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -403,12 +430,18 @@ $arrayofmassactions = array(
'enable'=>$langs->trans("Enable"), 'enable'=>$langs->trans("Enable"),
'disable'=>$langs->trans("Disable"), 'disable'=>$langs->trans("Disable"),
); );
if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -427,9 +460,10 @@ $objecttmp = new BOM($db);
$trackid = 'bom'.$object->id; $trackid = 'bom'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($search_all) if ($search_all) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
} }
@ -440,11 +474,13 @@ $moreforfilter.= '</div>';*/
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@ -461,20 +497,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit
// Fields title search // Fields title search
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
elseif (strpos($val['type'], 'integer:') === 0) { print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
} elseif (strpos($val['type'], 'integer:') === 0) {
print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) {
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
}
print '</td>'; print '</td>';
} }
} }
@ -496,15 +538,18 @@ print '</tr>'."\n";
// Fields title label // Fields title label
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
} }
} }
@ -521,11 +566,11 @@ print '</tr>'."\n";
// Detect if we need a fetch on each output line // Detect if we need a fetch on each output line
$needToFetchEachLine = 0; $needToFetchEachLine = 0;
if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) if (preg_match('/\$object/', $val)) {
{ $needToFetchEachLine++; // There is at least one compute field that use $object
if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object }
} }
} }
@ -534,38 +579,53 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < ($limit ? min($num, $limit) : $num)) while ($i < ($limit ? min($num, $limit) : $num)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (empty($obj)) break; // Should not happen if (empty($obj)) {
break; // Should not happen
}
// Store properties in $object // Store properties in $object
$object->setVarsFromFetchObj($obj); $object->setVarsFromFetchObj($obj);
// Show here line of result // Show here line of result
print '<tr class="oddeven">'; print '<tr class="oddeven">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
}
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; if (in_array($val['type'], array('timestamp'))) {
elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif ($key == 'ref') {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
}
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') {
if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; $cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) {
$cssforfield = 'tdoverflowmax100';
}
if (!empty($arrayfields['t.'.$key]['checked'])) if (!empty($arrayfields['t.'.$key]['checked'])) {
{
print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
if ($key == 'status') print $object->getLibStatut(5); if ($key == 'status') {
else print $object->showOutputField($val, $key, $object->$key, ''); print $object->getLibStatut(5);
} else {
print $object->showOutputField($val, $key, $object->$key, '');
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!empty($val['isameasure'])) $totalarray['nbfield']++;
{ }
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; if (!empty($val['isameasure'])) {
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
}
$totalarray['val']['t.'.$key] += $object->$key; $totalarray['val']['t.'.$key] += $object->$key;
} }
} }
@ -578,14 +638,17 @@ while ($i < ($limit ? min($num, $limit) : $num))
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($object->id, $arrayofselected)) $selected = 1; if (in_array($object->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";
@ -597,10 +660,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) if ($num == 0) {
{
$colspan = 1; $colspan = 1;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }
@ -617,10 +683,11 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
{
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);

View File

@ -53,7 +53,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id;
}
$permissionnote = 1; $permissionnote = 1;
//$permissionnote=$user->rights->bom->creer; // Used by the include of actions_setnotes.inc.php //$permissionnote=$user->rights->bom->creer; // Used by the include of actions_setnotes.inc.php
@ -77,8 +79,7 @@ $form = new Form($db);
$help_url = ''; $help_url = '';
llxHeader('', $langs->trans('BillOfMaterials'), $help_url); llxHeader('', $langs->trans('BillOfMaterials'), $help_url);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
$head = bomPrepareHead($object); $head = bomPrepareHead($object);

View File

@ -108,30 +108,42 @@ class Boms extends DolibarrApi
// If the internal user must only see his customers, force searching by him // If the internal user must only see his customers, force searching by him
$search_sale = 0; $search_sale = 0;
if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
$search_sale = DolibarrApiAccess::$user->id;
}
$sql = "SELECT t.rowid"; $sql = "SELECT t.rowid";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $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) if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $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.$tmpobject->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." as t";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
}
$sql .= " WHERE 1 = 1"; $sql .= " WHERE 1 = 1";
// Example of use $mode // Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; //if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; //if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
if ($tmpobject->ismultientitymanaged) $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; if ($tmpobject->ismultientitymanaged) {
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
if ($restrictonsocid && $socid) $sql .= " AND t.fk_soc = ".$socid; }
if ($restrictonsocid && $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= " AND t.fk_soc = sc.fk_soc";
}
if ($restrictonsocid && $socid) {
$sql .= " AND t.fk_soc = ".$socid;
}
if ($restrictonsocid && $search_sale > 0) {
$sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
}
// Insert sale filter // Insert sale filter
if ($restrictonsocid && $search_sale > 0) if ($restrictonsocid && $search_sale > 0) {
{
$sql .= " AND sc.fk_user = ".$search_sale; $sql .= " AND sc.fk_user = ".$search_sale;
} }
if ($sqlfilters) if ($sqlfilters) {
{
if (!DolibarrApi::_checkFilters($sqlfilters)) { if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
@ -141,8 +153,7 @@ class Boms extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -151,12 +162,10 @@ class Boms extends DolibarrApi
} }
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$bom_static = new BOM($this->db); $bom_static = new BOM($this->db);
if ($bom_static->fetch($obj->rowid)) { if ($bom_static->fetch($obj->rowid)) {
@ -220,7 +229,9 @@ class Boms extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->bom->$field = $value; $this->bom->$field = $value;
} }
@ -251,8 +262,7 @@ class Boms extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
if (!$this->bom->delete(DolibarrApiAccess::$user)) if (!$this->bom->delete(DolibarrApiAccess::$user)) {
{
throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error); throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error);
} }
@ -316,8 +326,7 @@ class Boms extends DolibarrApi
// If object has lines, remove $db property // If object has lines, remove $db property
if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
$nboflines = count($object->lines); $nboflines = count($object->lines);
for ($i = 0; $i < $nboflines; $i++) for ($i = 0; $i < $nboflines; $i++) {
{
$this->_cleanObjectDatas($object->lines[$i]); $this->_cleanObjectDatas($object->lines[$i]);
unset($object->lines[$i]->lines); unset($object->lines[$i]->lines);
@ -340,9 +349,12 @@ class Boms extends DolibarrApi
{ {
$myobject = array(); $myobject = array();
foreach ($this->bom->fields as $field => $propfield) { foreach ($this->bom->fields as $field => $propfield) {
if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
if (!isset($data[$field])) continue; // Not a mandatory field
}
if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$myobject[$field] = $data[$field]; $myobject[$field] = $data[$field];
} }
return $myobject; return $myobject;

View File

@ -230,25 +230,24 @@ class BOM extends CommonObject
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Unset fields that are disabled // Unset fields that are disabled
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (isset($val['enabled']) && empty($val['enabled'])) {
if (isset($val['enabled']) && empty($val['enabled']))
{
unset($this->fields[$key]); unset($this->fields[$key]);
} }
} }
// Translate some data of arrayofkeyval // Translate some data of arrayofkeyval
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) foreach ($val['arrayofkeyval'] as $key2 => $val2) {
{
foreach ($val['arrayofkeyval'] as $key2 => $val2)
{
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
} }
} }
@ -264,7 +263,9 @@ class BOM extends CommonObject
*/ */
public function create(User $user, $notrigger = false) public function create(User $user, $notrigger = false)
{ {
if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency <= 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->createCommon($user, $notrigger); return $this->createCommon($user, $notrigger);
} }
@ -289,7 +290,9 @@ class BOM extends CommonObject
// Load source object // Load source object
$result = $object->fetchCommon($fromid); $result = $object->fetchCommon($fromid);
if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); if ($result > 0 && !empty($object->table_element_line)) {
$object->fetchLines();
}
// Get lines so they will be clone // Get lines so they will be clone
//foreach ($object->lines as $line) //foreach ($object->lines as $line)
@ -306,14 +309,11 @@ class BOM extends CommonObject
$object->status = self::STATUS_DRAFT; $object->status = self::STATUS_DRAFT;
// ... // ...
// Clear extrafields that are unique // Clear extrafields that are unique
if (is_array($object->array_options) && count($object->array_options) > 0) if (is_array($object->array_options) && count($object->array_options) > 0) {
{
$extrafields->fetch_name_optionals_label($object->table_element); $extrafields->fetch_name_optionals_label($object->table_element);
foreach ($object->array_options as $key => $option) foreach ($object->array_options as $key => $option) {
{
$shortkey = preg_replace('/options_/', '', $key); $shortkey = preg_replace('/options_/', '', $key);
if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
{
//var_dump($key); var_dump($clonedObj->array_options[$key]); exit; //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
unset($object->array_options[$key]); unset($object->array_options[$key]);
} }
@ -329,24 +329,21 @@ class BOM extends CommonObject
$this->errors = $object->errors; $this->errors = $object->errors;
} }
if (!$error) if (!$error) {
{
// copy internal contacts // copy internal contacts
if ($this->copy_linked_contact($object, 'internal') < 0) if ($this->copy_linked_contact($object, 'internal') < 0) {
{
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
// copy external contacts if same company // copy external contacts if same company
if (property_exists($this, 'socid') && $this->socid == $object->socid) if (property_exists($this, 'socid') && $this->socid == $object->socid) {
{ if ($this->copy_linked_contact($object, 'external') < 0) {
if ($this->copy_linked_contact($object, 'external') < 0)
$error++; $error++;
} }
} }
}
// If there is lines, create lines too // If there is lines, create lines too
@ -375,7 +372,9 @@ class BOM extends CommonObject
{ {
$result = $this->fetchCommon($id, $ref); $result = $this->fetchCommon($id, $ref);
if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); if ($result > 0 && !empty($this->table_element_line)) {
$this->fetchLines();
}
$this->calculateCosts(); $this->calculateCosts();
return $result; return $result;
@ -416,8 +415,11 @@ class BOM extends CommonObject
$sql = 'SELECT '; $sql = 'SELECT ';
$sql .= $this->getFieldList(); $sql .= $this->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if ($this->ismultientitymanaged) {
else $sql .= ' WHERE 1 = 1'; $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
} else {
$sql .= ' WHERE 1 = 1';
}
// Manage filter // Manage filter
$sqlwhere = array(); $sqlwhere = array();
if (count($filter) > 0) { if (count($filter) > 0) {
@ -448,8 +450,7 @@ class BOM extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql)) while ($obj = $this->db->fetch_object($resql)) {
{
$record = new self($this->db); $record = new self($this->db);
$record->setVarsFromFetchObj($obj); $record->setVarsFromFetchObj($obj);
@ -475,7 +476,9 @@ class BOM extends CommonObject
*/ */
public function update(User $user, $notrigger = false) public function update(User $user, $notrigger = false)
{ {
if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency <= 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->updateCommon($user, $notrigger); return $this->updateCommon($user, $notrigger);
} }
@ -503,8 +506,7 @@ class BOM extends CommonObject
*/ */
public function deleteLine(User $user, $idline, $notrigger = false) public function deleteLine(User $user, $idline, $notrigger = false)
{ {
if ($this->status < 0) if ($this->status < 0) {
{
$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
return -2; return -2;
} }
@ -524,8 +526,7 @@ class BOM extends CommonObject
global $langs, $conf; global $langs, $conf;
$langs->load("mrp"); $langs->load("mrp");
if (!empty($conf->global->BOM_ADDON)) if (!empty($conf->global->BOM_ADDON)) {
{
$mybool = false; $mybool = false;
$file = $conf->global->BOM_ADDON.".php"; $file = $conf->global->BOM_ADDON.".php";
@ -533,16 +534,14 @@ class BOM extends CommonObject
// Include file with class // Include file with class
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$dir = dol_buildpath($reldir."core/modules/bom/"); $dir = dol_buildpath($reldir."core/modules/bom/");
// Load file with numbering class (if found) // Load file with numbering class (if found)
$mybool |= @include_once $dir.$file; $mybool |= @include_once $dir.$file;
} }
if ($mybool === false) if ($mybool === false) {
{
dol_print_error('', "Failed to include file ".$file); dol_print_error('', "Failed to include file ".$file);
return ''; return '';
} }
@ -550,8 +549,7 @@ class BOM extends CommonObject
$obj = new $classname(); $obj = new $classname();
$numref = $obj->getNextValue($prod, $this); $numref = $obj->getNextValue($prod, $this);
if ($numref != "") if ($numref != "") {
{
return $numref; return $numref;
} else { } else {
$this->error = $obj->error; $this->error = $obj->error;
@ -580,8 +578,7 @@ class BOM extends CommonObject
$error = 0; $error = 0;
// Protection // Protection
if ($this->status == self::STATUS_VALIDATED) if ($this->status == self::STATUS_VALIDATED) {
{
dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
return 0; return 0;
} }
@ -599,8 +596,7 @@ class BOM extends CommonObject
$this->db->begin(); $this->db->begin();
// Define new ref // 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 if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
{
$this->fetch_product(); $this->fetch_product();
$num = $this->getNextNumRef($this->product); $num = $this->getNextNumRef($this->product);
} else { } else {
@ -618,50 +614,47 @@ class BOM extends CommonObject
dol_syslog(get_class($this)."::validate()", LOG_DEBUG); dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($this->db); dol_print_error($this->db);
$this->error = $this->db->lasterror(); $this->error = $this->db->lasterror();
$error++; $error++;
} }
if (!$error && !$notrigger) if (!$error && !$notrigger) {
{
// Call trigger // Call trigger
$result = $this->call_trigger('BOM_VALIDATE', $user); $result = $this->call_trigger('BOM_VALIDATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
if (!$error) if (!$error) {
{
$this->oldref = $this->ref; $this->oldref = $this->ref;
// Rename directory if dir was a temporary ref // Rename directory if dir was a temporary ref
if (preg_match('/^[\(]?PROV/i', $this->ref)) if (preg_match('/^[\(]?PROV/i', $this->ref)) {
{
// Now we rename also files into index // 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 = 'bom/".$this->db->escape($this->newref)."'"; $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'bom/".$this->db->escape($this->newref)."'";
$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->error = $this->db->lasterror(); } 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 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
$oldref = dol_sanitizeFileName($this->ref); $oldref = dol_sanitizeFileName($this->ref);
$newref = dol_sanitizeFileName($num); $newref = dol_sanitizeFileName($num);
$dirsource = $conf->bom->dir_output.'/'.$oldref; $dirsource = $conf->bom->dir_output.'/'.$oldref;
$dirdest = $conf->bom->dir_output.'/'.$newref; $dirdest = $conf->bom->dir_output.'/'.$newref;
if (!$error && file_exists($dirsource)) if (!$error && file_exists($dirsource)) {
{
dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
if (@rename($dirsource, $dirdest)) if (@rename($dirsource, $dirdest)) {
{
dol_syslog("Rename ok"); dol_syslog("Rename ok");
// Rename docs starting with $oldref with $newref // Rename docs starting with $oldref with $newref
$listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); $listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
foreach ($listoffiles as $fileentry) foreach ($listoffiles as $fileentry) {
{
$dirsource = $fileentry['name']; $dirsource = $fileentry['name'];
$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
$dirsource = $fileentry['path'].'/'.$dirsource; $dirsource = $fileentry['path'].'/'.$dirsource;
@ -674,14 +667,12 @@ class BOM extends CommonObject
} }
// Set new ref and current status // Set new ref and current status
if (!$error) if (!$error) {
{
$this->ref = $num; $this->ref = $num;
$this->status = self::STATUS_VALIDATED; $this->status = self::STATUS_VALIDATED;
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
@ -700,8 +691,7 @@ class BOM extends CommonObject
public function setDraft($user, $notrigger = 0) public function setDraft($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status <= self::STATUS_DRAFT) if ($this->status <= self::STATUS_DRAFT) {
{
return 0; return 0;
} }
@ -725,8 +715,7 @@ class BOM extends CommonObject
public function cancel($user, $notrigger = 0) public function cancel($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_VALIDATED) if ($this->status != self::STATUS_VALIDATED) {
{
return 0; return 0;
} }
@ -750,8 +739,7 @@ class BOM extends CommonObject
public function reopen($user, $notrigger = 0) public function reopen($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_CANCELED) if ($this->status != self::STATUS_CANCELED) {
{
return 0; return 0;
} }
@ -780,7 +768,9 @@ class BOM extends CommonObject
{ {
global $db, $conf, $langs, $hookmanager; global $db, $conf, $langs, $hookmanager;
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
$result = ''; $result = '';
@ -793,19 +783,20 @@ class BOM extends CommonObject
$url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $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 ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowBillOfMaterials"); $label = $langs->trans("ShowBillOfMaterials");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
@ -818,15 +809,21 @@ class BOM extends CommonObject
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint; if ($reshook > 0) $linkclose = $hookmanager->resPrint;
*/ */
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $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) {
if ($withpicto != 2) $result .= $this->ref; $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@ -834,8 +831,11 @@ class BOM extends CommonObject
$hookmanager->initHooks(array('bomdao')); $hookmanager->initHooks(array('bomdao'));
$parameters = array('id'=>$this->id, 'getnomurl'=>$result); $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $result = $hookmanager->resPrint; if ($reshook > 0) {
else $result .= $hookmanager->resPrint; $result = $hookmanager->resPrint;
} else {
$result .= $hookmanager->resPrint;
}
return $result; return $result;
} }
@ -862,8 +862,7 @@ class BOM extends CommonObject
public function LibStatut($status, $mode = 0) public function LibStatut($status, $mode = 0)
{ {
// phpcs:enable // phpcs:enable
if (empty($this->labelStatus)) if (empty($this->labelStatus)) {
{
global $langs; global $langs;
//$langs->load("mrp"); //$langs->load("mrp");
$this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
@ -872,8 +871,12 @@ class BOM extends CommonObject
} }
$statusType = 'status'.$status; $statusType = 'status'.$status;
if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; if ($status == self::STATUS_VALIDATED) {
if ($status == self::STATUS_CANCELED) $statusType = 'status6'; $statusType = 'status4';
}
if ($status == self::STATUS_CANCELED) {
$statusType = 'status6';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode);
} }
@ -891,28 +894,23 @@ class BOM extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE t.rowid = '.$id; $sql .= ' WHERE t.rowid = '.$id;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$this->id = $obj->rowid; $this->id = $obj->rowid;
if ($obj->fk_user_author) if ($obj->fk_user_author) {
{
$cuser = new User($this->db); $cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author); $cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser; $this->user_creation = $cuser;
} }
if ($obj->fk_user_valid) if ($obj->fk_user_valid) {
{
$vuser = new User($this->db); $vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid); $vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser; $this->user_validation = $vuser;
} }
if ($obj->fk_user_cloture) if ($obj->fk_user_cloture) {
{
$cluser = new User($this->db); $cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture); $cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser; $this->user_cloture = $cluser;
@ -941,8 +939,7 @@ class BOM extends CommonObject
$objectline = new BOMLine($this->db); $objectline = new BOMLine($this->db);
$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.$this->id)); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.$this->id));
if (is_numeric($result)) if (is_numeric($result)) {
{
$this->error = $this->error; $this->error = $this->error;
$this->errors = $this->errors; $this->errors = $this->errors;
return $result; return $result;
@ -1051,8 +1048,7 @@ class BOM extends CommonObject
} }
$line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp); $line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp);
if (empty($line->unit_cost)) { if (empty($line->unit_cost)) {
if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) {
{
$line->unit_cost = $productFournisseur->fourn_unitprice; $line->unit_cost = $productFournisseur->fourn_unitprice;
} }
} }
@ -1197,25 +1193,24 @@ class BOMLine extends CommonObjectLine
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Unset fields that are disabled // Unset fields that are disabled
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (isset($val['enabled']) && empty($val['enabled'])) {
if (isset($val['enabled']) && empty($val['enabled']))
{
unset($this->fields[$key]); unset($this->fields[$key]);
} }
} }
// Translate some data of arrayofkeyval // Translate some data of arrayofkeyval
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) foreach ($val['arrayofkeyval'] as $key2 => $val2) {
{
foreach ($val['arrayofkeyval'] as $key2 => $val2)
{
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
} }
} }
@ -1231,7 +1226,9 @@ class BOMLine extends CommonObjectLine
*/ */
public function create(User $user, $notrigger = false) public function create(User $user, $notrigger = false)
{ {
if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency < 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->createCommon($user, $notrigger); return $this->createCommon($user, $notrigger);
} }
@ -1272,8 +1269,11 @@ class BOMLine extends CommonObjectLine
$sql = 'SELECT '; $sql = 'SELECT ';
$sql .= $this->getFieldList(); $sql .= $this->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if ($this->ismultientitymanaged) {
else $sql .= ' WHERE 1 = 1'; $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
} else {
$sql .= ' WHERE 1 = 1';
}
// Manage filter // Manage filter
$sqlwhere = array(); $sqlwhere = array();
if (count($filter) > 0) { if (count($filter) > 0) {
@ -1304,8 +1304,7 @@ class BOMLine extends CommonObjectLine
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql)) while ($obj = $this->db->fetch_object($resql)) {
{
$record = new self($this->db); $record = new self($this->db);
$record->setVarsFromFetchObj($obj); $record->setVarsFromFetchObj($obj);
@ -1331,7 +1330,9 @@ class BOMLine extends CommonObjectLine
*/ */
public function update(User $user, $notrigger = false) public function update(User $user, $notrigger = false)
{ {
if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency < 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->updateCommon($user, $notrigger); return $this->updateCommon($user, $notrigger);
} }
@ -1363,7 +1364,9 @@ class BOMLine extends CommonObjectLine
{ {
global $db, $conf, $langs, $hookmanager; global $db, $conf, $langs, $hookmanager;
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
$result = ''; $result = '';
@ -1373,19 +1376,20 @@ class BOMLine extends CommonObjectLine
$url = dol_buildpath('/bom/bomline_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/bom/bomline_card.php', 1).'?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $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 ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowBillOfMaterialsLine"); $label = $langs->trans("ShowBillOfMaterialsLine");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
@ -1398,15 +1402,21 @@ class BOMLine extends CommonObjectLine
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint; if ($reshook > 0) $linkclose = $hookmanager->resPrint;
*/ */
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $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) {
if ($withpicto != 2) $result .= $this->ref; $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@ -1414,8 +1424,11 @@ class BOMLine extends CommonObjectLine
$hookmanager->initHooks(array('bomlinedao')); $hookmanager->initHooks(array('bomlinedao'));
$parameters = array('id'=>$this->id, 'getnomurl'=>$result); $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $result = $hookmanager->resPrint; if ($reshook > 0) {
else $result .= $hookmanager->resPrint; $result = $hookmanager->resPrint;
} else {
$result .= $hookmanager->resPrint;
}
return $result; return $result;
} }
@ -1458,28 +1471,23 @@ class BOMLine extends CommonObjectLine
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE t.rowid = '.$id; $sql .= ' WHERE t.rowid = '.$id;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$this->id = $obj->rowid; $this->id = $obj->rowid;
if ($obj->fk_user_author) if ($obj->fk_user_author) {
{
$cuser = new User($this->db); $cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author); $cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser; $this->user_creation = $cuser;
} }
if ($obj->fk_user_valid) if ($obj->fk_user_valid) {
{
$vuser = new User($this->db); $vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid); $vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser; $this->user_validation = $vuser;
} }
if ($obj->fk_user_cloture) if ($obj->fk_user_cloture) {
{
$cluser = new User($this->db); $cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture); $cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser; $this->user_cloture = $cluser;

View File

@ -88,14 +88,19 @@ function bomPrepareHead($object)
$head[$h][2] = 'card'; $head[$h][2] = 'card';
$h++; $h++;
if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) {
{
$nbNote = 0; $nbNote = 0;
if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_private)) {
if (!empty($object->note_public)) $nbNote++; $nbNote++;
}
if (!empty($object->note_public)) {
$nbNote++;
}
$head[$h][0] = DOL_URL_ROOT.'/bom/bom_note.php?id='.$object->id; $head[$h][0] = DOL_URL_ROOT.'/bom/bom_note.php?id='.$object->id;
$head[$h][1] = $langs->trans('Notes'); $head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : ''); if ($nbNote > 0) {
$head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : '');
}
$head[$h][2] = 'note'; $head[$h][2] = 'note';
$h++; $h++;
} }
@ -107,7 +112,9 @@ function bomPrepareHead($object)
$nbLinks = Link::count($db, $object->element, $object->id); $nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/bom/bom_document.php?id='.$object->id; $head[$h][0] = DOL_URL_ROOT.'/bom/bom_document.php?id='.$object->id;
$head[$h][1] = $langs->trans('Documents'); $head[$h][1] = $langs->trans('Documents');
if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>' : ''); if (($nbFiles + $nbLinks) > 0) {
$head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>' : '');
}
$head[$h][2] = 'document'; $head[$h][2] = 'document';
$h++; $h++;

View File

@ -39,12 +39,13 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1)
$total = 0; $total = 0;
$ilink = 0; $ilink = 0;
foreach ($linkedObjectBlock as $key => $objectlink) foreach ($linkedObjectBlock as $key => $objectlink) {
{
$ilink++; $ilink++;
$product_static = new Product($db); $product_static = new Product($db);
$trclass = 'oddeven'; $trclass = 'oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) {
$trclass .= ' liste_sub_total';
}
echo '<tr class="'.$trclass.'" >'; echo '<tr class="'.$trclass.'" >';
echo '<td class="linkedcol-element" >'.$langs->trans("Bom"); echo '<td class="linkedcol-element" >'.$langs->trans("Bom");
if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) {

View File

@ -38,7 +38,9 @@ if (empty($object) || !is_object($object)) {
global $forceall, $forcetoshowtitlelines; global $forceall, $forcetoshowtitlelines;
if (empty($forceall)) $forceall = 0; if (empty($forceall)) {
$forceall = 0;
}
// Define colspan for the button 'Add' // Define colspan for the button 'Add'
@ -60,8 +62,7 @@ if ($nolinesbefore) {
print '<div id="add"></div><span class="hideonsmartphone">'.$langs->trans('AddNewLine').'</span>'; print '<div id="add"></div><span class="hideonsmartphone">'.$langs->trans('AddNewLine').'</span>';
print '</td>'; print '</td>';
print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>'; print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
print '<td class="linecoluseunit left">'; print '<td class="linecoluseunit left">';
print '<span id="title_units">'; print '<span id="title_units">';
print $langs->trans('Unit'); print $langs->trans('Unit');
@ -86,16 +87,18 @@ $coldisplay++;
print '<td class="bordertop nobottom linecoldescription minwidth500imp">'; print '<td class="bordertop nobottom linecoldescription minwidth500imp">';
// Predefined product/service // Predefined product/service
if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) {
{ if ($forceall >= 0 && $freelines) {
if ($forceall >= 0 && $freelines) echo '<br>'; echo '<br>';
}
echo '<span class="prod_entry_mode_predef">'; echo '<span class="prod_entry_mode_predef">';
$filtertype = ''; $filtertype = '';
if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $filtertype = '1'; if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) {
$filtertype = '1';
}
$statustoshow = -1; $statustoshow = -1;
if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
{
// hide products in closed warehouse, but show products for internal transfer // hide products in closed warehouse, but show products for internal transfer
$form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array')); $form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array'));
} else { } else {
@ -109,8 +112,7 @@ $coldisplay++;
print '<td class="bordertop nobottom linecolqty right"><input type="text" size="2" name="qty" id="qty" class="flat right" value="'.(GETPOSTISSET("qty") ? GETPOST("qty", 'alpha', 2) : 1).'">'; print '<td class="bordertop nobottom linecolqty right"><input type="text" size="2" name="qty" id="qty" class="flat right" value="'.(GETPOSTISSET("qty") ? GETPOST("qty", 'alpha', 2) : 1).'">';
print '</td>'; print '</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
$coldisplay++; $coldisplay++;
print '<td class="nobottom linecoluseunit left">'; print '<td class="nobottom linecoluseunit left">';
print '</td>'; print '</td>';

View File

@ -32,8 +32,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($object) || !is_object($object)) if (empty($object) || !is_object($object)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -41,7 +40,9 @@ if (empty($object) || !is_object($object))
global $forceall; global $forceall;
if (empty($forceall)) $forceall = 0; if (empty($forceall)) {
$forceall = 0;
}
// Define colspan for the button 'Add' // Define colspan for the button 'Add'
@ -79,8 +80,7 @@ if ($line->fk_product > 0) {
print $tmpproduct->getNomUrl(1); print $tmpproduct->getNomUrl(1);
} }
if (is_object($hookmanager)) if (is_object($hookmanager)) {
{
$fk_parent_line = (GETPOST('fk_parent_line') ? GETPOST('fk_parent_line') : $line->fk_parent_line); $fk_parent_line = (GETPOST('fk_parent_line') ? GETPOST('fk_parent_line') : $line->fk_parent_line);
$parameters = array('line'=>$line, 'fk_parent_line'=>$fk_parent_line, 'var'=>$var, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer); $parameters = array('line'=>$line, 'fk_parent_line'=>$fk_parent_line, 'var'=>$var, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer);
$reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action);
@ -108,8 +108,7 @@ if (($line->info_bits & 2) != 2) {
} }
print '</td>'; print '</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
$coldisplay++; $coldisplay++;
print '<td class="nobottom linecoluseunit left">'; print '<td class="nobottom linecoluseunit left">';
print '</td>'; print '</td>';

View File

@ -34,8 +34,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($object) || !is_object($object)) if (empty($object) || !is_object($object)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -46,7 +45,9 @@ print "<thead>\n";
print '<tr class="liste_titre nodrag nodrop">'; print '<tr class="liste_titre nodrag nodrop">';
// Adds a line numbering column // Adds a line numbering column
if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum center">&nbsp;</td>'; if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
print '<td class="linecolnum center">&nbsp;</td>';
}
// Description // Description
print '<td class="linecoldescription">'.$langs->trans('Description').'</td>'; print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
@ -54,8 +55,7 @@ print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
// Qty // Qty
print '<td class="linecolqty right">'.$form->textwithpicto($langs->trans('Qty'), $langs->trans("QtyRequiredIfNoLoss")).'</td>'; print '<td class="linecolqty right">'.$form->textwithpicto($langs->trans('Qty'), $langs->trans("QtyRequiredIfNoLoss")).'</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>'; print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
} }
@ -77,8 +77,7 @@ print '<td class="linecoldelete" style="width: 10px"></td>';
print '<td class="linecolmove" style="width: 10px"></td>'; print '<td class="linecolmove" style="width: 10px"></td>';
if ($action == 'selectlines') if ($action == 'selectlines') {
{
print '<td class="linecolcheckall center">'; print '<td class="linecolcheckall center">';
print '<input type="checkbox" class="linecheckboxtoggle" />'; print '<input type="checkbox" class="linecheckboxtoggle" />';
print '<script>$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>'; print '<script>$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';

View File

@ -35,8 +35,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($object) || !is_object($object)) if (empty($object) || !is_object($object)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -44,11 +43,21 @@ if (empty($object) || !is_object($object))
global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax; global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax;
if (empty($dateSelector)) $dateSelector = 0; if (empty($dateSelector)) {
if (empty($forceall)) $forceall = 0; $dateSelector = 0;
if (empty($senderissupplier)) $senderissupplier = 0; }
if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0; if (empty($forceall)) {
if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0; $forceall = 0;
}
if (empty($senderissupplier)) {
$senderissupplier = 0;
}
if (empty($inputalsopricewithtax)) {
$inputalsopricewithtax = 0;
}
if (empty($outputalsopricetotalwithtax)) {
$outputalsopricetotalwithtax = 0;
}
// add html5 elements // add html5 elements
$domData = ' data-element="'.$line->element.'"'; $domData = ' data-element="'.$line->element.'"';
@ -79,8 +88,7 @@ $coldisplay++;
echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price
print '</td>'; print '</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
print '<td class="linecoluseunit nowrap left">'; print '<td class="linecoluseunit nowrap left">';
$label = $tmpproduct->getLabelOfUnit('long'); $label = $tmpproduct->getLabelOfUnit('long');
if ($label !== '') { if ($label !== '') {
@ -159,8 +167,7 @@ if ($action == 'selectlines') {
print '</tr>'; print '</tr>';
//Line extrafield //Line extrafield
if (!empty($extrafields)) if (!empty($extrafields)) {
{
print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', 1, 'line'); print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', 1, 'line');
} }

View File

@ -27,16 +27,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
// If socid provided by ajax company selector // If socid provided by ajax company selector
if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) {
{
$_GET['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_GET['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha');
$_POST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_POST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha');
$_REQUEST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_REQUEST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha');
} }
// Security check // Security check
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "cashdesk")); $langs->loadLangs(array("admin", "cashdesk"));
@ -45,11 +45,12 @@ $langs->loadLangs(array("admin", "cashdesk"));
/* /*
* Actions * Actions
*/ */
if (GETPOST('action', 'alpha') == 'set') if (GETPOST('action', 'alpha') == 'set') {
{
$db->begin(); $db->begin();
if (GETPOST('socid', 'int') < 0) $_POST["socid"] = ''; if (GETPOST('socid', 'int') < 0) {
$_POST["socid"] = '';
}
$res = dolibarr_set_const($db, "CASHDESK_ID_THIRDPARTY", (GETPOST('socid', 'int') > 0 ? GETPOST('socid', 'int') : ''), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "CASHDESK_ID_THIRDPARTY", (GETPOST('socid', 'int') > 0 ? GETPOST('socid', 'int') : ''), 'chaine', 0, '', $conf->entity);
$res = dolibarr_set_const($db, "CASHDESK_ID_BANKACCOUNT_CASH", (GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') : ''), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "CASHDESK_ID_BANKACCOUNT_CASH", (GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') : ''), 'chaine', 0, '', $conf->entity);
@ -62,10 +63,11 @@ if (GETPOST('action', 'alpha') == 'set')
dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha'));
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
@ -93,8 +95,7 @@ print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="set">'; print '<input type="hidden" name="action" value="set">';
if (!empty($conf->service->enabled)) if (!empty($conf->service->enabled)) {
{
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Parameters").'</td><td>'.$langs->trans("Value").'</td>'; print '<td>'.$langs->trans("Parameters").'</td><td>'.$langs->trans("Value").'</td>';
@ -121,8 +122,7 @@ print '<tr class="oddeven"><td width=\"50%\">'.$langs->trans("CashDeskThirdParty
print '<td colspan="2">'; print '<td colspan="2">';
print $form->select_company($conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client in (1,3) AND s.status = 1)', 1, 0, 0, array(), 0); print $form->select_company($conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client in (1,3) AND s.status = 1)', 1, 0, 0, array(), 0);
print '</td></tr>'; print '</td></tr>';
if (!empty($conf->banque->enabled)) if (!empty($conf->banque->enabled)) {
{
print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForSell").'</td>'; print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForSell").'</td>';
print '<td colspan="2">'; print '<td colspan="2">';
$form->select_comptes($conf->global->CASHDESK_ID_BANKACCOUNT_CASH, 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", 1); $form->select_comptes($conf->global->CASHDESK_ID_BANKACCOUNT_CASH, 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", 1);
@ -141,8 +141,7 @@ if (!empty($conf->banque->enabled))
print '</td></tr>'; print '</td></tr>';
} }
if (!empty($conf->stock->enabled)) if (!empty($conf->stock->enabled)) {
{
print '<tr class="oddeven"><td>'.$langs->trans("CashDeskDoNotDecreaseStock").'</td>'; // Force warehouse (this is not a default value) print '<tr class="oddeven"><td>'.$langs->trans("CashDeskDoNotDecreaseStock").'</td>'; // Force warehouse (this is not a default value)
print '<td colspan="2">'; print '<td colspan="2">';
if (empty($conf->productbatch->enabled)) { if (empty($conf->productbatch->enabled)) {
@ -161,8 +160,7 @@ if (!empty($conf->stock->enabled))
print '<tr class="oddeven"><td>'.$langs->trans("CashDeskIdWareHouse").'</td>'; // Force warehouse (this is not a default value) print '<tr class="oddeven"><td>'.$langs->trans("CashDeskIdWareHouse").'</td>'; // Force warehouse (this is not a default value)
print '<td colspan="2">'; print '<td colspan="2">';
if (!$disabled) if (!$disabled) {
{
print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE, 'CASHDESK_ID_WAREHOUSE', '', 1, $disabled); print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE, 'CASHDESK_ID_WAREHOUSE', '', 1, $disabled);
print ' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">('.$langs->trans("Create").')</a>'; print ' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">('.$langs->trans("Create").')</a>';
} else { } else {
@ -172,8 +170,7 @@ if (!empty($conf->stock->enabled))
} }
// Use Dolibarr Receipt Printer // Use Dolibarr Receipt Printer
if (!empty($conf->receiptprinter->enabled)) if (!empty($conf->receiptprinter->enabled)) {
{
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
print $langs->trans("DolibarrReceiptPrinter").' ('.$langs->trans("FeatureNotYetAvailable").')'; print $langs->trans("DolibarrReceiptPrinter").' ('.$langs->trans("FeatureNotYetAvailable").')';
print '<td colspan="2">'; print '<td colspan="2">';

View File

@ -25,15 +25,13 @@
require_once 'class/Facturation.class.php'; require_once 'class/Facturation.class.php';
// Si nouvelle vente, reinitialisation des donnees (destruction de l'objet et vidage de la table contenant la liste des articles) // Si nouvelle vente, reinitialisation des donnees (destruction de l'objet et vidage de la table contenant la liste des articles)
if ($_GET['id'] == 'NOUV') if ($_GET['id'] == 'NOUV') {
{
unset($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']);
unset($_SESSION['poscart']); unset($_SESSION['poscart']);
} }
// Recuperation, s'il existe, de l'objet contenant les infos de la vente en cours ... // Recuperation, s'il existe, de l'objet contenant les infos de la vente en cours ...
if (isset($_SESSION['serObjFacturation'])) if (isset($_SESSION['serObjFacturation'])) {
{
$obj_facturation = unserialize($_SESSION['serObjFacturation']); $obj_facturation = unserialize($_SESSION['serObjFacturation']);
unset($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']);
} else { } else {
@ -58,7 +56,9 @@ print '<div class="inline-block" style="vertical-align: top">';
print '<div class="principal">'; print '<div class="principal">';
$page = GETPOST('menutpl', 'alpha'); $page = GETPOST('menutpl', 'alpha');
if (empty($page)) $page = 'facturation'; if (empty($page)) {
$page = 'facturation';
}
if (in_array( if (in_array(
$page, $page,
@ -67,8 +67,7 @@ if (in_array(
'index', 'index_verif', 'facturation', 'facturation_verif', 'facturation_dhtml', 'index', 'index_verif', 'facturation', 'facturation_verif', 'facturation_dhtml',
'validation', 'validation_ok', 'validation_ticket', 'validation_verif', 'validation', 'validation_ok', 'validation_ticket', 'validation_verif',
) )
)) )) {
{
include $page.'.php'; include $page.'.php';
} else { } else {
dol_print_error('', 'menu param '.$page.' is not inside allowed list'); dol_print_error('', 'menu param '.$page.' is not inside allowed list');

View File

@ -30,8 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/cashdesk/include/keypad.php';
$error = GETPOST('error'); $error = GETPOST('error');
// Test if already logged // Test if already logged
if ($_SESSION['uid'] <= 0) if ($_SESSION['uid'] <= 0) {
{
header('Location: index.php'); header('Location: index.php');
exit; exit;
} }
@ -53,8 +52,7 @@ top_htmlhead($head, $langs->trans("CashDesk"), 0, 0, $arrayofjs, $arrayofcss);
print '<body>'."\n"; print '<body>'."\n";
if (!empty($error)) if (!empty($error)) {
{
dol_htmloutput_events(); dol_htmloutput_events();
} }

View File

@ -27,8 +27,7 @@
<?php <?php
// Wrapper to show tooltips // Wrapper to show tooltips
if (!empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) if (!empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) {
{
print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n"; print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n";
print '<script type="text/javascript"> print '<script type="text/javascript">
jQuery(document).ready(function () { jQuery(document).ready(function () {

View File

@ -95,15 +95,18 @@ class Auth
$test = true; $test = true;
// Authentication mode // Authentication mode
if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr'; if (empty($dolibarr_main_authentication)) {
$dolibarr_main_authentication = 'http,dolibarr';
}
// Authentication mode: forceuser // Authentication mode: forceuser
if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) {
$dolibarr_auto_user = 'auto';
}
// Set authmode // Set authmode
$authmode = explode(',', $dolibarr_main_authentication); $authmode = explode(',', $dolibarr_main_authentication);
// No authentication mode // No authentication mode
if (!count($authmode)) if (!count($authmode)) {
{
$langs->load('main'); $langs->load('main');
dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication')); dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication'));
exit; exit;
@ -117,15 +120,17 @@ class Auth
// If ok, the variable will be initialized login // If ok, the variable will be initialized login
// If error, we will put error message in session under the name dol_loginmesg // If error, we will put error message in session under the name dol_loginmesg
$goontestloop = false; $goontestloop = false;
if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop = true; if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) {
if (isset($aLogin) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop = true; $goontestloop = true;
}
if (isset($aLogin) || GETPOST('openid_mode', 'alpha', 1)) {
$goontestloop = true;
}
if ($test && $goontestloop) if ($test && $goontestloop) {
{
include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode); $login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode);
if ($login) if ($login) {
{
$this->login($aLogin); $this->login($aLogin);
$this->passwd($aPasswd); $this->passwd($aPasswd);
$ret = 0; $ret = 0;

View File

@ -116,8 +116,7 @@ class Facturation
// Clean vat code // Clean vat code
$reg = array(); $reg = array();
$vat_src_code = ''; $vat_src_code = '';
if (preg_match('/\((.*)\)/', $txtva, $reg)) if (preg_match('/\((.*)\)/', $txtva, $reg)) {
{
$vat_src_code = $reg[1]; $vat_src_code = $reg[1];
$txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
} }
@ -133,8 +132,7 @@ class Facturation
$total_localtax2 = $resultarray[10]; $total_localtax2 = $resultarray[10];
// Calculation of the discount amount // Calculation of the discount amount
if ($this->remisePercent()) if ($this->remisePercent()) {
{
$remise_percent = $this->remisePercent(); $remise_percent = $this->remisePercent();
} else { } else {
$remise_percent = 0; $remise_percent = 0;
@ -155,10 +153,8 @@ class Facturation
$newcartarray[$i]['price'] = $product->price; $newcartarray[$i]['price'] = $product->price;
$newcartarray[$i]['price_ttc'] = $product->price_ttc; $newcartarray[$i]['price_ttc'] = $product->price_ttc;
if (!empty($conf->global->PRODUIT_MULTIPRICES)) if (!empty($conf->global->PRODUIT_MULTIPRICES)) {
{ if (isset($product->multiprices[$societe->price_level])) {
if (isset($product->multiprices[$societe->price_level]))
{
$newcartarray[$i]['price'] = $product->multiprices[$societe->price_level]; $newcartarray[$i]['price'] = $product->multiprices[$societe->price_level];
$newcartarray[$i]['price_ttc'] = $product->multiprices_ttc[$societe->price_level]; $newcartarray[$i]['price_ttc'] = $product->multiprices_ttc[$societe->price_level];
} }
@ -191,10 +187,8 @@ class Facturation
$j = 0; $j = 0;
$newposcart = array(); $newposcart = array();
foreach ($poscart as $key => $val) foreach ($poscart as $key => $val) {
{ if ($poscart[$key]['id'] != $aArticle) {
if ($poscart[$key]['id'] != $aArticle)
{
$newposcart[$j] = $poscart[$key]; $newposcart[$j] = $poscart[$key];
$newposcart[$j]['id'] = $j; $newposcart[$j]['id'] = $j;
$j++; $j++;
@ -223,8 +217,7 @@ class Facturation
$tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); $tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array());
$tab_size = count($tab); $tab_size = count($tab);
for ($i = 0; $i < $tab_size; $i++) for ($i = 0; $i < $tab_size; $i++) {
{
// Total HT // Total HT
$remise = $tab[$i]['remise']; $remise = $tab[$i]['remise'];
$total_ht += ($tab[$i]['total_ht']); $total_ht += ($tab[$i]['total_ht']);
@ -291,11 +284,9 @@ class Facturation
public function id($aId = null) public function id($aId = null)
{ {
if (!$aId) if (!$aId) {
{
return $this->id; return $this->id;
} elseif ($aId == 'RESET') } elseif ($aId == 'RESET') {
{
$this->id = null; $this->id = null;
} else { } else {
$this->id = $aId; $this->id = $aId;
@ -311,11 +302,9 @@ class Facturation
public function ref($aRef = null) public function ref($aRef = null)
{ {
if (is_null($aRef)) if (is_null($aRef)) {
{
return $this->ref; return $this->ref;
} elseif ($aRef == 'RESET') } elseif ($aRef == 'RESET') {
{
$this->ref = null; $this->ref = null;
} else { } else {
$this->ref = $aRef; $this->ref = $aRef;
@ -330,11 +319,9 @@ class Facturation
*/ */
public function qte($aQte = null) public function qte($aQte = null)
{ {
if (is_null($aQte)) if (is_null($aQte)) {
{
return $this->qte; return $this->qte;
} elseif ($aQte == 'RESET') } elseif ($aQte == 'RESET') {
{
$this->qte = null; $this->qte = null;
} else { } else {
$this->qte = $aQte; $this->qte = $aQte;
@ -350,11 +337,9 @@ class Facturation
public function stock($aStock = null) public function stock($aStock = null)
{ {
if (is_null($aStock)) if (is_null($aStock)) {
{
return $this->stock; return $this->stock;
} elseif ($aStock == 'RESET') } elseif ($aStock == 'RESET') {
{
$this->stock = null; $this->stock = null;
} else { } else {
$this->stock = $aStock; $this->stock = $aStock;
@ -370,11 +355,9 @@ class Facturation
public function remisePercent($aRemisePercent = null) public function remisePercent($aRemisePercent = null)
{ {
if (is_null($aRemisePercent)) if (is_null($aRemisePercent)) {
{
return $this->remise_percent; return $this->remise_percent;
} elseif ($aRemisePercent == 'RESET') } elseif ($aRemisePercent == 'RESET') {
{
$this->remise_percent = null; $this->remise_percent = null;
} else { } else {
$this->remise_percent = $aRemisePercent; $this->remise_percent = $aRemisePercent;
@ -564,11 +547,9 @@ class Facturation
*/ */
public function amountWithTax($aTotalTtc = null) public function amountWithTax($aTotalTtc = null)
{ {
if (is_null($aTotalTtc)) if (is_null($aTotalTtc)) {
{
return $this->prix_total_ttc; return $this->prix_total_ttc;
} elseif ($aTotalTtc == 'RESET') } elseif ($aTotalTtc == 'RESET') {
{
$this->prix_total_ttc = null; $this->prix_total_ttc = null;
} else { } else {
$this->prix_total_ttc = $aTotalTtc; $this->prix_total_ttc = $aTotalTtc;

View File

@ -22,10 +22,18 @@
*/ */
//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Uncomment creates pb to relogon after a disconnect //if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Uncomment creates pb to relogon after a disconnect
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); if (!defined('NOREQUIREMENU')) {
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); define('NOREQUIREMENU', '1');
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); }
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
require_once '../main.inc.php'; require_once '../main.inc.php';

View File

@ -40,16 +40,21 @@ if (GETPOST('filtre', 'alpha')) {
$ret = array(); $i = 0; $ret = array(); $i = 0;
$sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx, p.fk_product_type"; $sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx, p.fk_product_type";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
$sql .= " AND p.tosell = 1"; $sql .= " AND p.tosell = 1";
if (!$conf->global->CASHDESK_SERVICES) $sql .= " AND p.fk_product_type = 0"; if (!$conf->global->CASHDESK_SERVICES) {
$sql .= " AND p.fk_product_type = 0";
}
$sql .= " AND ("; $sql .= " AND (";
$sql .= "p.ref LIKE '%".$db->escape(GETPOST('filtre'))."%' OR p.label LIKE '%".$db->escape(GETPOST('filtre'))."%'"; $sql .= "p.ref LIKE '%".$db->escape(GETPOST('filtre'))."%' OR p.label LIKE '%".$db->escape(GETPOST('filtre'))."%'";
if (!empty($conf->barcode->enabled)) if (!empty($conf->barcode->enabled)) {
{
$filtre = GETPOST('filtre', 'alpha'); $filtre = GETPOST('filtre', 'alpha');
//If the barcode looks like an EAN13 format and the last digit is included in it, //If the barcode looks like an EAN13 format and the last digit is included in it,
@ -67,14 +72,11 @@ if (GETPOST('filtre', 'alpha')) {
dol_syslog("facturation.php", LOG_DEBUG); dol_syslog("facturation.php", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$nbr_enreg = $db->num_rows($resql); $nbr_enreg = $db->num_rows($resql);
while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) {
{ foreach ($tab as $cle => $valeur) {
foreach ($tab as $cle => $valeur)
{
$ret[$i][$cle] = $valeur; $ret[$i][$cle] = $valeur;
} }
$i++; $i++;
@ -90,24 +92,27 @@ if (GETPOST('filtre', 'alpha')) {
$i = 0; $i = 0;
$sql = "SELECT p.rowid, ref, label, tva_tx, p.fk_product_type"; $sql = "SELECT p.rowid, ref, label, tva_tx, p.fk_product_type";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
$sql .= " AND p.tosell = 1"; $sql .= " AND p.tosell = 1";
if (!$conf->global->CASHDESK_SERVICES) $sql .= " AND p.fk_product_type = 0"; if (!$conf->global->CASHDESK_SERVICES) {
$sql .= " AND p.fk_product_type = 0";
}
$sql .= " ORDER BY p.label"; $sql .= " ORDER BY p.label";
dol_syslog($sql); dol_syslog($sql);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$nbr_enreg = $db->num_rows($resql); $nbr_enreg = $db->num_rows($resql);
while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) {
{ foreach ($tab as $cle => $valeur) {
foreach ($tab as $cle => $valeur)
{
$ret[$i][$cle] = $valeur; $ret[$i][$cle] = $valeur;
} }
$i++; $i++;
@ -121,16 +126,13 @@ if (GETPOST('filtre', 'alpha')) {
//$nbr_enreg = count($tab_designations); //$nbr_enreg = count($tab_designations);
if ($nbr_enreg > 1) if ($nbr_enreg > 1) {
{ if ($nbr_enreg > $conf_taille_listes) {
if ($nbr_enreg > $conf_taille_listes)
{
$top_liste_produits = '----- '.$conf_taille_listes.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----'; $top_liste_produits = '----- '.$conf_taille_listes.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----';
} else { } else {
$top_liste_produits = '----- '.$nbr_enreg.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----'; $top_liste_produits = '----- '.$nbr_enreg.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----';
} }
} elseif ($nbr_enreg == 1) } elseif ($nbr_enreg == 1) {
{
$top_liste_produits = '----- 1 '.$langs->transnoentitiesnoconv("ProductFound").' -----'; $top_liste_produits = '----- 1 '.$langs->transnoentitiesnoconv("ProductFound").' -----';
} else { } else {
$top_liste_produits = '----- '.$langs->transnoentitiesnoconv("NoProductFound").' -----'; $top_liste_produits = '----- '.$langs->transnoentitiesnoconv("NoProductFound").' -----';

View File

@ -24,12 +24,24 @@
*/ */
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); if (!defined('NOREQUIRESOC')) {
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); define('NOREQUIRESOC', '1');
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); }
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); if (!defined('NOCSRFCHECK')) {
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); define('NOCSRFCHECK', '1');
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); }
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1');
}
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
// Change this following line to use the correct relative path (../, ../../, etc) // Change this following line to use the correct relative path (../, ../../, etc)
require '../main.inc.php'; require '../main.inc.php';
@ -40,24 +52,30 @@ top_httphead('text/html');
$search = GETPOST("code", "alpha"); $search = GETPOST("code", "alpha");
// Search from criteria // Search from criteria
if (dol_strlen($search) >= 0) // If search criteria is on char length at least if (dol_strlen($search) >= 0) { // If search criteria is on char length at least
{
$sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx"; $sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
$sql .= " AND p.tosell = 1"; $sql .= " AND p.tosell = 1";
$sql .= " AND p.fk_product_type = 0"; $sql .= " AND p.fk_product_type = 0";
// Add criteria on ref/label // Add criteria on ref/label
if (!empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)) if (!empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)) {
{
$sql .= " AND (p.ref LIKE '".$db->escape($search)."%' OR p.label LIKE '".$db->escape($search)."%'"; $sql .= " AND (p.ref LIKE '".$db->escape($search)."%' OR p.label LIKE '".$db->escape($search)."%'";
if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$db->escape($search)."%'"; if (!empty($conf->barcode->enabled)) {
$sql .= " OR p.barcode LIKE '".$db->escape($search)."%'";
}
$sql .= ")"; $sql .= ")";
} else { } else {
$sql .= " AND (p.ref LIKE '%".$db->escape($search)."%' OR p.label LIKE '%".$db->escape($search)."%'"; $sql .= " AND (p.ref LIKE '%".$db->escape($search)."%' OR p.label LIKE '%".$db->escape($search)."%'";
if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '%".$db->escape($search)."%'"; if (!empty($conf->barcode->enabled)) {
$sql .= " OR p.barcode LIKE '%".$db->escape($search)."%'";
}
$sql .= ")"; $sql .= ")";
} }
$sql .= " ORDER BY label"; $sql .= " ORDER BY label";
@ -65,17 +83,13 @@ if (dol_strlen($search) >= 0) // If search criteria is on char length at least
dol_syslog("facturation_dhtml.php", LOG_DEBUG); dol_syslog("facturation_dhtml.php", LOG_DEBUG);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{ if ($nbr = $db->num_rows($result)) {
if ($nbr = $db->num_rows($result))
{
$resultat = '<ul class="dhtml_bloc">'; $resultat = '<ul class="dhtml_bloc">';
$ret = array(); $i = 0; $ret = array(); $i = 0;
while ($tab = $db->fetch_array($result)) while ($tab = $db->fetch_array($result)) {
{ foreach ($tab as $cle => $valeur) {
foreach ($tab as $cle => $valeur)
{
$ret[$i][$cle] = $valeur; $ret[$i][$cle] = $valeur;
} }
$i++; $i++;
@ -83,8 +97,7 @@ if (dol_strlen($search) >= 0) // If search criteria is on char length at least
$tab = $ret; $tab = $ret;
$tab_size = count($tab); $tab_size = count($tab);
for ($i = 0; $i < $tab_size; $i++) for ($i = 0; $i < $tab_size; $i++) {
{
$resultat .= ' $resultat .= '
<li class="dhtml_defaut" title="'.$tab[$i]['ref'].'" <li class="dhtml_defaut" title="'.$tab[$i]['ref'].'"
onMouseOver="javascript: this.className = \'dhtml_selection\';" onMouseOver="javascript: this.className = \'dhtml_selection\';"

View File

@ -35,36 +35,33 @@ $obj_facturation = unserialize($_SESSION['serObjFacturation']);
unset($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']);
switch ($action) switch ($action) {
{
default: default:
if ($_POST['hdnSource'] != 'NULL') if ($_POST['hdnSource'] != 'NULL') {
{
$sql = "SELECT p.rowid, p.ref, p.price, p.tva_tx, p.default_vat_code, p.recuperableonly"; $sql = "SELECT p.rowid, p.ref, p.price, p.tva_tx, p.default_vat_code, p.recuperableonly";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = ".$conf_fkentrepot; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = ".$conf_fkentrepot;
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
// Recuperation des donnees en fonction de la source (liste deroulante ou champ texte) ... // Recuperation des donnees en fonction de la source (liste deroulante ou champ texte) ...
if ($_POST['hdnSource'] == 'LISTE') if ($_POST['hdnSource'] == 'LISTE') {
{
$sql .= " AND p.rowid = ".((int) GETPOST('selProduit', 'int')); $sql .= " AND p.rowid = ".((int) GETPOST('selProduit', 'int'));
} elseif ($_POST['hdnSource'] == 'REF') } elseif ($_POST['hdnSource'] == 'REF') {
{
$sql .= " AND p.ref = '".$db->escape(GETPOST('txtRef', 'alpha'))."'"; $sql .= " AND p.ref = '".$db->escape(GETPOST('txtRef', 'alpha'))."'";
} }
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
// ... et enregistrement dans l'objet // ... et enregistrement dans l'objet
if ($db->num_rows($result)) if ($db->num_rows($result)) {
{
$ret = array(); $ret = array();
$tab = $db->fetch_array($result); $tab = $db->fetch_array($result);
foreach ($tab as $key => $value) foreach ($tab as $key => $value) {
{
$ret[$key] = $value; $ret[$key] = $value;
} }
// Here $ret['tva_tx'] is vat rate of product but we want to not use the one into table but found by function // Here $ret['tva_tx'] is vat rate of product but we want to not use the one into table but found by function
@ -81,7 +78,9 @@ switch ($action)
// Update if prices fields are defined // Update if prices fields are defined
$tva_tx = get_default_tva($mysoc, $societe, $product->id); $tva_tx = get_default_tva($mysoc, $societe, $product->id);
$tva_npr = get_default_npr($mysoc, $societe, $product->id); $tva_npr = get_default_npr($mysoc, $societe, $product->id);
if (empty($tva_tx)) $tva_npr = 0; if (empty($tva_tx)) {
$tva_npr = 0;
}
$pu_ht = $prod->price; $pu_ht = $prod->price;
$pu_ttc = $prod->price_ttc; $pu_ttc = $prod->price_ttc;
@ -89,19 +88,20 @@ switch ($action)
$price_base_type = $prod->price_base_type; $price_base_type = $prod->price_base_type;
// multiprix // multiprix
if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($societe->price_level)) if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($societe->price_level)) {
{
$pu_ht = $prod->multiprices[$societe->price_level]; $pu_ht = $prod->multiprices[$societe->price_level];
$pu_ttc = $prod->multiprices_ttc[$societe->price_level]; $pu_ttc = $prod->multiprices_ttc[$societe->price_level];
$price_min = $prod->multiprices_min[$societe->price_level]; $price_min = $prod->multiprices_min[$societe->price_level];
$price_base_type = $prod->multiprices_base_type[$societe->price_level]; $price_base_type = $prod->multiprices_base_type[$societe->price_level];
if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
{ if (isset($prod->multiprices_tva_tx[$societe->price_level])) {
if (isset($prod->multiprices_tva_tx[$societe->price_level])) $tva_tx = $prod->multiprices_tva_tx[$societe->price_level]; $tva_tx = $prod->multiprices_tva_tx[$societe->price_level];
if (isset($prod->multiprices_recuperableonly[$societe->price_level])) $tva_npr = $prod->multiprices_recuperableonly[$societe->price_level];
} }
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) if (isset($prod->multiprices_recuperableonly[$societe->price_level])) {
{ $tva_npr = $prod->multiprices_recuperableonly[$societe->price_level];
}
}
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
$prodcustprice = new Productcustomerprice($db); $prodcustprice = new Productcustomerprice($db);
@ -109,17 +109,19 @@ switch ($action)
$filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $societe->id); $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $societe->id);
$result = $prodcustprice->fetch_all('', '', 0, 0, $filter); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
if ($result >= 0) if ($result >= 0) {
{ if (count($prodcustprice->lines) > 0) {
if (count($prodcustprice->lines) > 0)
{
$pu_ht = price($prodcustprice->lines[0]->price); $pu_ht = price($prodcustprice->lines[0]->price);
$pu_ttc = price($prodcustprice->lines[0]->price_ttc); $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
$price_base_type = $prodcustprice->lines[0]->price_base_type; $price_base_type = $prodcustprice->lines[0]->price_base_type;
$tva_tx = $prodcustprice->lines[0]->tva_tx; $tva_tx = $prodcustprice->lines[0]->tva_tx;
if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
$tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
}
$tva_npr = $prodcustprice->lines[0]->recuperableonly; $tva_npr = $prodcustprice->lines[0]->recuperableonly;
if (empty($tva_tx)) $tva_npr = 0; if (empty($tva_tx)) {
$tva_npr = 0;
}
} }
} else { } else {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
@ -133,10 +135,9 @@ switch ($action)
if (!empty($price_ht)) { if (!empty($price_ht)) {
$pu_ht = price2num($price_ht, 'MU'); $pu_ht = price2num($price_ht, 'MU');
$pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
} } elseif ($tmpvat != $tmpprodvat) {
// On reevalue prix selon taux tva car taux tva transaction peut etre different // On reevalue prix selon taux tva car taux tva transaction peut etre different
// de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
elseif ($tmpvat != $tmpprodvat) {
if ($price_base_type != 'HT') { if ($price_base_type != 'HT') {
$pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
} else { } else {
@ -155,11 +156,9 @@ switch ($action)
$obj_facturation->vatrate = $vatrate; // Save vat rate (full text vat with code) $obj_facturation->vatrate = $vatrate; // Save vat rate (full text vat with code)
// Definition du filtre pour n'afficher que le produit concerne // Definition du filtre pour n'afficher que le produit concerne
if ($_POST['hdnSource'] == 'LISTE') if ($_POST['hdnSource'] == 'LISTE') {
{
$filtre = $ret['ref']; $filtre = $ret['ref'];
} elseif ($_POST['hdnSource'] == 'REF') } elseif ($_POST['hdnSource'] == 'REF') {
{
$filtre = $_POST['txtRef']; $filtre = $_POST['txtRef'];
} }
@ -167,8 +166,7 @@ switch ($action)
} else { } else {
$obj_facturation->raz(); $obj_facturation->raz();
if ($_POST['hdnSource'] == 'REF') if ($_POST['hdnSource'] == 'REF') {
{
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation&filtre='.$_POST['txtRef']; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation&filtre='.$_POST['txtRef'];
} else { } else {
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation'; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation';
@ -185,18 +183,15 @@ switch ($action)
case 'change_thirdparty': // We have clicked on button "Modify" a thirdparty case 'change_thirdparty': // We have clicked on button "Modify" a thirdparty
$newthirdpartyid = GETPOST('CASHDESK_ID_THIRDPARTY', 'int'); $newthirdpartyid = GETPOST('CASHDESK_ID_THIRDPARTY', 'int');
if ($newthirdpartyid > 0) if ($newthirdpartyid > 0) {
{
$_SESSION["CASHDESK_ID_THIRDPARTY"] = $newthirdpartyid; $_SESSION["CASHDESK_ID_THIRDPARTY"] = $newthirdpartyid;
} }
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation'; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation';
break; break;
case 'ajout_article': // We have clicked on button "Add product" case 'ajout_article':
if (!empty($obj_facturation->id)) { // A product was previously selected and stored in session, so we can add it
if (!empty($obj_facturation->id)) // A product was previously selected and stored in session, so we can add it
{
dol_syslog("facturation_verif save vat ".$_POST['selTva']); dol_syslog("facturation_verif save vat ".$_POST['selTva']);
$obj_facturation->qte($_POST['txtQte']); $obj_facturation->qte($_POST['txtQte']);
$obj_facturation->tva($_POST['selTva']); // id of vat. Saved so we can use it for next product $obj_facturation->tva($_POST['selTva']); // id of vat. Saved so we can use it for next product

View File

@ -32,7 +32,9 @@ $conf_db_base = $dolibarr_main_db_name;
$conf_fksoc = (!empty($_SESSION["CASHDESK_ID_THIRDPARTY"])) ? $_SESSION["CASHDESK_ID_THIRDPARTY"] : ($conf->global->CASHDESK_ID_THIRDPARTY > 0 ? $conf->global->CASHDESK_ID_THIRDPARTY : 0); $conf_fksoc = (!empty($_SESSION["CASHDESK_ID_THIRDPARTY"])) ? $_SESSION["CASHDESK_ID_THIRDPARTY"] : ($conf->global->CASHDESK_ID_THIRDPARTY > 0 ? $conf->global->CASHDESK_ID_THIRDPARTY : 0);
// Identifiant unique correspondant a l'entrepot a utiliser // Identifiant unique correspondant a l'entrepot a utiliser
$conf_fkentrepot = (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"])) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : ($conf->global->CASHDESK_ID_WAREHOUSE > 0 ? $conf->global->CASHDESK_ID_WAREHOUSE : 0); $conf_fkentrepot = (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"])) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : ($conf->global->CASHDESK_ID_WAREHOUSE > 0 ? $conf->global->CASHDESK_ID_WAREHOUSE : 0);
if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $conf_fkentrepot = 0; // If option to disable the stock decrease is on, we set warehouse id to 0. if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
$conf_fkentrepot = 0; // If option to disable the stock decrease is on, we set warehouse id to 0.
}
// Identifiant unique correspondant au compte caisse / liquide // Identifiant unique correspondant au compte caisse / liquide
$conf_fkaccount_cash = (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) ? $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"] : ($conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0 ? $conf->global->CASHDESK_ID_BANKACCOUNT_CASH : 0); $conf_fkaccount_cash = (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) ? $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"] : ($conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0 ? $conf->global->CASHDESK_ID_BANKACCOUNT_CASH : 0);

View File

@ -26,7 +26,9 @@ function genkeypad($keypadname, $formname)
{ {
global $conf; global $conf;
if (empty($conf->global->CASHDESK_SHOW_KEYPAD)) return ''; if (empty($conf->global->CASHDESK_SHOW_KEYPAD)) {
return '';
}
// défine the font size of button // défine the font size of button
$btnsize = 32; $btnsize = 32;

View File

@ -32,8 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$langs->loadLangs(array("admin", "cashdesk")); $langs->loadLangs(array("admin", "cashdesk"));
// Test if user logged // Test if user logged
if ($_SESSION['uid'] > 0) if ($_SESSION['uid'] > 0) {
{
header('Location: '.DOL_URL_ROOT.'/cashdesk/affIndex.php'); header('Location: '.DOL_URL_ROOT.'/cashdesk/affIndex.php');
exit; exit;
} }
@ -72,8 +71,7 @@ if (is_array($hookmanager->resArray) && !empty($hookmanager->resArray)) {
<div class="menu_principal hideonsmartphone"> <div class="menu_principal hideonsmartphone">
<div class="logo"> <div class="logo">
<?php <?php
if (!empty($mysoc->logo_small)) if (!empty($mysoc->logo_small)) {
{
print '<img class="logopos" alt="Logo company" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small).'">'; print '<img class="logopos" alt="Logo company" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small).'">';
} else { } else {
print '<div class="logopos">'.$mysoc->name.'</div>'; print '<div class="logopos">'.$mysoc->name.'</div>';
@ -85,7 +83,9 @@ if (!empty($mysoc->logo_small))
<div class="contenu"> <div class="contenu">
<div class="inline-block" style="vertical-align: top"> <div class="inline-block" style="vertical-align: top">
<div class="principal_login"> <div class="principal_login">
<?php if ($err) print dol_escape_htmltag($err)."<br><br>\n"; ?> <?php if ($err) {
print dol_escape_htmltag($err)."<br><br>\n";
} ?>
<fieldset class="cadre_facturation"><legend class="titre1"><?php echo $langs->trans("Identification"); ?></legend> <fieldset class="cadre_facturation"><legend class="titre1"><?php echo $langs->trans("Identification"); ?></legend>
<form id="frmLogin" method="POST" action="index_verif.php"> <form id="frmLogin" method="POST" action="index_verif.php">
<input type="hidden" name="token" value="<?php echo newToken(); ?>" /> <input type="hidden" name="token" value="<?php echo newToken(); ?>" />
@ -104,8 +104,7 @@ if (!empty($mysoc->logo_small))
<?php <?php
if (!empty($morelogincontent)) { if (!empty($morelogincontent)) {
if (is_array($morelogincontent)) { if (is_array($morelogincontent)) {
foreach ($morelogincontent as $format => $option) foreach ($morelogincontent as $format => $option) {
{
if ($format == 'table') { if ($format == 'table') {
echo '<!-- Option by hook -->'; echo '<!-- Option by hook -->';
echo $option; echo $option;
@ -130,20 +129,23 @@ print '<td class="label1">'.$langs->trans("CashDeskThirdPartyForSell").'</td>';
print '<td>'; print '<td>';
$disabled = 0; $disabled = 0;
$langs->load("companies"); $langs->load("companies");
if (!empty($conf->global->CASHDESK_ID_THIRDPARTY)) $disabled = 1; // If a particular third party is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_THIRDPARTY)) {
$disabled = 1; // If a particular third party is defined, we disable choice
}
print $form->select_company(GETPOST('socid', 'int') ?GETPOST('socid', 'int') : $conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client IN (1,3) AND s.status = 1)', !$disabled, $disabled, 0, array(), 0, 'maxwidth300'); print $form->select_company(GETPOST('socid', 'int') ?GETPOST('socid', 'int') : $conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client IN (1,3) AND s.status = 1)', !$disabled, $disabled, 0, array(), 0, 'maxwidth300');
//print '<input name="warehouse_id" class="texte_login" type="warehouse_id" value="" />'; //print '<input name="warehouse_id" class="texte_login" type="warehouse_id" value="" />';
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
{
$langs->load("stocks"); $langs->load("stocks");
print "<tr>"; print "<tr>";
print '<td class="label1">'.$langs->trans("Warehouse").'</td>'; print '<td class="label1">'.$langs->trans("Warehouse").'</td>';
print '<td>'; print '<td>';
$disabled = 0; $disabled = 0;
if ($conf->global->CASHDESK_ID_WAREHOUSE > 0) $disabled = 1; // If a particular stock is defined, we disable choice if ($conf->global->CASHDESK_ID_WAREHOUSE > 0) {
$disabled = 1; // If a particular stock is defined, we disable choice
}
print $formproduct->selectWarehouses((GETPOST('warehouseid') ?GETPOST('warehouseid', 'int') : (empty($conf->global->CASHDESK_ID_WAREHOUSE) ? 'ifone' : $conf->global->CASHDESK_ID_WAREHOUSE)), 'warehouseid', '', !$disabled, $disabled); print $formproduct->selectWarehouses((GETPOST('warehouseid') ?GETPOST('warehouseid', 'int') : (empty($conf->global->CASHDESK_ID_WAREHOUSE) ? 'ifone' : $conf->global->CASHDESK_ID_WAREHOUSE)), 'warehouseid', '', !$disabled, $disabled);
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -153,7 +155,9 @@ print "<tr>";
print '<td class="label1">'.$langs->trans("CashDeskBankAccountForSell").'</td>'; print '<td class="label1">'.$langs->trans("CashDeskBankAccountForSell").'</td>';
print '<td>'; print '<td>';
$defaultknown = 0; $defaultknown = 0;
if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && $conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0) $defaultknown = 1; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && $conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0) {
$defaultknown = 1; // If a particular stock is defined, we disable choice
}
$form->select_comptes(((GETPOST('bankid_cash') > 0) ?GETPOST('bankid_cash') : $conf->global->CASHDESK_ID_BANKACCOUNT_CASH), 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", ($defaultknown ? 0 : 2)); $form->select_comptes(((GETPOST('bankid_cash') > 0) ?GETPOST('bankid_cash') : $conf->global->CASHDESK_ID_BANKACCOUNT_CASH), 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", ($defaultknown ? 0 : 2));
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -162,7 +166,9 @@ print "<tr>";
print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCheque").'</td>'; print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCheque").'</td>';
print '<td>'; print '<td>';
$defaultknown = 0; $defaultknown = 0;
if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE) && $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE > 0) $defaultknown = 1; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE) && $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE > 0) {
$defaultknown = 1; // If a particular stock is defined, we disable choice
}
$form->select_comptes(((GETPOST('bankid_cheque') > 0) ?GETPOST('bankid_cheque') : $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE), 'CASHDESK_ID_BANKACCOUNT_CHEQUE', 0, "courant=1", ($defaultknown ? 0 : 2)); $form->select_comptes(((GETPOST('bankid_cheque') > 0) ?GETPOST('bankid_cheque') : $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE), 'CASHDESK_ID_BANKACCOUNT_CHEQUE', 0, "courant=1", ($defaultknown ? 0 : 2));
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -171,7 +177,9 @@ print "<tr>";
print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCB").'</td>'; print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCB").'</td>';
print '<td>'; print '<td>';
$defaultknown = 0; $defaultknown = 0;
if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CB) && $conf->global->CASHDESK_ID_BANKACCOUNT_CB > 0) $defaultknown = 1; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CB) && $conf->global->CASHDESK_ID_BANKACCOUNT_CB > 0) {
$defaultknown = 1; // If a particular stock is defined, we disable choice
}
$form->select_comptes(((GETPOST('bankid_cb') > 0) ?GETPOST('bankid_cb') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB), 'CASHDESK_ID_BANKACCOUNT_CB', 0, "courant=1", ($defaultknown ? 0 : 2)); $form->select_comptes(((GETPOST('bankid_cb') > 0) ?GETPOST('bankid_cb') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB), 'CASHDESK_ID_BANKACCOUNT_CB', 0, "courant=1", ($defaultknown ? 0 : 2));
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -195,8 +203,7 @@ print "</tr>\n";
<?php <?php
if ($_GET['err'] < 0) if ($_GET['err'] < 0) {
{
echo ('<script type="text/javascript">'); echo ('<script type="text/javascript">');
echo (' document.getElementById(\'frmLogin\').pwdPassword.focus();'); echo (' document.getElementById(\'frmLogin\').pwdPassword.focus();');
echo ('</script>'); echo ('</script>');

View File

@ -42,36 +42,31 @@ $bankid_cheque = (GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE") > 0) ?GETPOST("CASHD
$bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB") > 0) ?GETPOST("CASHDESK_ID_BANKACCOUNT_CB", 'int') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB; $bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB") > 0) ?GETPOST("CASHDESK_ID_BANKACCOUNT_CB", 'int') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB;
// Check username // Check username
if (empty($username)) if (empty($username)) {
{
$retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Login")); $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Login"));
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
} }
// Check third party id // Check third party id
if (!($thirdpartyid > 0)) if (!($thirdpartyid > 0)) {
{
$retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("CashDeskThirdPartyForSell")); $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("CashDeskThirdPartyForSell"));
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
} }
// If we setup stock module to ask movement on invoices, we must not allow access if required setup not finished. // If we setup stock module to ask movement on invoices, we must not allow access if required setup not finished.
if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) {
{
$retour = $langs->trans("CashDeskYouDidNotDisableStockDecease"); $retour = $langs->trans("CashDeskYouDidNotDisableStockDecease");
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
} }
// If stock decrease on bill validation, check user has stock edit permissions // If stock decrease on bill validation, check user has stock edit permissions
if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) {
{
$testuser = new User($db); $testuser = new User($db);
$testuser->fetch(0, $username); $testuser->fetch(0, $username);
$testuser->getrights('stock'); $testuser->getrights('stock');
if (empty($testuser->rights->stock->creer)) if (empty($testuser->rights->stock->creer)) {
{
$retour = $langs->trans("UserNeedPermissionToEditStockToUsePos"); $retour = $langs->trans("UserNeedPermissionToEditStockToUsePos");
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
@ -83,8 +78,7 @@ if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_S
$auth = new Auth($db); $auth = new Auth($db);
$retour = $auth->verif($username, $password); $retour = $auth->verif($username, $password);
if ($retour >= 0) if ($retour >= 0) {
{
$return = array(); $return = array();
$sql = "SELECT rowid, lastname, firstname"; $sql = "SELECT rowid, lastname, firstname";
@ -93,12 +87,10 @@ if ($retour >= 0)
$sql .= " AND entity IN (0,".$conf->entity.")"; $sql .= " AND entity IN (0,".$conf->entity.")";
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$tab = $db->fetch_array($res); $tab = $db->fetch_array($res);
foreach ($tab as $key => $value) foreach ($tab as $key => $value) {
{
$return[$key] = $value; $return[$key] = $value;
} }

View File

@ -21,8 +21,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -64,10 +63,11 @@ $id = $obj_facturation->id();
// Si trop d'articles ont ete trouves, on n'affiche que les X premiers (defini dans le fichier de configuration) ... // Si trop d'articles ont ete trouves, on n'affiche que les X premiers (defini dans le fichier de configuration) ...
$nbtoshow = $nbr_enreg; $nbtoshow = $nbr_enreg;
if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) $nbtoshow = $conf_taille_listes; if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) {
$nbtoshow = $conf_taille_listes;
}
for ($i = 0; $i < $nbtoshow; $i++) for ($i = 0; $i < $nbtoshow; $i++) {
{
if ($id == $tab_designations[$i]['rowid']) { if ($id == $tab_designations[$i]['rowid']) {
$selected = 'selected'; $selected = 'selected';
} else { } else {
@ -116,7 +116,9 @@ for ($i = 0; $i < $nbtoshow; $i++)
$vatrate = $obj_facturation->vatrate; // To get vat rate we just have selected $vatrate = $obj_facturation->vatrate; // To get vat rate we just have selected
$buyer = new Societe($db); $buyer = new Societe($db);
if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) $buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) {
$buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]);
}
echo $form->load_tva('selTva', (GETPOSTISSET("selTva") ? GETPOST("selTva", 'alpha', 2) : $vatrate), $mysoc, $buyer, 0, 0, '', false, -1); echo $form->load_tva('selTva', (GETPOSTISSET("selTva") ? GETPOST("selTva", 'alpha', 2) : $vatrate), $mysoc, $buyer, 0, 0, '', false, -1);
?> ?>
</td> </td>
@ -165,25 +167,28 @@ for ($i = 0; $i < $nbtoshow; $i++)
<div class="inline-block"> <div class="inline-block">
<?php <?php
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';
if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) {
{
$langs->load("errors"); $langs->load("errors");
print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("Cash").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />'; print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("Cash").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />';
} else print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("Cash").'" onclick="javascript: verifClic(\'ESP\');" />'; } else {
print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("Cash").'" onclick="javascript: verifClic(\'ESP\');" />';
}
print '</div>'; print '</div>';
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';
if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) {
{
$langs->load("errors"); $langs->load("errors");
print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />'; print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />';
} else print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" onclick="javascript: verifClic(\'CB\');" />'; } else {
print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" onclick="javascript: verifClic(\'CB\');" />';
}
print '</div>'; print '</div>';
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';
if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) {
{
$langs->load("errors"); $langs->load("errors");
print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete"), $langs->transnoentitiesnoconv("CashDesk")).'" />'; print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete"), $langs->transnoentitiesnoconv("CashDesk")).'" />';
} else print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" onclick="javascript: verifClic(\'CHQ\');" />'; } else {
print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" onclick="javascript: verifClic(\'CHQ\');" />';
}
print '</div>'; print '</div>';
print '<div class="clearboth">'; print '<div class="clearboth">';
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';

View File

@ -18,8 +18,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -48,10 +47,10 @@ $societe->fetch($thirdpartyid);
$tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); $tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array());
$tab_size = count($tab); $tab_size = count($tab);
if ($tab_size <= 0) print '<div class="center">'.$langs->trans("NoArticle").'</div><br>'; if ($tab_size <= 0) {
else { print '<div class="center">'.$langs->trans("NoArticle").'</div><br>';
for ($i = 0; $i < $tab_size; $i++) } else {
{ for ($i = 0; $i < $tab_size; $i++) {
echo ('<div class="cadre_article">'."\n"); echo ('<div class="cadre_article">'."\n");
echo ('<p><a href="facturation_verif.php?action=suppr_article&suppr_id='.$tab[$i]['id'].'" title="'.$langs->trans("DeleteArticle").'">'.$tab[$i]['ref'].' - '.$tab[$i]['label'].'</a></p>'."\n"); echo ('<p><a href="facturation_verif.php?action=suppr_article&suppr_id='.$tab[$i]['id'].'" title="'.$langs->trans("DeleteArticle").'">'.$tab[$i]['ref'].' - '.$tab[$i]['label'].'</a></p>'."\n");

View File

@ -20,8 +20,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -37,27 +36,23 @@ include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$company->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); $company->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]);
$companyLink = $company->getNomUrl(1); $companyLink = $company->getNomUrl(1);
}*/ }*/
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) {
{
$bankcash = new Account($db); $bankcash = new Account($db);
$bankcash->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]); $bankcash->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]);
$bankcash->label = $bankcash->ref; $bankcash->label = $bankcash->ref;
$bankcashLink = $bankcash->getNomUrl(1); $bankcashLink = $bankcash->getNomUrl(1);
} }
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) {
{
$bankcb = new Account($db); $bankcb = new Account($db);
$bankcb->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]); $bankcb->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]);
$bankcbLink = $bankcb->getNomUrl(1); $bankcbLink = $bankcb->getNomUrl(1);
} }
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) {
{
$bankcheque = new Account($db); $bankcheque = new Account($db);
$bankcheque->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]); $bankcheque->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]);
$bankchequeLink = $bankcheque->getNomUrl(1); $bankchequeLink = $bankcheque->getNomUrl(1);
} }
if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) {
{
$warehouse = new Entrepot($db); $warehouse = new Entrepot($db);
$warehouse->fetch($_SESSION["CASHDESK_ID_WAREHOUSE"]); $warehouse->fetch($_SESSION["CASHDESK_ID_WAREHOUSE"]);
$warehouseLink = $warehouse->getNomUrl(1); $warehouseLink = $warehouse->getNomUrl(1);
@ -87,8 +82,7 @@ print '</form>';
print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'<br>'; print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'<br>';
print $langs->trans("CashDeskBankCheque").': '.$bankchequeLink.'<br>';*/ print $langs->trans("CashDeskBankCheque").': '.$bankchequeLink.'<br>';*/
print '<div class="clearboth">'; print '<div class="clearboth">';
if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
{
print $langs->trans("CashDeskWarehouse").': '.$warehouseLink; print $langs->trans("CashDeskWarehouse").': '.$warehouseLink;
} }
print '</div></li></ul>'; print '</div></li></ul>';

View File

@ -18,8 +18,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -82,8 +81,7 @@ $object->fetch($facid);
$tab = $_SESSION['poscart']; $tab = $_SESSION['poscart'];
$tab_size = count($tab); $tab_size = count($tab);
for ($i = 0; $i < $tab_size; $i++) for ($i = 0; $i < $tab_size; $i++) {
{
$remise = $tab[$i]['remise']; $remise = $tab[$i]['remise'];
?> ?>
<tr> <tr>

View File

@ -17,8 +17,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -47,25 +46,27 @@ if ($obj_facturation->amountVat()) {
<tr><td class="resume_label"><?php echo $langs->trans("TotalTTC"); ?> </td><td><?php echo price(price2num($obj_facturation->amountWithTax(), 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?></td></tr> <tr><td class="resume_label"><?php echo $langs->trans("TotalTTC"); ?> </td><td><?php echo price(price2num($obj_facturation->amountWithTax(), 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?></td></tr>
<tr><td class="resume_label"><?php echo $langs->trans("PaymentMode"); ?> </td><td> <tr><td class="resume_label"><?php echo $langs->trans("PaymentMode"); ?> </td><td>
<?php <?php
switch ($obj_facturation->getSetPaymentMode()) switch ($obj_facturation->getSetPaymentMode()) {
{
case 'ESP': case 'ESP':
echo $langs->trans("Cash"); echo $langs->trans("Cash");
$filtre = 'courant=2'; $filtre = 'courant=2';
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) {
$selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]; $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"];
}
break; break;
case 'CB': case 'CB':
echo $langs->trans("CreditCard"); echo $langs->trans("CreditCard");
$filtre = 'courant=1'; $filtre = 'courant=1';
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) {
$selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]; $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CB"];
}
break; break;
case 'CHQ': case 'CHQ':
echo $langs->trans("Cheque"); echo $langs->trans("Cheque");
$filtre = 'courant=1'; $filtre = 'courant=1';
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) {
$selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]; $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"];
}
break; break;
case 'DIF': case 'DIF':
echo $langs->trans("Reported"); echo $langs->trans("Reported");

View File

@ -18,8 +18,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }

View File

@ -33,8 +33,7 @@ $hookmanager->initHooks(array('cashdeskTplTicket'));
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $obj_facturation); $reshook = $hookmanager->executeHooks('doActions', $parameters, $obj_facturation);
if (empty($reshook)) if (empty($reshook)) {
{
require 'tpl/ticket.tpl.php'; require 'tpl/ticket.tpl.php';
} }

View File

@ -36,8 +36,7 @@ $obj_facturation = unserialize($_SESSION['serObjFacturation']);
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$bankaccountid = GETPOST('cashdeskbank'); $bankaccountid = GETPOST('cashdeskbank');
switch ($action) switch ($action) {
{
default: default:
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=validation'; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=validation';
break; break;
@ -55,15 +54,18 @@ switch ($action)
// To use a specific numbering module for POS, reset $conf->global->FACTURE_ADDON and other vars here // To use a specific numbering module for POS, reset $conf->global->FACTURE_ADDON and other vars here
// and restore values just after // and restore values just after
$sav_FACTURE_ADDON = ''; $sav_FACTURE_ADDON = '';
if (!empty($conf->global->POS_ADDON)) if (!empty($conf->global->POS_ADDON)) {
{
$sav_FACTURE_ADDON = $conf->global->FACTURE_ADDON; $sav_FACTURE_ADDON = $conf->global->FACTURE_ADDON;
$conf->global->FACTURE_ADDON = $conf->global->POS_ADDON; $conf->global->FACTURE_ADDON = $conf->global->POS_ADDON;
// To force prefix only for POS with terre module // To force prefix only for POS with terre module
if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX; if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) {
$conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX;
}
// To force prefix only for POS with mars module // To force prefix only for POS with mars module
if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX; if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) {
$conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX;
}
// To force rule only for POS with mercure // To force rule only for POS with mercure
//... //...
} }
@ -71,8 +73,7 @@ switch ($action)
$num = $invoice->getNextNumRef($company); $num = $invoice->getNextNumRef($company);
// Restore save values // Restore save values
if (!empty($sav_FACTURE_ADDON)) if (!empty($sav_FACTURE_ADDON)) {
{
$conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON; $conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON;
} }
@ -120,14 +121,12 @@ switch ($action)
$heure = dol_print_date($now, 'hour'); $heure = dol_print_date($now, 'hour');
$note = ''; $note = '';
if (!is_object($obj_facturation)) if (!is_object($obj_facturation)) {
{
dol_print_error('', 'Empty context'); dol_print_error('', 'Empty context');
exit; exit;
} }
switch ($obj_facturation->getSetPaymentMode()) switch ($obj_facturation->getSetPaymentMode()) {
{
case 'DIF': case 'DIF':
$mode_reglement_id = 0; $mode_reglement_id = 0;
//$cond_reglement_id = dol_getIdFromCode($db,'RECEP','cond_reglement','code','rowid') //$cond_reglement_id = dol_getIdFromCode($db,'RECEP','cond_reglement','code','rowid')
@ -151,8 +150,12 @@ switch ($action)
$cond_reglement_id = 0; $cond_reglement_id = 0;
break; break;
} }
if (empty($mode_reglement_id)) $mode_reglement_id = 0; // If mode_reglement_id not found if (empty($mode_reglement_id)) {
if (empty($cond_reglement_id)) $cond_reglement_id = 0; // If cond_reglement_id not found $mode_reglement_id = 0; // If mode_reglement_id not found
}
if (empty($cond_reglement_id)) {
$cond_reglement_id = 0; // If cond_reglement_id not found
}
$note .= $_POST['txtaNotes']; $note .= $_POST['txtaNotes'];
dol_syslog("obj_facturation->getSetPaymentMode()=".$obj_facturation->getSetPaymentMode()." mode_reglement_id=".$mode_reglement_id." cond_reglement_id=".$cond_reglement_id); dol_syslog("obj_facturation->getSetPaymentMode()=".$obj_facturation->getSetPaymentMode()." mode_reglement_id=".$mode_reglement_id." cond_reglement_id=".$cond_reglement_id);
@ -175,8 +178,7 @@ switch ($action)
// Loop on each line into cart // Loop on each line into cart
$tab_liste_size = count($tab_liste); $tab_liste_size = count($tab_liste);
for ($i = 0; $i < $tab_liste_size; $i++) for ($i = 0; $i < $tab_liste_size; $i++) {
{
$tmp = getTaxesFromId($tab_liste[$i]['fk_tva']); $tmp = getTaxesFromId($tab_liste[$i]['fk_tva']);
$vat_rate = $tmp['rate']; $vat_rate = $tmp['rate'];
$vat_npr = $tmp['npr']; $vat_npr = $tmp['npr'];
@ -218,32 +220,32 @@ switch ($action)
//print "c=".$invoice->cond_reglement_id." m=".$invoice->mode_reglement_id; exit; //print "c=".$invoice->cond_reglement_id." m=".$invoice->mode_reglement_id; exit;
// Si paiement differe ... // Si paiement differe ...
if ($obj_facturation->getSetPaymentMode() == 'DIF') if ($obj_facturation->getSetPaymentMode() == 'DIF') {
{
$resultcreate = $invoice->create($user, 0, dol_stringtotime($obj_facturation->paiementLe())); $resultcreate = $invoice->create($user, 0, dol_stringtotime($obj_facturation->paiementLe()));
if ($resultcreate > 0) if ($resultcreate > 0) {
{
$warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0);
if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
$warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice
}
$resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0);
if ($warehouseidtodecrease > 0) if ($warehouseidtodecrease > 0) {
{
// Decrease // Decrease
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
$langs->load("agenda"); $langs->load("agenda");
// Loop on each line // Loop on each line
$cpt = count($invoice->lines); $cpt = count($invoice->lines);
for ($i = 0; $i < $cpt; $i++) for ($i = 0; $i < $cpt; $i++) {
{ if ($invoice->lines[$i]->fk_product > 0) {
if ($invoice->lines[$i]->fk_product > 0)
{
$mouvP = new MouvementStock($db); $mouvP = new MouvementStock($db);
$mouvP->origin = &$invoice; $mouvP->origin = &$invoice;
// We decrease stock for product // We decrease stock for product
if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) {
else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
} else {
$result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
}
if ($result < 0) { if ($result < 0) {
$error++; $error++;
} }
@ -258,29 +260,30 @@ switch ($action)
$id = $invoice->id; $id = $invoice->id;
} else { } else {
$resultcreate = $invoice->create($user, 0, 0); $resultcreate = $invoice->create($user, 0, 0);
if ($resultcreate > 0) if ($resultcreate > 0) {
{
$warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0);
if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
$warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice
}
$resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0);
if ($warehouseidtodecrease > 0) if ($warehouseidtodecrease > 0) {
{
// Decrease // Decrease
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
$langs->load("agenda"); $langs->load("agenda");
// Loop on each line // Loop on each line
$cpt = count($invoice->lines); $cpt = count($invoice->lines);
for ($i = 0; $i < $cpt; $i++) for ($i = 0; $i < $cpt; $i++) {
{ if ($invoice->lines[$i]->fk_product > 0) {
if ($invoice->lines[$i]->fk_product > 0)
{
$mouvP = new MouvementStock($db); $mouvP = new MouvementStock($db);
$mouvP->origin = &$invoice; $mouvP->origin = &$invoice;
// We decrease stock for product // We decrease stock for product
if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) {
else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
} else {
$result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
}
if ($result < 0) { if ($result < 0) {
setEventMessages($mouvP->error, $mouvP->errors, 'errors'); setEventMessages($mouvP->error, $mouvP->errors, 'errors');
$error++; $error++;
@ -301,23 +304,18 @@ switch ($action)
$payment->num_payment = ''; $payment->num_payment = '';
$paiement_id = $payment->create($user); $paiement_id = $payment->create($user);
if ($paiement_id > 0) if ($paiement_id > 0) {
{ if (!$error) {
if (!$error)
{
$result = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccountid, '', ''); $result = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccountid, '', '');
if (!$result > 0) if (!$result > 0) {
{
$errmsg = $paiement->error; $errmsg = $paiement->error;
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
if ($invoice->total_ttc == $obj_facturation->amountWithTax() if ($invoice->total_ttc == $obj_facturation->amountWithTax()
&& $obj_facturation->getSetPaymentMode() != 'DIFF') && $obj_facturation->getSetPaymentMode() != 'DIFF') {
{
// We set status to paid // We set status to paid
$result = $invoice->setPaid($user); $result = $invoice->setPaid($user);
//print 'set paid';exit; //print 'set paid';exit;
@ -334,8 +332,7 @@ switch ($action)
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$redirection = 'affIndex.php?menutpl=validation_ok&facid='.$id; // Ajout de l'id de la facture, pour l'inclure dans un lien pointant directement vers celle-ci dans Dolibarr $redirection = 'affIndex.php?menutpl=validation_ok&facid='.$id; // Ajout de l'id de la facture, pour l'inclure dans un lien pointant directement vers celle-ci dans Dolibarr
} else { } else {

View File

@ -27,8 +27,9 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php';
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("categories", "admin")); $langs->loadLangs(array("categories", "admin"));
@ -40,11 +41,9 @@ $action = GETPOST('action', 'aZ09');
*/ */
$reg = array(); $reg = array();
if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) {
{
$code = $reg[1]; $code = $reg[1];
if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
exit; exit;
} else { } else {
@ -52,11 +51,9 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg))
} }
} }
if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) {
{
$code = $reg[1]; $code = $reg[1];
if (dolibarr_del_const($db, $code, $conf->entity) > 0) if (dolibarr_del_const($db, $code, $conf->entity) > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
exit; exit;
} else { } else {
@ -100,12 +97,10 @@ print '<td>'.$langs->trans("CategorieRecursiv").'</td>';
print '<td align="center" width="20">'.$form->textwithpicto('', $langs->trans("CategorieRecursivHelp"), 1, 'help').'</td>'; print '<td align="center" width="20">'.$form->textwithpicto('', $langs->trans("CategorieRecursivHelp"), 1, 'help').'</td>';
print '<td align="center" width="100">'; print '<td align="center" width="100">';
if ($conf->use_javascript_ajax) if ($conf->use_javascript_ajax) {
{
print ajax_constantonoff('CATEGORIE_RECURSIV_ADD'); print ajax_constantonoff('CATEGORIE_RECURSIV_ADD');
} else { } else {
if (empty($conf->global->CATEGORIE_RECURSIV_ADD)) if (empty($conf->global->CATEGORIE_RECURSIV_ADD)) {
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_CATEGORIE_RECURSIV_ADD">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_CATEGORIE_RECURSIV_ADD">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
} else { } else {
print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_CATEGORIE_RECURSIV_ADD">'.img_picto($langs->trans("Enabled"), 'on').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_CATEGORIE_RECURSIV_ADD">'.img_picto($langs->trans("Enabled"), 'on').'</a>';

View File

@ -37,13 +37,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'categorie'; //Must be the $element of the class that manage extrafield $elementtype = 'categorie'; //Must be the $element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -76,8 +80,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -90,8 +93,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -103,8 +105,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -37,7 +37,9 @@ $langs->load("categories");
// Security check // Security check
$socid = (int) GETPOST('socid', 'int'); $socid = (int) GETPOST('socid', 'int');
if (!$user->rights->categorie->lire) accessforbidden(); if (!$user->rights->categorie->lire) {
accessforbidden();
}
$action = GETPOST('action', 'alpha'); $action = GETPOST('action', 'alpha');
$cancel = GETPOST('cancel', 'alpha'); $cancel = GETPOST('cancel', 'alpha');
@ -54,15 +56,29 @@ $visible = (int) GETPOST('visible', 'int');
$parent = (int) GETPOST('parent', 'int'); $parent = (int) GETPOST('parent', 'int');
if ($origin) { if ($origin) {
if ($type == Categorie::TYPE_PRODUCT) $idProdOrigin = $origin; if ($type == Categorie::TYPE_PRODUCT) {
if ($type == Categorie::TYPE_SUPPLIER) $idSupplierOrigin = $origin; $idProdOrigin = $origin;
if ($type == Categorie::TYPE_CUSTOMER) $idCompanyOrigin = $origin; }
if ($type == Categorie::TYPE_MEMBER) $idMemberOrigin = $origin; if ($type == Categorie::TYPE_SUPPLIER) {
if ($type == Categorie::TYPE_CONTACT) $idContactOrigin = $origin; $idSupplierOrigin = $origin;
if ($type == Categorie::TYPE_PROJECT) $idProjectOrigin = $origin; }
if ($type == Categorie::TYPE_CUSTOMER) {
$idCompanyOrigin = $origin;
}
if ($type == Categorie::TYPE_MEMBER) {
$idMemberOrigin = $origin;
}
if ($type == Categorie::TYPE_CONTACT) {
$idContactOrigin = $origin;
}
if ($type == Categorie::TYPE_PROJECT) {
$idProjectOrigin = $origin;
}
} }
if ($catorigin && $type == Categorie::TYPE_PRODUCT) $idCatOrigin = $catorigin; if ($catorigin && $type == Categorie::TYPE_PRODUCT) {
$idCatOrigin = $catorigin;
}
$object = new Categorie($db); $object = new Categorie($db);
@ -80,13 +96,10 @@ $error = 0;
*/ */
// Add action // Add action
if ($action == 'add' && $user->rights->categorie->creer) if ($action == 'add' && $user->rights->categorie->creer) {
{
// Action ajout d'une categorie // Action ajout d'une categorie
if ($cancel) if ($cancel) {
{ if ($urlfrom) {
if ($urlfrom)
{
header("Location: ".$urlfrom); header("Location: ".$urlfrom);
exit; exit;
} elseif ($backtopage) { } elseif ($backtopage) {
@ -125,24 +138,25 @@ if ($action == 'add' && $user->rights->categorie->creer)
$object->visible = $visible; $object->visible = $visible;
$object->type = $type; $object->type = $type;
if ($parent != "-1") $object->fk_parent = $parent; if ($parent != "-1") {
$object->fk_parent = $parent;
}
$ret = $extrafields->setOptionalsFromPost(null, $object); $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
if (!$object->label) if (!$object->label) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors');
$action = 'create'; $action = 'create';
} }
// Create category in database // Create category in database
if (!$error) if (!$error) {
{
$result = $object->create($user); $result = $object->create($user);
if ($result > 0) if ($result > 0) {
{
$action = 'confirmed'; $action = 'confirmed';
$_POST["addcat"] = ''; $_POST["addcat"] = '';
} else { } else {
@ -152,41 +166,31 @@ if ($action == 'add' && $user->rights->categorie->creer)
} }
// Confirm action // Confirm action
if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->creer) if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->creer) {
{
// Action confirmation de creation categorie // Action confirmation de creation categorie
if ($action == 'confirmed') if ($action == 'confirmed') {
{ if ($urlfrom) {
if ($urlfrom)
{
header("Location: ".$urlfrom); header("Location: ".$urlfrom);
exit; exit;
} elseif ($backtopage) } elseif ($backtopage) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} elseif ($idProdOrigin) } elseif ($idProdOrigin) {
{
header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProdOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProdOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
exit; exit;
} elseif ($idCompanyOrigin) } elseif ($idCompanyOrigin) {
{
header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idCompanyOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idCompanyOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
exit; exit;
} elseif ($idSupplierOrigin) } elseif ($idSupplierOrigin) {
{
header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idSupplierOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idSupplierOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
exit; exit;
} elseif ($idMemberOrigin) } elseif ($idMemberOrigin) {
{
header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idMemberOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idMemberOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
exit; exit;
} elseif ($idContactOrigin) } elseif ($idContactOrigin) {
{
header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idContactOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idContactOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
exit; exit;
} elseif ($idProjectOrigin) } elseif ($idProjectOrigin) {
{
header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProjectOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProjectOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
exit; exit;
} }
@ -207,11 +211,9 @@ $formother = new FormOther($db);
$helpurl = ''; $helpurl = '';
llxHeader("", $langs->trans("Categories"), $helpurl); llxHeader("", $langs->trans("Categories"), $helpurl);
if ($user->rights->categorie->creer) if ($user->rights->categorie->creer) {
{
// Create or add // Create or add
if ($action == 'create' || GETPOST("addcat") == 'addcat') if ($action == 'create' || GETPOST("addcat") == 'addcat') {
{
dol_set_focus('#label'); dol_set_focus('#label');
print '<form action="'.$_SERVER['PHP_SELF'].'?type='.$type.'" method="POST">'; print '<form action="'.$_SERVER['PHP_SELF'].'?type='.$type.'" method="POST">';
@ -222,8 +224,12 @@ if ($user->rights->categorie->creer)
print '<input type="hidden" name="id" value="'.GETPOST('origin', 'alpha').'">'; print '<input type="hidden" name="id" value="'.GETPOST('origin', 'alpha').'">';
print '<input type="hidden" name="type" value="'.$type.'">'; print '<input type="hidden" name="type" value="'.$type.'">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
if ($origin) print '<input type="hidden" name="origin" value="'.$origin.'">'; if ($origin) {
if ($catorigin) print '<input type="hidden" name="catorigin" value="'.$catorigin.'">'; print '<input type="hidden" name="origin" value="'.$origin.'">';
}
if ($catorigin) {
print '<input type="hidden" name="catorigin" value="'.$catorigin.'">';
}
print load_fiche_titre($langs->trans("CreateCat")); print load_fiche_titre($langs->trans("CreateCat"));
@ -257,8 +263,7 @@ if ($user->rights->categorie->creer)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if (empty($reshook)) if (empty($reshook)) {
{
print $object->showOptionals($extrafields, 'edit', $parameters); print $object->showOptionals($extrafields, 'edit', $parameters);
} }

View File

@ -140,15 +140,12 @@ class Categories extends DolibarrApi
$sql = "SELECT t.rowid"; $sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."categorie as t"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie as t";
$sql .= ' WHERE t.entity IN ('.getEntity('category').')'; $sql .= ' WHERE t.entity IN ('.getEntity('category').')';
if (!empty($type)) if (!empty($type)) {
{
$sql .= ' AND t.type='.array_search($type, Categories::$TYPES); $sql .= ' AND t.type='.array_search($type, Categories::$TYPES);
} }
// Add sql filters // Add sql filters
if ($sqlfilters) if ($sqlfilters) {
{ if (!DolibarrApi::_checkFilters($sqlfilters)) {
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@ -157,8 +154,7 @@ class Categories extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -167,13 +163,11 @@ class Categories extends DolibarrApi
} }
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$i = 0; $i = 0;
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$category_static = new Categorie($this->db); $category_static = new Categorie($this->db);
if ($category_static->fetch($obj->rowid)) { if ($category_static->fetch($obj->rowid)) {
@ -181,8 +175,7 @@ class Categories extends DolibarrApi
} }
$i++; $i++;
} }
} } else {
else {
throw new RestException(503, 'Error when retrieve category list : '.$this->db->lasterror()); throw new RestException(503, 'Error when retrieve category list : '.$this->db->lasterror());
} }
if (!count($obj_ret)) { if (!count($obj_ret)) {
@ -238,7 +231,9 @@ class Categories extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->category->$field = $value; $this->category->$field = $value;
} }
@ -721,8 +716,9 @@ class Categories extends DolibarrApi
{ {
$category = array(); $category = array();
foreach (Categories::$FIELDS as $field) { foreach (Categories::$FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$category[$field] = $data[$field]; $category[$field] = $data[$field];
} }
return $category; return $category;
@ -747,8 +743,7 @@ class Categories extends DolibarrApi
throw new RestException(401); throw new RestException(401);
} }
if (empty($type)) if (empty($type)) {
{
throw new RestException(500, 'The "type" parameter is required.'); throw new RestException(500, 'The "type" parameter is required.');
} }

View File

@ -313,8 +313,12 @@ class Categorie extends CommonObject
global $conf; global $conf;
// Check parameters // Check parameters
if (empty($id) && empty($label) && empty($ref_ext)) return -1; if (empty($id) && empty($label) && empty($ref_ext)) {
if (!is_null($type) && !is_numeric($type)) $type = $this->MAP_ID[$type]; return -1;
}
if (!is_null($type) && !is_numeric($type)) {
$type = $this->MAP_ID[$type];
}
$sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext"; $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext";
$sql .= ", date_creation, tms, fk_user_creat, fk_user_modif"; $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif";
@ -325,7 +329,9 @@ class Categorie extends CommonObject
$sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'"; $sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'";
} else { } else {
$sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")"; $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")";
if (!is_null($type)) $sql .= " AND type = ".((int) $type); if (!is_null($type)) {
$sql .= " AND type = ".((int) $type);
}
} }
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
@ -357,7 +363,9 @@ class Categorie extends CommonObject
$this->db->free($resql); $this->db->free($resql);
// multilangs // multilangs
if (!empty($conf->global->MAIN_MULTILANGS)) $this->getMultiLangs(); if (!empty($conf->global->MAIN_MULTILANGS)) {
$this->getMultiLangs();
}
return 1; return 1;
} else { } else {
@ -387,7 +395,9 @@ class Categorie extends CommonObject
$type = $this->type; $type = $this->type;
if (!is_numeric($type)) $type = $this->MAP_ID[$type]; if (!is_numeric($type)) {
$type = $this->MAP_ID[$type];
}
$error = 0; $error = 0;
@ -399,7 +409,9 @@ class Categorie extends CommonObject
$this->color = trim($this->color); $this->color = trim($this->color);
$this->import_key = trim($this->import_key); $this->import_key = trim($this->import_key);
$this->ref_ext = trim($this->ref_ext); $this->ref_ext = trim($this->ref_ext);
if (empty($this->visible)) $this->visible = 0; if (empty($this->visible)) {
$this->visible = 0;
}
$this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
if ($this->already_exists()) { if ($this->already_exists()) {
@ -463,7 +475,9 @@ class Categorie extends CommonObject
if (!$error) { if (!$error) {
// Call trigger // Call trigger
$result = $this->call_trigger('CATEGORY_CREATE', $user); $result = $this->call_trigger('CATEGORY_CREATE', $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@ -542,7 +556,9 @@ class Categorie extends CommonObject
if (!$error) { if (!$error) {
// Call trigger // Call trigger
$result = $this->call_trigger('CATEGORY_MODIFY', $user); $result = $this->call_trigger('CATEGORY_MODIFY', $user);
if ($result < 0) { $error++; $this->db->rollback(); return -1; } if ($result < 0) {
$error++; $this->db->rollback(); return -1;
}
// End call triggers // End call triggers
} }
@ -579,7 +595,9 @@ class Categorie extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('CATEGORY_DELETE', $user); $result = $this->call_trigger('CATEGORY_DELETE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@ -649,9 +667,13 @@ class Categorie extends CommonObject
$error = 0; $error = 0;
if ($this->id == -1) return -2; if ($this->id == -1) {
return -2;
}
if (empty($type)) $type = $obj->element; if (empty($type)) {
$type = $obj->element;
}
$this->db->begin(); $this->db->begin();
@ -699,7 +721,9 @@ class Categorie extends CommonObject
// Call trigger // Call trigger
$this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger $this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
$result = $this->call_trigger('CATEGORY_LINK', $user); $result = $this->call_trigger('CATEGORY_LINK', $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
if (!$error) { if (!$error) {
@ -757,7 +781,9 @@ class Categorie extends CommonObject
// Call trigger // Call trigger
$this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger $this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
$result = $this->call_trigger('CATEGORY_UNLINK', $user); $result = $this->call_trigger('CATEGORY_UNLINK', $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
if (!$error) { if (!$error) {
@ -805,7 +831,9 @@ class Categorie extends CommonObject
if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) { if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) {
$sql .= " AND o.rowid = ".$user->socid; $sql .= " AND o.rowid = ".$user->socid;
} }
if ($limit > 0 || $offset > 0) $sql .= $this->db->plimit($limit + 1, $offset); if ($limit > 0 || $offset > 0) {
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG); dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
@ -1037,7 +1065,9 @@ class Categorie extends CommonObject
// phpcs:enable // phpcs:enable
global $conf, $langs; global $conf, $langs;
if (!is_numeric($type)) $type = $this->MAP_ID[$type]; if (!is_numeric($type)) {
$type = $this->MAP_ID[$type];
}
if (is_null($type)) { if (is_null($type)) {
$this->error = 'BadValueForParameterType'; $this->error = 'BadValueForParameterType';
return -1; return -1;
@ -1063,9 +1093,13 @@ class Categorie extends CommonObject
// Init $this->cats array // Init $this->cats array
$sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates $sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates
if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= ", t.label as label_trans, t.description as description_trans"; if (!empty($conf->global->MAIN_MULTILANGS)) {
$sql .= ", t.label as label_trans, t.description as description_trans";
}
$sql .= " FROM ".MAIN_DB_PREFIX."categorie as c"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'"; if (!empty($conf->global->MAIN_MULTILANGS)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'";
}
$sql .= " WHERE c.entity IN (".getEntity('category').")"; $sql .= " WHERE c.entity IN (".getEntity('category').")";
$sql .= " AND c.type = ".(int) $type; $sql .= " AND c.type = ".(int) $type;
@ -1204,14 +1238,18 @@ class Categorie extends CommonObject
public function get_all_categories($type = null, $parent = false) public function get_all_categories($type = null, $parent = false)
{ {
// phpcs:enable // phpcs:enable
if (!is_numeric($type)) $type = $this->MAP_ID[$type]; if (!is_numeric($type)) {
$type = $this->MAP_ID[$type];
}
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
$sql .= " WHERE entity IN (".getEntity('category').")"; $sql .= " WHERE entity IN (".getEntity('category').")";
if (!is_null($type)) if (!is_null($type)) {
$sql .= " AND type = ".(int) $type; $sql .= " AND type = ".(int) $type;
if ($parent) }
if ($parent) {
$sql .= " AND fk_parent = 0"; $sql .= " AND fk_parent = 0";
}
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res) { if ($res) {
@ -1252,7 +1290,9 @@ class Categorie extends CommonObject
// phpcs:enable // phpcs:enable
$type = $this->type; $type = $this->type;
if (!is_numeric($type)) $type = $this->MAP_ID[$type]; if (!is_numeric($type)) {
$type = $this->MAP_ID[$type];
}
/* We have to select any rowid from llx_categorie which category's mother and label /* We have to select any rowid from llx_categorie which category's mother and label
* are equals to those of the calling category * are equals to those of the calling category
@ -1318,7 +1358,9 @@ class Categorie extends CommonObject
// Check contrast with background and correct text color // Check contrast with background and correct text color
$forced_color = 'categtextwhite'; $forced_color = 'categtextwhite';
if ($cat->color) { if ($cat->color) {
if (colorIsLight($cat->color)) $forced_color = 'categtextblack'; if (colorIsLight($cat->color)) {
$forced_color = 'categtextblack';
}
} }
} }
} }
@ -1399,8 +1441,9 @@ class Categorie extends CommonObject
} }
} }
if (count($ways) == 0) if (count($ways) == 0) {
$ways[0][0] = $this; $ways[0][0] = $this;
}
return $ways; return $ways;
} }
@ -1419,7 +1462,9 @@ class Categorie extends CommonObject
{ {
$cats = array(); $cats = array();
if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; if (is_numeric($type)) {
$type = Categorie::$MAP_ID_TO_CODE[$type];
}
if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this with standard category code after migration of llx_bank_categ into llx_categorie if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this with standard category code after migration of llx_bank_categ into llx_categorie
// Load bank categories // Load bank categories
@ -1509,11 +1554,14 @@ class Categorie extends CommonObject
$sql .= " WHERE type = ".$this->MAP_ID[$type]; $sql .= " WHERE type = ".$this->MAP_ID[$type];
$sql .= " AND entity IN (".getEntity('category').")"; $sql .= " AND entity IN (".getEntity('category').")";
if ($nom) { if ($nom) {
if (!$exact) if (!$exact) {
$nom = '%'.str_replace('*', '%', $nom).'%'; $nom = '%'.str_replace('*', '%', $nom).'%';
if (!$case) }
if (!$case) {
$sql .= " AND label LIKE '".$this->db->escape($nom)."'"; $sql .= " AND label LIKE '".$this->db->escape($nom)."'";
else $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'"; } else {
$sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
}
} }
if ($id) { if ($id) {
$sql .= " AND rowid = '".$id."'"; $sql .= " AND rowid = '".$id."'";
@ -1554,7 +1602,9 @@ class Categorie extends CommonObject
// Check contrast with background and correct text color // Check contrast with background and correct text color
$forced_color = 'categtextwhite'; $forced_color = 'categtextwhite';
if ($this->color) { if ($this->color) {
if (colorIsLight($this->color)) $forced_color = 'categtextblack'; if (colorIsLight($this->color)) {
$forced_color = 'categtextblack';
}
} }
$link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : '')).'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip '.$forced_color.'">'; $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : '')).'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip '.$forced_color.'">';
@ -1563,9 +1613,15 @@ class Categorie extends CommonObject
$picto = 'category'; $picto = 'category';
if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); if ($withpicto) {
if ($withpicto && $withpicto != 2) $result .= ' '; $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
if ($withpicto != 2) $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend; }
if ($withpicto && $withpicto != 2) {
$result .= ' ';
}
if ($withpicto != 2) {
$result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend;
}
return $result; return $result;
} }
@ -1653,13 +1709,18 @@ class Categorie extends CommonObject
// Objet // Objet
$obj = array(); $obj = array();
$obj['photo'] = $photo; $obj['photo'] = $photo;
if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; if ($photo_vignette && is_file($dirthumb.$photo_vignette)) {
else $obj['photo_vignette'] = ""; $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
} else {
$obj['photo_vignette'] = "";
}
$tabobj[$nbphoto - 1] = $obj; $tabobj[$nbphoto - 1] = $obj;
// On continue ou on arrete de boucler // On continue ou on arrete de boucler
if ($nbmax && $nbphoto >= $nbmax) break; if ($nbmax && $nbphoto >= $nbmax) {
break;
}
} }
} }
@ -1764,8 +1825,9 @@ class Categorie extends CommonObject
} }
// on ne sauvegarde pas des champs vides // on ne sauvegarde pas des champs vides
if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) {
dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
}
if (!$this->db->query($sql2)) { if (!$this->db->query($sql2)) {
$this->error = $this->db->lasterror(); $this->error = $this->db->lasterror();
return -1; return -1;
@ -1876,7 +1938,9 @@ class Categorie extends CommonObject
*/ */
public static function getFilterJoinQuery($type, $rowIdName) public static function getFilterJoinQuery($type, $rowIdName)
{ {
if ($type == 'bank_account') $type = 'account'; if ($type == 'bank_account') {
$type = 'account';
}
return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type; return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type;
} }
@ -1891,7 +1955,9 @@ class Categorie extends CommonObject
*/ */
public static function getFilterSelectQuery($type, $rowIdName, $searchList) public static function getFilterSelectQuery($type, $rowIdName, $searchList)
{ {
if ($type == 'bank_account') $type = 'account'; if ($type == 'bank_account') {
$type = 'account';
}
if (empty($searchList) && !is_array($searchList)) { if (empty($searchList) && !is_array($searchList)) {
return ""; return "";

View File

@ -62,7 +62,9 @@ if ($result <= 0) {
} }
$type = $object->type; $type = $object->type;
if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility if (is_numeric($type)) {
$type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility
}
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($object->table_element); $extrafields->fetch_name_optionals_label($object->table_element);
@ -105,10 +107,11 @@ if ($action == 'update' && $user->rights->categorie->creer) {
} }
if (!$error && empty($object->error)) { if (!$error && empty($object->error)) {
$ret = $extrafields->setOptionalsFromPost(null, $object); $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
if (!$error && $object->update($user) > 0) if (!$error && $object->update($user) > 0) {
{
if ($backtopage) { if ($backtopage) {
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;

View File

@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->load("categories"); $langs->load("categories");
if (!$user->rights->categorie->lire) accessforbidden(); if (!$user->rights->categorie->lire) {
accessforbidden();
}
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$type = (GETPOST('type', 'aZ09') ? GETPOST('type', 'aZ09') : Categorie::TYPE_PRODUCT); $type = (GETPOST('type', 'aZ09') ? GETPOST('type', 'aZ09') : Categorie::TYPE_PRODUCT);
@ -42,7 +44,9 @@ $catname = GETPOST('catname', 'alpha');
$nosearch = GETPOST('nosearch', 'int'); $nosearch = GETPOST('nosearch', 'int');
$categstatic = new Categorie($db); $categstatic = new Categorie($db);
if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility if (is_numeric($type)) {
$type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility
}
/* /*
@ -54,11 +58,15 @@ $form = new Form($db);
$moreparam = ($nosearch ? '&nosearch=1' : ''); $moreparam = ($nosearch ? '&nosearch=1' : '');
$typetext = $type; $typetext = $type;
if ($type == Categorie::TYPE_ACCOUNT) $title = $langs->trans('AccountsCategoriesArea'); if ($type == Categorie::TYPE_ACCOUNT) {
elseif ($type == Categorie::TYPE_WAREHOUSE) $title = $langs->trans('StocksCategoriesArea'); $title = $langs->trans('AccountsCategoriesArea');
elseif ($type == Categorie::TYPE_ACTIONCOMM) $title = $langs->trans('ActionCommCategoriesArea'); } elseif ($type == Categorie::TYPE_WAREHOUSE) {
elseif ($type == Categorie::TYPE_WEBSITE_PAGE) $title = $langs->trans('WebsitePagesCategoriesArea'); $title = $langs->trans('StocksCategoriesArea');
else { } elseif ($type == Categorie::TYPE_ACTIONCOMM) {
$title = $langs->trans('ActionCommCategoriesArea');
} elseif ($type == Categorie::TYPE_WEBSITE_PAGE) {
$title = $langs->trans('WebsitePagesCategoriesArea');
} else {
$title = $langs->trans(ucfirst($type).'sCategoriesArea'); $title = $langs->trans(ucfirst($type).'sCategoriesArea');
} }
@ -100,15 +108,13 @@ if (empty($nosearch)) {
/* /*
* Categories found * Categories found
*/ */
if ($catname || $id > 0) if ($catname || $id > 0) {
{
$cats = $categstatic->rechercher($id, $catname, $typetext); $cats = $categstatic->rechercher($id, $catname, $typetext);
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("FoundCats").'</td></tr>'; print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("FoundCats").'</td></tr>';
foreach ($cats as $cat) foreach ($cats as $cat) {
{
$color = $categstatic->color ? ' style="background: #'.sprintf("%06s", $categstatic->color).';"' : ' style="background: #bbb"'; $color = $categstatic->color ? ' style="background: #'.sprintf("%06s", $categstatic->color).';"' : ' style="background: #bbb"';
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
@ -128,7 +134,9 @@ if (empty($nosearch)) {
print "\t</tr>\n"; print "\t</tr>\n";
} }
print "</table>"; print "</table>";
} else print '&nbsp;'; } else {
print '&nbsp;';
}
print '</div></div>'; print '</div></div>';
} }
@ -143,19 +151,25 @@ $cate_arbo = $categstatic->get_full_arbo($typetext);
$fulltree = $cate_arbo; $fulltree = $cate_arbo;
// Load possible missing includes // Load possible missing includes
if ($conf->global->CATEGORY_SHOW_COUNTS) if ($conf->global->CATEGORY_SHOW_COUNTS) {
{ if ($type == Categorie::TYPE_MEMBER) {
if ($type == Categorie::TYPE_MEMBER) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
if ($type == Categorie::TYPE_ACCOUNT) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; }
if ($type == Categorie::TYPE_PROJECT) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if ($type == Categorie::TYPE_ACCOUNT) {
if ($type == Categorie::TYPE_USER) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
}
if ($type == Categorie::TYPE_PROJECT) {
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
}
if ($type == Categorie::TYPE_USER) {
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
}
} }
// Define data (format for treeview) // Define data (format for treeview)
$data = array(); $data = array();
$data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>'');
foreach ($fulltree as $key => $val) foreach ($fulltree as $key => $val) {
{
$categstatic->id = $val['id']; $categstatic->id = $val['id'];
$categstatic->ref = $val['label']; $categstatic->ref = $val['label'];
$categstatic->color = $val['color']; $categstatic->color = $val['color'];
@ -163,8 +177,7 @@ foreach ($fulltree as $key => $val)
$desc = dol_htmlcleanlastbr($val['description']); $desc = dol_htmlcleanlastbr($val['description']);
$counter = ''; $counter = '';
if ($conf->global->CATEGORY_SHOW_COUNTS) if ($conf->global->CATEGORY_SHOW_COUNTS) {
{
// we need only a count of the elements, so it is enough to consume only the id's from the database // we need only a count of the elements, so it is enough to consume only the id's from the database
$elements = $type == Categorie::TYPE_ACCOUNT $elements = $type == Categorie::TYPE_ACCOUNT
? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account" ? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account"
@ -206,15 +219,13 @@ foreach ($fulltree as $key => $val)
print '<table class="liste nohover" width="100%">'; print '<table class="liste nohover" width="100%">';
print '<tr class="liste_titre"><td>'.$langs->trans("Categories").'</td><td></td><td class="right">'; print '<tr class="liste_titre"><td>'.$langs->trans("Categories").'</td><td></td><td class="right">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print '<div id="iddivjstreecontrol"><a class="notasortlink" href="#">'.img_picto('', 'folder', 'class="paddingright"').$langs->trans("UndoExpandAll").'</a> | <a class="notasortlink" href="#">'.img_picto('', 'folder-open', 'class="paddingright"').$langs->trans("ExpandAll").'</a></div>'; print '<div id="iddivjstreecontrol"><a class="notasortlink" href="#">'.img_picto('', 'folder', 'class="paddingright"').$langs->trans("UndoExpandAll").'</a> | <a class="notasortlink" href="#">'.img_picto('', 'folder-open', 'class="paddingright"').$langs->trans("ExpandAll").'</a></div>';
} }
print '</td></tr>'; print '</td></tr>';
$nbofentries = (count($data) - 1); $nbofentries = (count($data) - 1);
if ($nbofentries > 0) if ($nbofentries > 0) {
{
print '<tr class="pair"><td colspan="3">'; print '<tr class="pair"><td colspan="3">';
tree_recur($data, $data[0], 0); tree_recur($data, $data[0], 0);
print '</td></tr>'; print '</td></tr>';

View File

@ -40,7 +40,9 @@ $id = GETPOST('id', 'int');
$label = GETPOST('label', 'alpha'); $label = GETPOST('label', 'alpha');
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'categorie', $id, '&category'); $result = restrictedArea($user, 'categorie', $id, '&category');
$object = new Categorie($db); $object = new Categorie($db);
@ -50,7 +52,9 @@ if ($result <= 0) {
} }
$type = $object->type; $type = $object->type;
if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility if (is_numeric($type)) {
$type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility
}
/* /*
* View * View

View File

@ -41,8 +41,7 @@ $label = GETPOST('label', 'alpha');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm'); $confirm = GETPOST('confirm');
if ($id == '' && $label == '') if ($id == '' && $label == '') {
{
dol_print_error('', 'Missing parameter id'); dol_print_error('', 'Missing parameter id');
exit(); exit();
} }
@ -57,7 +56,9 @@ if ($result <= 0) {
} }
$type = $object->type; $type = $object->type;
if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility if (is_numeric($type)) {
$type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility
}
$upload_dir = $conf->categorie->multidir_output[$object->entity]; $upload_dir = $conf->categorie->multidir_output[$object->entity];
@ -65,16 +66,12 @@ $upload_dir = $conf->categorie->multidir_output[$object->entity];
* Actions * Actions
*/ */
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) {
{
if ($object->id) { if ($object->id) {
$file = $_FILES['userfile']; $file = $_FILES['userfile'];
if (is_array($file['name']) && count($file['name']) > 0) if (is_array($file['name']) && count($file['name']) > 0) {
{ foreach ($file['name'] as $i => $name) {
foreach ($file['name'] as $i => $name) if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) {
{
if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i]))
{
setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles'));
unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]); unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]);
} }
@ -87,13 +84,11 @@ if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sen
} }
} }
if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) {
{
$object->delete_photo($upload_dir."/".$_GET["file"]); $object->delete_photo($upload_dir."/".$_GET["file"]);
} }
if ($action == 'addthumb' && $_GET["file"]) if ($action == 'addthumb' && $_GET["file"]) {
{
$object->addThumbs($upload_dir."/".$_GET["file"]); $object->addThumbs($upload_dir."/".$_GET["file"]);
} }
@ -107,8 +102,7 @@ llxHeader("", "", $langs->trans("Categories"));
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
if ($object->id) if ($object->id) {
{
$title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $title = Categorie::$MAP_TYPE_TITLE_AREA[$type];
$head = categories_prepare_head($object, $type); $head = categories_prepare_head($object, $type);
@ -119,8 +113,7 @@ if ($object->id)
$object->ref = $object->label; $object->ref = $object->label;
$morehtmlref = '<br><div class="refidno"><a href="'.DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type.'">'.$langs->trans("Root").'</a> >> '; $morehtmlref = '<br><div class="refidno"><a href="'.DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type.'">'.$langs->trans("Root").'</a> >> ';
$ways = $object->print_all_ways(" &gt;&gt; ", '', 1); $ways = $object->print_all_ways(" &gt;&gt; ", '', 1);
foreach ($ways as $way) foreach ($ways as $way) {
{
$morehtmlref .= $way."<br>\n"; $morehtmlref .= $way."<br>\n";
} }
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
@ -130,8 +123,7 @@ if ($object->id)
/* /*
* Confirmation de la suppression de photo * Confirmation de la suppression de photo
*/ */
if ($action == 'delete') if ($action == 'delete') {
{
print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1);
} }
@ -168,10 +160,8 @@ if ($object->id)
print '<div class="tabsAction">'."\n"; print '<div class="tabsAction">'."\n";
if ($action != 'ajout_photo' && $user->rights->categorie->creer) if ($action != 'ajout_photo' && $user->rights->categorie->creer) {
{ if (!empty($conf->global->MAIN_UPLOAD_DOC)) {
if (!empty($conf->global->MAIN_UPLOAD_DOC))
{
print '<a class="butAction hideonsmartphone" href="'.$_SERVER['PHP_SELF'].'?action=ajout_photo&amp;id='.$object->id.'&amp;type='.$type.'">'; print '<a class="butAction hideonsmartphone" href="'.$_SERVER['PHP_SELF'].'?action=ajout_photo&amp;id='.$object->id.'&amp;type='.$type.'">';
print $langs->trans("AddPhoto").'</a>'; print $langs->trans("AddPhoto").'</a>';
} else { } else {
@ -185,16 +175,14 @@ if ($object->id)
/* /*
* Ajouter une photo * Ajouter une photo
*/ */
if ($action == 'ajout_photo' && $user->rights->categorie->creer && !empty($conf->global->MAIN_UPLOAD_DOC)) if ($action == 'ajout_photo' && $user->rights->categorie->creer && !empty($conf->global->MAIN_UPLOAD_DOC)) {
{
// Affiche formulaire upload // Affiche formulaire upload
$formfile = new FormFile($db); $formfile = new FormFile($db);
$formfile->form_attach_new_file($_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;type='.$type, $langs->trans("AddPhoto"), 1, '', $user->rights->categorie->creer, 50, $object, '', false, '', 0); $formfile->form_attach_new_file($_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;type='.$type, $langs->trans("AddPhoto"), 1, '', $user->rights->categorie->creer, 50, $object, '', false, '', 0);
} }
// Affiche photos // Affiche photos
if ($action != 'ajout_photo') if ($action != 'ajout_photo') {
{
$nbphoto = 0; $nbphoto = 0;
$nbbyrow = 5; $nbbyrow = 5;
@ -206,23 +194,24 @@ if ($object->id)
$listofphoto = $object->liste_photos($dir); $listofphoto = $object->liste_photos($dir);
if (is_array($listofphoto) && count($listofphoto)) if (is_array($listofphoto) && count($listofphoto)) {
{
print '<br>'; print '<br>';
print '<table width="100%" valign="top" align="center">'; print '<table width="100%" valign="top" align="center">';
foreach ($listofphoto as $key => $obj) foreach ($listofphoto as $key => $obj) {
{
$nbphoto++; $nbphoto++;
if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print '<tr align=center valign=middle border=1>'; if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) {
if ($nbbyrow) print '<td width="'.ceil(100 / $nbbyrow).'%" class="photo">'; print '<tr align=center valign=middle border=1>';
}
if ($nbbyrow) {
print '<td width="'.ceil(100 / $nbbyrow).'%" class="photo">';
}
print '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart=category&entity='.$object->entity.'&file='.urlencode($pdir.$obj['photo']).'" alt="Taille origine" target="_blank">'; print '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart=category&entity='.$object->entity.'&file='.urlencode($pdir.$obj['photo']).'" alt="Taille origine" target="_blank">';
// Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine
if ($obj['photo_vignette']) if ($obj['photo_vignette']) {
{
$filename = $obj['photo_vignette']; $filename = $obj['photo_vignette'];
} else { } else {
$filename = $obj['photo']; $filename = $obj['photo'];
@ -243,22 +232,23 @@ if ($object->id)
print '<br>'; print '<br>';
// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) {
{
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addthumb&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addthumb&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
} }
if ($user->rights->categorie->creer) if ($user->rights->categorie->creer) {
{
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">'; print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">';
print img_delete().'</a>'; print img_delete().'</a>';
} }
if ($nbbyrow) print '</td>'; if ($nbbyrow) {
if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print '</tr>'; print '</td>';
}
if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) {
print '</tr>';
}
} }
// Ferme tableau // Ferme tableau
while ($nbphoto % $nbbyrow) while ($nbphoto % $nbbyrow) {
{
print '<td width="'.ceil(100 / $nbbyrow).'%">&nbsp;</td>'; print '<td width="'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
$nbphoto++; $nbphoto++;
} }
@ -266,8 +256,7 @@ if ($object->id)
print '</table>'; print '</table>';
} }
if ($nbphoto < 1) if ($nbphoto < 1) {
{
print '<div class="opacitymedium">'.$langs->trans("NoPhotoYet")."</div>"; print '<div class="opacitymedium">'.$langs->trans("NoPhotoYet")."</div>";
} }
} }

View File

@ -40,8 +40,7 @@ $label = GETPOST('label', 'alpha');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'alpha'); $cancel = GETPOST('cancel', 'alpha');
if ($id == '' && $label == '') if ($id == '' && $label == '') {
{
dol_print_error('', 'Missing parameter id'); dol_print_error('', 'Missing parameter id');
exit(); exit();
} }
@ -56,7 +55,9 @@ if ($result <= 0) {
} }
$type = $object->type; $type = $object->type;
if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility if (is_numeric($type)) {
$type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility
}
/* /*
* Actions * Actions
@ -64,8 +65,7 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar
$error = 0; $error = 0;
// retour a l'affichage des traduction si annulation // retour a l'affichage des traduction si annulation
if ($cancel == $langs->trans("Cancel")) if ($cancel == $langs->trans("Cancel")) {
{
$action = ''; $action = '';
} }
@ -73,8 +73,7 @@ if ($cancel == $langs->trans("Cancel"))
// Validation de l'ajout // Validation de l'ajout
if ($action == 'vadd' && if ($action == 'vadd' &&
$cancel != $langs->trans("Cancel") && $cancel != $langs->trans("Cancel") &&
($user->rights->categorie->creer)) ($user->rights->categorie->creer)) {
{
$object->fetch($id); $object->fetch($id);
$current_lang = $langs->getDefaultLang(); $current_lang = $langs->getDefaultLang();
@ -106,7 +105,9 @@ $cancel != $langs->trans("Cancel") &&
// sauvegarde en base // sauvegarde en base
$res = $object->setMultiLangs($user); $res = $object->setMultiLangs($user);
if ($res < 0) $error++; if ($res < 0) {
$error++;
}
} }
} }
@ -121,13 +122,11 @@ $cancel != $langs->trans("Cancel") &&
// Validation de l'edition // Validation de l'edition
if ($action == 'vedit' && if ($action == 'vedit' &&
$cancel != $langs->trans("Cancel") && $cancel != $langs->trans("Cancel") &&
($user->rights->categorie->creer)) ($user->rights->categorie->creer)) {
{
$object->fetch($id); $object->fetch($id);
$current_lang = $langs->getDefaultLang(); $current_lang = $langs->getDefaultLang();
foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet foreach ($object->multilangs as $key => $value) { // enregistrement des nouvelles valeurs dans l'objet
{
$libelle = GETPOST('libelle-'.$key, 'alpha'); $libelle = GETPOST('libelle-'.$key, 'alpha');
$desc = GETPOST('desc-'.$key); $desc = GETPOST('desc-'.$key);
@ -147,7 +146,9 @@ $cancel != $langs->trans("Cancel") &&
if (!$error) { if (!$error) {
$res = $object->setMultiLangs($user); $res = $object->setMultiLangs($user);
if ($res < 0) $error++; if ($res < 0) {
$error++;
}
} }
if ($error) { if ($error) {
@ -175,10 +176,8 @@ $head = categories_prepare_head($object, $type);
// Calculate $cnt_trans // Calculate $cnt_trans
$cnt_trans = 0; $cnt_trans = 0;
if (!empty($object->multilangs)) if (!empty($object->multilangs)) {
{ foreach ($object->multilangs as $key => $value) {
foreach ($object->multilangs as $key => $value)
{
$cnt_trans++; $cnt_trans++;
} }
} }
@ -232,12 +231,12 @@ print dol_get_fiche_end();
print "\n<div class=\"tabsAction\">\n"; print "\n<div class=\"tabsAction\">\n";
if ($action == '') if ($action == '') {
{ if ($user->rights->produit->creer || $user->rights->service->creer) {
if ($user->rights->produit->creer || $user->rights->service->creer)
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=add&id='.$object->id.'&type='.$type.'">'.$langs->trans('Add').'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=add&id='.$object->id.'&type='.$type.'">'.$langs->trans('Add').'</a>';
if ($cnt_trans > 0) print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&id='.$object->id.'&type='.$type.'">'.$langs->trans('Update').'</a>'; if ($cnt_trans > 0) {
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&id='.$object->id.'&type='.$type.'">'.$langs->trans('Update').'</a>';
}
} }
} }
@ -245,8 +244,7 @@ print "\n</div>\n";
if ($action == 'edit') if ($action == 'edit') {
{
//WYSIWYG Editor //WYSIWYG Editor
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
@ -256,10 +254,8 @@ if ($action == 'edit')
print '<input type="hidden" name="id" value="'.$object->id.'">'; print '<input type="hidden" name="id" value="'.$object->id.'">';
print '<input type="hidden" name="type" value="'.$type.'">'; print '<input type="hidden" name="type" value="'.$type.'">';
if (!empty($object->multilangs)) if (!empty($object->multilangs)) {
{ foreach ($object->multilangs as $key => $value) {
foreach ($object->multilangs as $key => $value)
{
print "<br><b><u>".$langs->trans('Language_'.$key)." :</u></b><br>"; print "<br><b><u>".$langs->trans('Language_'.$key)." :</u></b><br>";
print '<table class="border centpercent">'; print '<table class="border centpercent">';
@ -287,27 +283,27 @@ if ($action == 'edit')
print '</div>'; print '</div>';
print '</form>'; print '</form>';
} elseif ($action != 'add') } elseif ($action != 'add') {
{ if ($cnt_trans) {
if ($cnt_trans) print '<div class="underbanner clearboth"></div>'; print '<div class="underbanner clearboth"></div>';
}
if (!empty($object->multilangs)) if (!empty($object->multilangs)) {
{ foreach ($object->multilangs as $key => $value) {
foreach ($object->multilangs as $key => $value)
{
$s = picto_from_langcode($key); $s = picto_from_langcode($key);
print '<table class="border centpercent">'; print '<table class="border centpercent">';
print '<tr class="liste_titre"><td colspan="2">'.($s ? $s.' ' : '')." <b>".$langs->trans('Language_'.$key).":</b> ".'<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'&langtodelete='.$key.'&type='.$type.'">'.img_delete('', '').'</a></td></tr>'; print '<tr class="liste_titre"><td colspan="2">'.($s ? $s.' ' : '')." <b>".$langs->trans('Language_'.$key).":</b> ".'<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'&langtodelete='.$key.'&type='.$type.'">'.img_delete('', '').'</a></td></tr>';
print '<tr><td class="titlefield">'.$langs->trans('Label').'</td><td>'.$object->multilangs[$key]["label"].'</td></tr>'; print '<tr><td class="titlefield">'.$langs->trans('Label').'</td><td>'.$object->multilangs[$key]["label"].'</td></tr>';
print '<tr><td>'.$langs->trans('Description').'</td><td>'.$object->multilangs[$key]["description"].'</td></tr>'; print '<tr><td>'.$langs->trans('Description').'</td><td>'.$object->multilangs[$key]["description"].'</td></tr>';
if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) {
{
print '<tr><td>'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')</td><td>'.$object->multilangs[$key]["other"].'</td></tr>'; print '<tr><td>'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')</td><td>'.$object->multilangs[$key]["other"].'</td></tr>';
} }
print '</table>'; print '</table>';
} }
} }
if (!$cnt_trans && $action != 'add') print '<div class="opacitymedium">'.$langs->trans('NoTranslation').'</div>'; if (!$cnt_trans && $action != 'add') {
print '<div class="opacitymedium">'.$langs->trans('NoTranslation').'</div>';
}
} }
@ -315,8 +311,7 @@ if ($action == 'edit')
* Form to add a new translation * Form to add a new translation
*/ */
if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) {
{
//WYSIWYG Editor //WYSIWYG Editor
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';

View File

@ -57,13 +57,14 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if ($id == "" && $label == "") if ($id == "" && $label == "") {
{
dol_print_error('', 'Missing parameter id'); dol_print_error('', 'Missing parameter id');
exit(); exit();
} }
@ -78,7 +79,9 @@ if ($result <= 0) {
} }
$type = $object->type; $type = $object->type;
if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility if (is_numeric($type)) {
$type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility
}
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($object->table_element); $extrafields->fetch_name_optionals_label($object->table_element);
@ -90,8 +93,7 @@ $hookmanager->initHooks(array('categorycard', 'globalcard'));
* Actions * Actions
*/ */
if ($confirm == 'no') if ($confirm == 'no') {
{
if ($backtopage) { if ($backtopage) {
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
@ -101,26 +103,21 @@ if ($confirm == 'no')
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
// Remove element from category // Remove element from category
if ($id > 0 && $removeelem > 0) if ($id > 0 && $removeelem > 0) {
{ if ($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) {
if ($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer))
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
$tmpobject = new Product($db); $tmpobject = new Product($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
$elementtype = 'product'; $elementtype = 'product';
} elseif ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) } elseif ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) {
{
$tmpobject = new Societe($db); $tmpobject = new Societe($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
$elementtype = 'supplier'; $elementtype = 'supplier';
} elseif ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) } elseif ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) {
{
$tmpobject = new Societe($db); $tmpobject = new Societe($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
$elementtype = 'customer'; $elementtype = 'customer';
} elseif ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) } elseif ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) {
{
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
$tmpobject = new Adherent($db); $tmpobject = new Adherent($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
@ -130,20 +127,17 @@ if ($id > 0 && $removeelem > 0)
$tmpobject = new Contact($db); $tmpobject = new Contact($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
$elementtype = 'contact'; $elementtype = 'contact';
} elseif ($type == Categorie::TYPE_ACCOUNT && $user->rights->banque->configurer) } elseif ($type == Categorie::TYPE_ACCOUNT && $user->rights->banque->configurer) {
{
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
$tmpobject = new Account($db); $tmpobject = new Account($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
$elementtype = 'account'; $elementtype = 'account';
} elseif ($type == Categorie::TYPE_PROJECT && $user->rights->projet->creer) } elseif ($type == Categorie::TYPE_PROJECT && $user->rights->projet->creer) {
{
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$tmpobject = new Project($db); $tmpobject = new Project($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
$elementtype = 'project'; $elementtype = 'project';
} elseif ($type == Categorie::TYPE_USER && $user->rights->user->user->creer) } elseif ($type == Categorie::TYPE_USER && $user->rights->user->user->creer) {
{
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
$tmpobject = new User($db); $tmpobject = new User($db);
$result = $tmpobject->fetch($removeelem); $result = $tmpobject->fetch($removeelem);
@ -151,13 +145,13 @@ if ($id > 0 && $removeelem > 0)
} }
$result = $object->del_type($tmpobject, $elementtype); $result = $object->del_type($tmpobject, $elementtype);
if ($result < 0) dol_print_error('', $object->error); if ($result < 0) {
dol_print_error('', $object->error);
}
} }
if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confirm == 'yes') if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confirm == 'yes') {
{ if ($object->delete($user) >= 0) {
if ($object->delete($user) >= 0)
{
if ($backtopage) { if ($backtopage) {
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
@ -174,20 +168,16 @@ if ($elemid && $action == 'addintocategory' &&
(($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) || (($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) ||
($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) || ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) ||
($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer)
)) )) {
{ if ($type == Categorie::TYPE_PRODUCT) {
if ($type == Categorie::TYPE_PRODUCT)
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
$newobject = new Product($db); $newobject = new Product($db);
$elementtype = 'product'; $elementtype = 'product';
} elseif ($type == Categorie::TYPE_CUSTOMER) } elseif ($type == Categorie::TYPE_CUSTOMER) {
{
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
$newobject = new Societe($db); $newobject = new Societe($db);
$elementtype = 'customer'; $elementtype = 'customer';
} elseif ($type == Categorie::TYPE_SUPPLIER) } elseif ($type == Categorie::TYPE_SUPPLIER) {
{
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
$newobject = new Societe($db); $newobject = new Societe($db);
$elementtype = 'supplier'; $elementtype = 'supplier';
@ -196,12 +186,10 @@ if ($elemid && $action == 'addintocategory' &&
// TODO Add into categ // TODO Add into categ
$result = $object->add_type($newobject, $elementtype); $result = $object->add_type($newobject, $elementtype);
if ($result >= 0) if ($result >= 0) {
{
setEventMessages($langs->trans("WasAddedSuccessfully", $newobject->ref), null, 'mesgs'); setEventMessages($langs->trans("WasAddedSuccessfully", $newobject->ref), null, 'mesgs');
} else { } else {
if ($cat->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') if ($cat->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
{
setEventMessages($langs->trans("ObjectAlreadyLinkedToCategory"), null, 'warnings'); setEventMessages($langs->trans("ObjectAlreadyLinkedToCategory"), null, 'warnings');
} else { } else {
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
@ -233,8 +221,7 @@ $object->next_prev_filter = ' type = '.$object->type;
$object->ref = $object->label; $object->ref = $object->label;
$morehtmlref = '<br><div class="refidno"><a href="'.DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type.'">'.$langs->trans("Root").'</a> >> '; $morehtmlref = '<br><div class="refidno"><a href="'.DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type.'">'.$langs->trans("Root").'</a> >> ';
$ways = $object->print_all_ways(" &gt;&gt; ", '', 1); $ways = $object->print_all_ways(" &gt;&gt; ", '', 1);
foreach ($ways as $way) foreach ($ways as $way) {
{
$morehtmlref .= $way."<br>\n"; $morehtmlref .= $way."<br>\n";
} }
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
@ -246,8 +233,7 @@ dol_banner_tab($object, 'label', $linkback, ($user->socid ? 0 : 1), 'label', 'la
* Confirmation suppression * Confirmation suppression
*/ */
if ($action == 'delete') if ($action == 'delete') {
{
if ($backtopage) { if ($backtopage) {
print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&backtopage='.urlencode($backtopage), $langs->trans('DeleteCategory'), $langs->trans('ConfirmDeleteCategory'), 'confirm_delete', '', '', 2); print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&backtopage='.urlencode($backtopage), $langs->trans('DeleteCategory'), $langs->trans('ConfirmDeleteCategory'), 'confirm_delete', '', '', 2);
} else { } else {
@ -288,16 +274,16 @@ print dol_get_fiche_end();
print "<div class='tabsAction'>\n"; print "<div class='tabsAction'>\n";
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
if ($user->rights->categorie->creer) if ($user->rights->categorie->creer) {
{
$socid = ($object->socid ? "&socid=".$object->socid : ""); $socid = ($object->socid ? "&socid=".$object->socid : "");
print '<a class="butAction" href="edit.php?id='.$object->id.$socid.'&type='.$type.'">'.$langs->trans("Modify").'</a>'; print '<a class="butAction" href="edit.php?id='.$object->id.$socid.'&type='.$type.'">'.$langs->trans("Modify").'</a>';
} }
if ($user->rights->categorie->supprimer) if ($user->rights->categorie->supprimer) {
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$object->id.'&type='.$type.'&backtolist='.urlencode($backtolist).'">'.$langs->trans("Delete").'</a>'; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$object->id.'&type='.$type.'&backtolist='.urlencode($backtolist).'">'.$langs->trans("Delete").'</a>';
} }
} }
@ -305,8 +291,7 @@ if (empty($reshook)) {
print "</div>"; print "</div>";
$newcardbutton = ''; $newcardbutton = '';
if (!empty($user->rights->categorie->creer)) if (!empty($user->rights->categorie->creer)) {
{
$link = DOL_URL_ROOT.'/categories/card.php'; $link = DOL_URL_ROOT.'/categories/card.php';
$link .= '?action=create'; $link .= '?action=create';
$link .= '&type='.$type; $link .= '&type='.$type;
@ -335,8 +320,7 @@ print '<td>'.$langs->trans("SubCats").'</td>';
print '<td></td>'; print '<td></td>';
print '<td class="right">'; print '<td class="right">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print '<div id="iddivjstreecontrol">'; print '<div id="iddivjstreecontrol">';
print '<a class="notasortlink" href="#">'.img_picto('', 'folder').' '.$langs->trans("UndoExpandAll").'</a>'; print '<a class="notasortlink" href="#">'.img_picto('', 'folder').' '.$langs->trans("UndoExpandAll").'</a>';
print " | "; print " | ";
@ -348,11 +332,9 @@ print '</td>';
print '</tr>'; print '</tr>';
$cats = $object->get_filles(); $cats = $object->get_filles();
if ($cats < 0) if ($cats < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} elseif (count($cats) < 1) } elseif (count($cats) < 1) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td colspan="3" class="opacitymedium">'.$langs->trans("NoSubCat").'</td>'; print '<td colspan="3" class="opacitymedium">'.$langs->trans("NoSubCat").'</td>';
print '</tr>'; print '</tr>';
@ -362,19 +344,25 @@ if ($cats < 0)
$fulltree = $categstatic->get_full_arbo($type, $object->id, 1); $fulltree = $categstatic->get_full_arbo($type, $object->id, 1);
// Load possible missing includes // Load possible missing includes
if ($conf->global->CATEGORY_SHOW_COUNTS) if ($conf->global->CATEGORY_SHOW_COUNTS) {
{ if ($type == Categorie::TYPE_MEMBER) {
if ($type == Categorie::TYPE_MEMBER) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
if ($type == Categorie::TYPE_ACCOUNT) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; }
if ($type == Categorie::TYPE_PROJECT) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if ($type == Categorie::TYPE_ACCOUNT) {
if ($type == Categorie::TYPE_USER) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
}
if ($type == Categorie::TYPE_PROJECT) {
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
}
if ($type == Categorie::TYPE_USER) {
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
}
} }
// Define data (format for treeview) // Define data (format for treeview)
$data = array(); $data = array();
$data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>'');
foreach ($fulltree as $key => $val) foreach ($fulltree as $key => $val) {
{
$categstatic->id = $val['id']; $categstatic->id = $val['id'];
$categstatic->ref = $val['label']; $categstatic->ref = $val['label'];
$categstatic->color = $val['color']; $categstatic->color = $val['color'];
@ -382,8 +370,7 @@ if ($cats < 0)
$desc = dol_htmlcleanlastbr($val['description']); $desc = dol_htmlcleanlastbr($val['description']);
$counter = ''; $counter = '';
if ($conf->global->CATEGORY_SHOW_COUNTS) if ($conf->global->CATEGORY_SHOW_COUNTS) {
{
// we need only a count of the elements, so it is enough to consume only the id's from the database // we need only a count of the elements, so it is enough to consume only the id's from the database
$elements = $type == Categorie::TYPE_ACCOUNT $elements = $type == Categorie::TYPE_ACCOUNT
? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account" ? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account"
@ -421,8 +408,7 @@ if ($cats < 0)
} }
$nbofentries = (count($data) - 1); $nbofentries = (count($data) - 1);
if ($nbofentries > 0) if ($nbofentries > 0) {
{
require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php';
print '<tr class="pair">'; print '<tr class="pair">';
print '<td colspan="3">'; print '<td colspan="3">';
@ -465,19 +451,16 @@ $typeid = $type;
// List of products or services (type is type of category) // List of products or services (type is type of category)
if ($type == Categorie::TYPE_PRODUCT) if ($type == Categorie::TYPE_PRODUCT) {
{
$permission = ($user->rights->produit->creer || $user->rights->service->creer); $permission = ($user->rights->produit->creer || $user->rights->service->creer);
$prods = $object->getObjectsInCateg($type, 0, $limit, $offset); $prods = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($prods < 0) if ($prods < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
// Form to add record into a category // Form to add record into a category
$showclassifyform = 1; $showclassifyform = 1;
if ($showclassifyform) if ($showclassifyform) {
{
print '<br>'; print '<br>';
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -510,13 +493,13 @@ if ($type == Categorie::TYPE_PRODUCT)
print '<table class="noborder centpercent">'."\n"; print '<table class="noborder centpercent">'."\n";
print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Ref").'</td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Ref").'</td></tr>'."\n";
if (count($prods) > 0) if (count($prods) > 0) {
{
$i = 0; $i = 0;
foreach ($prods as $prod) foreach ($prods as $prod) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -525,8 +508,7 @@ if ($type == Categorie::TYPE_PRODUCT)
print '<td class="tdtop">'.$prod->label."</td>\n"; print '<td class="tdtop">'.$prod->label."</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$prod->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$prod->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -544,19 +526,16 @@ if ($type == Categorie::TYPE_PRODUCT)
} }
} }
if ($type == Categorie::TYPE_CUSTOMER) if ($type == Categorie::TYPE_CUSTOMER) {
{
$permission = $user->rights->societe->creer; $permission = $user->rights->societe->creer;
$socs = $object->getObjectsInCateg($type, 0, $limit, $offset); $socs = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($socs < 0) if ($socs < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
// Form to add record into a category // Form to add record into a category
$showclassifyform = 1; $showclassifyform = 1;
if ($showclassifyform) if ($showclassifyform) {
{
print '<br>'; print '<br>';
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -588,13 +567,13 @@ if ($type == Categorie::TYPE_CUSTOMER)
print '<table class="noborder centpercent">'."\n"; print '<table class="noborder centpercent">'."\n";
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Name").'</td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Name").'</td></tr>'."\n";
if (count($socs) > 0) if (count($socs) > 0) {
{
$i = 0; $i = 0;
foreach ($socs as $key => $soc) foreach ($socs as $key => $soc) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -602,8 +581,7 @@ if ($type == Categorie::TYPE_CUSTOMER)
print "</td>\n"; print "</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -622,19 +600,16 @@ if ($type == Categorie::TYPE_CUSTOMER)
} }
if ($type == Categorie::TYPE_SUPPLIER) if ($type == Categorie::TYPE_SUPPLIER) {
{
$permission = $user->rights->societe->creer; $permission = $user->rights->societe->creer;
$socs = $object->getObjectsInCateg($type, 0, $limit, $offset); $socs = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($socs < 0) if ($socs < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
// Form to add record into a category // Form to add record into a category
$showclassifyform = 1; $showclassifyform = 1;
if ($showclassifyform) if ($showclassifyform) {
{
print '<br>'; print '<br>';
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -666,13 +641,13 @@ if ($type == Categorie::TYPE_SUPPLIER)
print '<table class="noborder centpercent">'."\n"; print '<table class="noborder centpercent">'."\n";
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Name")."</td></tr>\n"; print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Name")."</td></tr>\n";
if (count($socs) > 0) if (count($socs) > 0) {
{
$i = 0; $i = 0;
foreach ($socs as $soc) foreach ($socs as $soc) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -680,8 +655,7 @@ if ($type == Categorie::TYPE_SUPPLIER)
print "</td>\n"; print "</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -701,15 +675,13 @@ if ($type == Categorie::TYPE_SUPPLIER)
} }
// List of members // List of members
if ($type == Categorie::TYPE_MEMBER) if ($type == Categorie::TYPE_MEMBER) {
{
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
$permission = $user->rights->adherent->creer; $permission = $user->rights->adherent->creer;
$prods = $object->getObjectsInCateg($type, 0, $limit, $offset); $prods = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($prods < 0) if ($prods < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
@ -726,13 +698,13 @@ if ($type == Categorie::TYPE_MEMBER)
print "<table class='noborder' width='100%'>\n"; print "<table class='noborder' width='100%'>\n";
print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Name").'</td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Name").'</td></tr>'."\n";
if (count($prods) > 0) if (count($prods) > 0) {
{
$i = 0; $i = 0;
foreach ($prods as $key => $member) foreach ($prods as $key => $member) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -743,8 +715,7 @@ if ($type == Categorie::TYPE_MEMBER)
print '<td class="tdtop">'.$member->firstname."</td>\n"; print '<td class="tdtop">'.$member->firstname."</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$member->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$member->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -762,13 +733,11 @@ if ($type == Categorie::TYPE_MEMBER)
} }
// Categorie contact // Categorie contact
if ($type == Categorie::TYPE_CONTACT) if ($type == Categorie::TYPE_CONTACT) {
{
$permission = $user->rights->societe->creer; $permission = $user->rights->societe->creer;
$contacts = $object->getObjectsInCateg($type, 0, $limit, $offset); $contacts = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($contacts < 0) if ($contacts < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
@ -788,13 +757,13 @@ if ($type == Categorie::TYPE_CONTACT)
print '<table class="noborder centpercent">'."\n"; print '<table class="noborder centpercent">'."\n";
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Ref").'</td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Ref").'</td></tr>'."\n";
if (count($contacts) > 0) if (count($contacts) > 0) {
{
$i = 0; $i = 0;
foreach ($contacts as $key => $contact) foreach ($contacts as $key => $contact) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -802,8 +771,7 @@ if ($type == Categorie::TYPE_CONTACT)
print "</td>\n"; print "</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$contact->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$contact->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -822,15 +790,13 @@ if ($type == Categorie::TYPE_CONTACT)
} }
// List of bank accounts // List of bank accounts
if ($type == Categorie::TYPE_ACCOUNT) if ($type == Categorie::TYPE_ACCOUNT) {
{
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
$permission = $user->rights->banque->creer; $permission = $user->rights->banque->creer;
$accounts = $object->getObjectsInCateg($type, 0, $limit, $offset); $accounts = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($accounts < 0) if ($accounts < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
@ -847,13 +813,13 @@ if ($type == Categorie::TYPE_ACCOUNT)
print "<table class='noborder' width='100%'>\n"; print "<table class='noborder' width='100%'>\n";
print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Ref").'</td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Ref").'</td></tr>'."\n";
if (count($accounts) > 0) if (count($accounts) > 0) {
{
$i = 0; $i = 0;
foreach ($accounts as $key => $account) foreach ($accounts as $key => $account) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -863,8 +829,7 @@ if ($type == Categorie::TYPE_ACCOUNT)
print '<td class="tdtop">'.$account->number."</td>\n"; print '<td class="tdtop">'.$account->number."</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$account->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$account->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -882,15 +847,13 @@ if ($type == Categorie::TYPE_ACCOUNT)
} }
// List of Project // List of Project
if ($type == Categorie::TYPE_PROJECT) if ($type == Categorie::TYPE_PROJECT) {
{
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$permission = $user->rights->projet->creer; $permission = $user->rights->projet->creer;
$objects = $object->getObjectsInCateg($type, 0, $limit, $offset); $objects = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($objects < 0) if ($objects < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
@ -908,13 +871,13 @@ if ($type == Categorie::TYPE_PROJECT)
print "<table class='noborder' width='100%'>\n"; print "<table class='noborder' width='100%'>\n";
print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Ref").'</td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Ref").'</td></tr>'."\n";
if (count($objects) > 0) if (count($objects) > 0) {
{
$i = 0; $i = 0;
foreach ($objects as $key => $project) foreach ($objects as $key => $project) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -924,8 +887,7 @@ if ($type == Categorie::TYPE_PROJECT)
print '<td class="tdtop">'.$project->title."</td>\n"; print '<td class="tdtop">'.$project->title."</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$project->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$project->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -943,13 +905,11 @@ if ($type == Categorie::TYPE_PROJECT)
} }
// List of users // List of users
if ($type == Categorie::TYPE_USER) if ($type == Categorie::TYPE_USER) {
{
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
$users = $object->getObjectsInCateg($type); $users = $object->getObjectsInCateg($type);
if ($users < 0) if ($users < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
@ -969,11 +929,9 @@ if ($type == Categorie::TYPE_USER)
print "<table class='noborder' width='100%'>\n"; print "<table class='noborder' width='100%'>\n";
print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Users").' <span class="badge">'.$num.'</span></td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Users").' <span class="badge">'.$num.'</span></td></tr>'."\n";
if (count($users) > 0) if (count($users) > 0) {
{
// Use "$userentry" here, because "$user" is the current user // Use "$userentry" here, because "$user" is the current user
foreach ($users as $key => $userentry) foreach ($users as $key => $userentry) {
{
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
print $userentry->getNomUrl(1); print $userentry->getNomUrl(1);
@ -982,8 +940,7 @@ if ($type == Categorie::TYPE_USER)
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($user->rights->user->user->creer) if ($user->rights->user->user->creer) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$type."&amp;removeelem=".$userentry->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$type."&amp;removeelem=".$userentry->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');
@ -1002,15 +959,13 @@ if ($type == Categorie::TYPE_USER)
// List of warehouses // List of warehouses
if ($type == Categorie::TYPE_WAREHOUSE) if ($type == Categorie::TYPE_WAREHOUSE) {
{
$permission = $user->rights->stock->creer; $permission = $user->rights->stock->creer;
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$objects = $object->getObjectsInCateg($type, 0, $limit, $offset); $objects = $object->getObjectsInCateg($type, 0, $limit, $offset);
if ($objects < 0) if ($objects < 0) {
{
dol_print_error($db, $object->error, $object->errors); dol_print_error($db, $object->error, $object->errors);
} else { } else {
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
@ -1028,13 +983,13 @@ if ($type == Categorie::TYPE_WAREHOUSE)
print "<table class='noborder' width='100%'>\n"; print "<table class='noborder' width='100%'>\n";
print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Ref").'</td></tr>'."\n"; print '<tr class="liste_titre"><td colspan="4">'.$langs->trans("Ref").'</td></tr>'."\n";
if (count($objects) > 0) if (count($objects) > 0) {
{
$i = 0; $i = 0;
foreach ($objects as $key => $project) foreach ($objects as $key => $project) {
{
$i++; $i++;
if ($i > $limit) break; if ($i > $limit) {
break;
}
print "\t".'<tr class="oddeven">'."\n"; print "\t".'<tr class="oddeven">'."\n";
print '<td class="nowrap" valign="top">'; print '<td class="nowrap" valign="top">';
@ -1044,8 +999,7 @@ if ($type == Categorie::TYPE_WAREHOUSE)
print '<td class="tdtop">'.$project->title."</td>\n"; print '<td class="tdtop">'.$project->title."</td>\n";
// Link to delete from category // Link to delete from category
print '<td class="right">'; print '<td class="right">';
if ($permission) if ($permission) {
{
print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$project->id."'>"; print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$project->id."'>";
print $langs->trans("DeleteFromCat"); print $langs->trans("DeleteFromCat");
print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft');

View File

@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "other", "website")); $langs->loadLangs(array("admin", "other", "website"));
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$conf->dol_hide_leftmenu = 1; // Force hide of left menu. $conf->dol_hide_leftmenu = 1; // Force hide of left menu.
@ -41,17 +43,37 @@ $page = GETPOST('page', 'alpha');
$pageid = GETPOST('pageid', 'int'); $pageid = GETPOST('pageid', 'int');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
if (GETPOST('delete')) { $action = 'delete'; } if (GETPOST('delete')) {
if (GETPOST('preview')) $action = 'preview'; $action = 'delete';
if (GETPOST('create')) { $action = 'create'; } }
if (GETPOST('editmedia')) { $action = 'editmedia'; } if (GETPOST('preview')) {
if (GETPOST('editcss')) { $action = 'editcss'; } $action = 'preview';
if (GETPOST('editmenu')) { $action = 'editmenu'; } }
if (GETPOST('setashome')) { $action = 'setashome'; } if (GETPOST('create')) {
if (GETPOST('editmeta')) { $action = 'editmeta'; } $action = 'create';
if (GETPOST('editcontent')) { $action = 'editcontent'; } }
if (GETPOST('editmedia')) {
$action = 'editmedia';
}
if (GETPOST('editcss')) {
$action = 'editcss';
}
if (GETPOST('editmenu')) {
$action = 'editmenu';
}
if (GETPOST('setashome')) {
$action = 'setashome';
}
if (GETPOST('editmeta')) {
$action = 'editmeta';
}
if (GETPOST('editcontent')) {
$action = 'editcontent';
}
if (empty($action)) $action = 'preview'; if (empty($action)) {
$action = 'preview';
}
@ -60,13 +82,16 @@ if (empty($action)) $action = 'preview';
* Actions * Actions
*/ */
if (GETPOST('refreshsite')) $pageid = 0; // If we change the site, we reset the pageid. if (GETPOST('refreshsite')) {
if (GETPOST('refreshpage')) $action = 'preview'; $pageid = 0; // If we change the site, we reset the pageid.
}
if (GETPOST('refreshpage')) {
$action = 'preview';
}
// Add a collab page // Add a collab page
if ($action == 'add') if ($action == 'add') {
{
$db->begin(); $db->begin();
$objectpage->title = GETPOST('WEBSITE_TITLE'); $objectpage->title = GETPOST('WEBSITE_TITLE');
@ -74,23 +99,19 @@ if ($action == 'add')
$objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); $objectpage->description = GETPOST('WEBSITE_DESCRIPTION');
$objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); $objectpage->keywords = GETPOST('WEBSITE_KEYWORD');
if (empty($objectpage->title)) if (empty($objectpage->title)) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors');
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$res = $objectpage->create($user); $res = $objectpage->create($user);
if ($res <= 0) if ($res <= 0) {
{
$error++; $error++;
setEventMessages($objectpage->error, $objectpage->errors, 'errors'); setEventMessages($objectpage->error, $objectpage->errors, 'errors');
} }
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs');
$action = ''; $action = '';
@ -103,25 +124,21 @@ if ($action == 'add')
} }
// Update page // Update page
if ($action == 'delete') if ($action == 'delete') {
{
$db->begin(); $db->begin();
$res = $object->fetch(0, $website); $res = $object->fetch(0, $website);
$res = $objectpage->fetch($pageid, $object->fk_website); $res = $objectpage->fetch($pageid, $object->fk_website);
if ($res > 0) if ($res > 0) {
{
$res = $objectpage->delete($user); $res = $objectpage->delete($user);
if (!($res > 0)) if (!($res > 0)) {
{
$error++; $error++;
setEventMessages($objectpage->error, $objectpage->errors, 'errors'); setEventMessages($objectpage->error, $objectpage->errors, 'errors');
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs');
@ -149,15 +166,16 @@ llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', '
print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST"><div>'; print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST"><div>';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
if ($action == 'create') if ($action == 'create') {
{
print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="action" value="add">';
} }
// Add a margin under toolbar ? // Add a margin under toolbar ?
$style = ''; $style = '';
if ($action != 'preview' && $action != 'editcontent') $style = ' margin-bottom: 5px;'; if ($action != 'preview' && $action != 'editcontent') {
$style = ' margin-bottom: 5px;';
}
//var_dump($objectpage);exit; //var_dump($objectpage);exit;
print '<div class="centpercent websitebar">'; print '<div class="centpercent websitebar">';

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -146,8 +146,12 @@ class ActionCommReminder extends CommonObject
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled)) {
$this->fields['entity']['enabled'] = 0;
}
} }
/** /**
@ -225,16 +229,25 @@ class ActionCommReminder extends CommonObject
global $langs; global $langs;
$labelStatus = $langs->trans('ToDo'); $labelStatus = $langs->trans('ToDo');
if ($status == 1) $labelStatus = $langs->trans('Done'); if ($status == 1) {
elseif ($status == -1) $labelStatus = $langs->trans('Error'); $labelStatus = $langs->trans('Done');
} elseif ($status == -1) {
$labelStatus = $langs->trans('Error');
}
$labelStatusShort = $langs->trans('ToDo'); $labelStatusShort = $langs->trans('ToDo');
if ($status == 1) $labelStatus = $langs->trans('Done'); if ($status == 1) {
elseif ($status == -1) $labelStatus = $langs->trans('Error'); $labelStatus = $langs->trans('Done');
} elseif ($status == -1) {
$labelStatus = $langs->trans('Error');
}
$statusType = 'status5'; $statusType = 'status5';
if ($status == 1) $statusType = 'status4'; if ($status == 1) {
elseif ($status == -1) $statusType = 'status8'; $statusType = 'status4';
} elseif ($status == -1) {
$statusType = 'status8';
}
return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
} }

View File

@ -114,34 +114,50 @@ class AgendaEvents extends DolibarrApi
// case of external user // case of external user
$socid = 0; $socid = 0;
if (!empty(DolibarrApiAccess::$user->socid)) $socid = DolibarrApiAccess::$user->socid; if (!empty(DolibarrApiAccess::$user->socid)) {
$socid = DolibarrApiAccess::$user->socid;
}
// If the internal user must only see his customers, force searching by him // If the internal user must only see his customers, force searching by him
$search_sale = 0; $search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
if (empty($conf->societe->enabled)) $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists $search_sale = DolibarrApiAccess::$user->id;
}
if (empty($conf->societe->enabled)) {
$search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
}
$sql = "SELECT t.id as rowid"; $sql = "SELECT t.id as rowid";
if (!empty($conf->societe->enabled)) if (!empty($conf->societe->enabled)) {
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $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) if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $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."actioncomm as t"; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as t";
if (!empty($conf->societe->enabled)) if (!empty($conf->societe->enabled)) {
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
}
}
$sql .= ' WHERE t.entity IN ('.getEntity('agenda').')'; $sql .= ' WHERE t.entity IN ('.getEntity('agenda').')';
if (!empty($conf->societe->enabled)) if (!empty($conf->societe->enabled)) {
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
if ($user_ids) $sql .= " AND t.fk_user_action IN (".$user_ids.")"; $sql .= " AND t.fk_soc = sc.fk_soc";
if ($socid > 0) $sql .= " AND t.fk_soc = ".$socid; }
}
if ($user_ids) {
$sql .= " AND t.fk_user_action IN (".$user_ids.")";
}
if ($socid > 0) {
$sql .= " AND t.fk_soc = ".$socid;
}
// Insert sale filter // Insert sale filter
if ($search_sale > 0) if ($search_sale > 0) {
{
$sql .= " AND sc.fk_user = ".$search_sale; $sql .= " AND sc.fk_user = ".$search_sale;
} }
// Add sql filters // Add sql filters
if ($sqlfilters) if ($sqlfilters) {
{ if (!DolibarrApi::_checkFilters($sqlfilters)) {
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@ -150,8 +166,7 @@ class AgendaEvents extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -161,13 +176,11 @@ class AgendaEvents extends DolibarrApi
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$i = 0; $i = 0;
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$actioncomm_static = new ActionComm($this->db); $actioncomm_static = new ActionComm($this->db);
if ($actioncomm_static->fetch($obj->rowid)) { if ($actioncomm_static->fetch($obj->rowid)) {
@ -251,12 +264,15 @@ class AgendaEvents extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->actioncomm->$field = $value; $this->actioncomm->$field = $value;
} }
if ($this->actioncomm->update(DolibarrApiAccess::$user, 1) > 0) if ($this->actioncomm->update(DolibarrApiAccess::$user, 1) > 0) {
return $this->get($id); return $this->get($id);
}
return false; return false;
} }
@ -316,8 +332,9 @@ class AgendaEvents extends DolibarrApi
{ {
$event = array(); $event = array();
foreach (AgendaEvents::$FIELDS as $field) { foreach (AgendaEvents::$FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$event[$field] = $data[$field]; $event[$field] = $data[$field];
} }
return $event; return $event;

View File

@ -106,15 +106,16 @@ class CActionComm
{ {
$sql = "SELECT id, code, type, libelle as label, color, active, picto"; $sql = "SELECT id, code, type, libelle as label, color, active, picto";
$sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm";
if (is_numeric($id)) $sql .= " WHERE id=".(int) $id; if (is_numeric($id)) {
else $sql .= " WHERE code='".$this->db->escape($id)."'"; $sql .= " WHERE id=".(int) $id;
} else {
$sql .= " WHERE code='".$this->db->escape($id)."'";
}
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->id; $this->id = $obj->id;
@ -165,62 +166,76 @@ class CActionComm
if ($active != '') { if ($active != '') {
$sql .= " AND active=".(int) $active; $sql .= " AND active=".(int) $active;
} }
if (!empty($excludetype)) $sql .= " AND type <> '".$this->db->escape($excludetype)."'"; if (!empty($excludetype)) {
if ($morefilter) $sql .= " AND ".$morefilter; $sql .= " AND type <> '".$this->db->escape($excludetype)."'";
}
if ($morefilter) {
$sql .= " AND ".$morefilter;
}
$sql .= " ORDER BY type, position, module"; $sql .= " ORDER BY type, position, module";
dol_syslog(get_class($this)."::liste_array", LOG_DEBUG); dol_syslog(get_class($this)."::liste_array", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$nump = $this->db->num_rows($resql); $nump = $this->db->num_rows($resql);
if ($nump) if ($nump) {
{
$idforallfornewmodule = 97; $idforallfornewmodule = 97;
$i = 0; $i = 0;
while ($i < $nump) while ($i < $nump) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$qualified = 1; $qualified = 1;
// $obj->type can be system, systemauto, module, moduleauto, xxx, xxxauto // $obj->type can be system, systemauto, module, moduleauto, xxx, xxxauto
if ($qualified && $onlyautoornot > 0 && preg_match('/^system/', $obj->type) && !preg_match('/^AC_OTH/', $obj->code)) $qualified = 0; // We discard detailed system events. We keep only the 2 generic lines (AC_OTH and AC_OTH_AUTO) if ($qualified && $onlyautoornot > 0 && preg_match('/^system/', $obj->type) && !preg_match('/^AC_OTH/', $obj->code)) {
$qualified = 0; // We discard detailed system events. We keep only the 2 generic lines (AC_OTH and AC_OTH_AUTO)
if ($qualified && $obj->module)
{
if ($obj->module == 'invoice' && !$conf->facture->enabled) $qualified = 0;
if ($obj->module == 'order' && !$conf->commande->enabled) $qualified = 0;
if ($obj->module == 'propal' && !$conf->propal->enabled) $qualified = 0;
if ($obj->module == 'invoice_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_invoice->enabled)) $qualified = 0;
if ($obj->module == 'order_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_order->enabled)) $qualified = 0;
if ($obj->module == 'shipping' && !$conf->expedition->enabled) $qualified = 0;
} }
if ($qualified) if ($qualified && $obj->module) {
{ if ($obj->module == 'invoice' && !$conf->facture->enabled) {
$qualified = 0;
}
if ($obj->module == 'order' && !$conf->commande->enabled) {
$qualified = 0;
}
if ($obj->module == 'propal' && !$conf->propal->enabled) {
$qualified = 0;
}
if ($obj->module == 'invoice_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_invoice->enabled)) {
$qualified = 0;
}
if ($obj->module == 'order_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_order->enabled)) {
$qualified = 0;
}
if ($obj->module == 'shipping' && !$conf->expedition->enabled) {
$qualified = 0;
}
}
if ($qualified) {
$keyfortrans = ''; $keyfortrans = '';
$transcode = ''; $transcode = '';
$code = $obj->code; $code = $obj->code;
$typecalendar = $obj->type; $typecalendar = $obj->type;
if ($onlyautoornot > 0 && $typecalendar == 'system') $code = 'AC_MANUAL'; if ($onlyautoornot > 0 && $typecalendar == 'system') {
elseif ($onlyautoornot > 0 && $typecalendar == 'systemauto') $code = 'AC_AUTO'; $code = 'AC_MANUAL';
elseif ($onlyautoornot > 0) $code = 'AC_'.strtoupper($obj->module); } elseif ($onlyautoornot > 0 && $typecalendar == 'systemauto') {
$code = 'AC_AUTO';
} elseif ($onlyautoornot > 0) {
$code = 'AC_'.strtoupper($obj->module);
}
if ($shortlabel) if ($shortlabel) {
{
$keyfortrans = "Action".$code.'Short'; $keyfortrans = "Action".$code.'Short';
$transcode = $langs->trans($keyfortrans); $transcode = $langs->trans($keyfortrans);
} }
if (empty($keyfortrans) || $keyfortrans == $transcode) if (empty($keyfortrans) || $keyfortrans == $transcode) {
{
$keyfortrans = "Action".$code; $keyfortrans = "Action".$code;
$transcode = $langs->trans($keyfortrans); $transcode = $langs->trans($keyfortrans);
} }
$label = (($transcode != $keyfortrans) ? $transcode : $langs->trans($obj->label)); $label = (($transcode != $keyfortrans) ? $transcode : $langs->trans($obj->label));
if ($onlyautoornot == -1 && !empty($conf->global->AGENDA_USE_EVENT_TYPE)) if ($onlyautoornot == -1 && !empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
{
if ($typecalendar == 'system') { if ($typecalendar == 'system') {
$label = '&nbsp;&nbsp; '.$label; $label = '&nbsp;&nbsp; '.$label;
$repid[-99] = $langs->trans("ActionAC_MANUAL"); $repid[-99] = $langs->trans("ActionAC_MANUAL");
@ -252,9 +267,13 @@ class CActionComm
} }
} }
if ($idorcode == 'id') $this->liste_array = $repid; if ($idorcode == 'id') {
elseif ($idorcode == 'code') $this->liste_array = $repcode; $this->liste_array = $repid;
else $this->liste_array = $repall; } elseif ($idorcode == 'code') {
$this->liste_array = $repcode;
} else {
$this->liste_array = $repall;
}
return $this->liste_array; return $this->liste_array;
} else { } else {
@ -276,6 +295,8 @@ class CActionComm
// Check if translation available // Check if translation available
$transcode = $langs->trans("Action".$this->code); $transcode = $langs->trans("Action".$this->code);
if ($transcode != "Action".$this->code) return $transcode; if ($transcode != "Action".$this->code) {
return $transcode;
}
} }
} }

View File

@ -62,8 +62,7 @@ class ICal
$file_text = ''; $file_text = '';
$tmparray = file($file); $tmparray = file($file);
if (is_array($tmparray)) if (is_array($tmparray)) {
{
$file_text = join("", $tmparray); //load file $file_text = join("", $tmparray); //load file
$file_text = preg_replace("/[\r\n]{1,} /", "", $file_text); $file_text = preg_replace("/[\r\n]{1,} /", "", $file_text);
} }
@ -112,21 +111,20 @@ class ICal
$this->file_text = preg_split("[\n]", $this->file_text); $this->file_text = preg_split("[\n]", $this->file_text);
// is this text vcalendar standard text ? on line 1 is BEGIN:VCALENDAR // is this text vcalendar standard text ? on line 1 is BEGIN:VCALENDAR
if (!stristr($this->file_text[0], 'BEGIN:VCALENDAR')) return 'error not VCALENDAR'; if (!stristr($this->file_text[0], 'BEGIN:VCALENDAR')) {
return 'error not VCALENDAR';
}
$insidealarm = 0; $insidealarm = 0;
$tmpkey = ''; $tmpvalue = ''; $type = ''; $tmpkey = ''; $tmpvalue = ''; $type = '';
foreach ($this->file_text as $text) foreach ($this->file_text as $text) {
{
$text = trim($text); // trim one line $text = trim($text); // trim one line
if (!empty($text)) if (!empty($text)) {
{
// get Key and Value VCALENDAR:Begin -> Key = VCALENDAR, Value = begin // get Key and Value VCALENDAR:Begin -> Key = VCALENDAR, Value = begin
list($key, $value) = $this->retun_key_value($text); list($key, $value) = $this->retun_key_value($text);
//var_dump($text.' -> '.$key.' - '.$value); //var_dump($text.' -> '.$key.' - '.$value);
switch ($text) // search special string switch ($text) { // search special string
{
case "BEGIN:VTODO": case "BEGIN:VTODO":
$this->todo_count = $this->todo_count + 1; // new to do begin $this->todo_count = $this->todo_count + 1; // new to do begin
$type = "VTODO"; $type = "VTODO";
@ -152,7 +150,6 @@ class ICal
case "END:VTODO": // end special text - goto VCALENDAR key case "END:VTODO": // end special text - goto VCALENDAR key
case "END:VEVENT": case "END:VEVENT":
case "END:VFREEBUSY": case "END:VFREEBUSY":
case "END:VCALENDAR": case "END:VCALENDAR":
case "END:DAYLIGHT": case "END:DAYLIGHT":
case "END:VTIMEZONE": case "END:VTIMEZONE":
@ -169,27 +166,25 @@ class ICal
break; break;
default: // no special string (SUMMARY, DESCRIPTION, ...) default: // no special string (SUMMARY, DESCRIPTION, ...)
if ($tmpvalue) if ($tmpvalue) {
{
$tmpvalue .= $text; $tmpvalue .= $text;
if (!preg_match('/=$/', $text)) // No more lines if (!preg_match('/=$/', $text)) { // No more lines
{
$key = $tmpkey; $key = $tmpkey;
$value = quotedPrintDecode(preg_replace('/^ENCODING=QUOTED-PRINTABLE:/i', '', $tmpvalue)); $value = quotedPrintDecode(preg_replace('/^ENCODING=QUOTED-PRINTABLE:/i', '', $tmpvalue));
$tmpkey = ''; $tmpkey = '';
$tmpvalue = ''; $tmpvalue = '';
} }
} elseif (preg_match('/^ENCODING=QUOTED-PRINTABLE:/i', $value)) } elseif (preg_match('/^ENCODING=QUOTED-PRINTABLE:/i', $value)) {
{ if (preg_match('/=$/', $value)) {
if (preg_match('/=$/', $value))
{
$tmpkey = $key; $tmpkey = $key;
$tmpvalue = $tmpvalue.preg_replace('/=$/', "", $value); // We must wait to have next line to have complete message $tmpvalue = $tmpvalue.preg_replace('/=$/', "", $value); // We must wait to have next line to have complete message
} else { } else {
$value = quotedPrintDecode(preg_replace('/^ENCODING=QUOTED-PRINTABLE:/i', '', $tmpvalue.$value)); $value = quotedPrintDecode(preg_replace('/^ENCODING=QUOTED-PRINTABLE:/i', '', $tmpvalue.$value));
} }
} //$value=quotedPrintDecode($tmpvalue.$value); } //$value=quotedPrintDecode($tmpvalue.$value);
if (!$insidealarm && !$tmpkey) $this->add_to_array($type, $key, $value); // add to array if (!$insidealarm && !$tmpkey) {
$this->add_to_array($type, $key, $value); // add to array
}
break; break;
} }
} }
@ -214,32 +209,35 @@ class ICal
//print 'type='.$type.' key='.$key.' value='.$value.'<br>'."\n"; //print 'type='.$type.' key='.$key.' value='.$value.'<br>'."\n";
if (empty($key)) if (empty($key)) {
{
$key = $this->last_key; $key = $this->last_key;
switch ($type) switch ($type) {
{ case 'VEVENT':
case 'VEVENT': $value = $this->cal[$type][$this->event_count][$key].$value; break; $value = $this->cal[$type][$this->event_count][$key].$value;
case 'VFREEBUSY': $value = $this->cal[$type][$this->freebusy_count][$key].$value; break; break;
case 'VTODO': $value = $this->cal[$type][$this->todo_count][$key].$value; break; case 'VFREEBUSY':
$value = $this->cal[$type][$this->freebusy_count][$key].$value;
break;
case 'VTODO':
$value = $this->cal[$type][$this->todo_count][$key].$value;
break;
} }
} }
if (($key == "DTSTAMP") || ($key == "LAST-MODIFIED") || ($key == "CREATED")) $value = $this->ical_date_to_unix($value); if (($key == "DTSTAMP") || ($key == "LAST-MODIFIED") || ($key == "CREATED")) {
$value = $this->ical_date_to_unix($value);
}
//if ($key == "RRULE" ) $value = $this->ical_rrule($value); //if ($key == "RRULE" ) $value = $this->ical_rrule($value);
if (stristr($key, "DTSTART") || stristr($key, "DTEND") || stristr($key, "DTSTART;VALUE=DATE") || stristr($key, "DTEND;VALUE=DATE")) if (stristr($key, "DTSTART") || stristr($key, "DTEND") || stristr($key, "DTSTART;VALUE=DATE") || stristr($key, "DTEND;VALUE=DATE")) {
{ if (stristr($key, "DTSTART;VALUE=DATE") || stristr($key, "DTEND;VALUE=DATE")) {
if (stristr($key, "DTSTART;VALUE=DATE") || stristr($key, "DTEND;VALUE=DATE"))
{
list($key, $value) = array($key, $value); list($key, $value) = array($key, $value);
} else { } else {
list($key, $value) = $this->ical_dt_date($key, $value); list($key, $value) = $this->ical_dt_date($key, $value);
} }
} }
switch ($type) switch ($type) {
{
case "VTODO": case "VTODO":
$this->cal[$type][$this->todo_count][$key] = $value; $this->cal[$type][$this->todo_count][$key] = $value;
break; break;
@ -296,8 +294,7 @@ class ICal
// phpcs:enable // phpcs:enable
$result = array(); $result = array();
$rrule = explode(';', $value); $rrule = explode(';', $value);
foreach ($rrule as $line) foreach ($rrule as $line) {
{
$rcontent = explode('=', $line); $rcontent = explode('=', $line);
$result[$rcontent[0]] = $rcontent[1]; $result[$rcontent[0]] = $rcontent[1];
} }
@ -319,8 +316,9 @@ class ICal
$ntime = 0; $ntime = 0;
// TIME LIMITED EVENT // TIME LIMITED EVENT
if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})/', $ical_date, $date)) if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})/', $ical_date, $date)) {
$ntime = dol_mktime($date[4], $date[5], $date[6], $date[2], $date[3], $date[1], true); $ntime = dol_mktime($date[4], $date[5], $date[6], $date[2], $date[3], $date[1], true);
}
//if (empty($date[4])) print 'Error bad date: '.$ical_date.' - date1='.$date[1]; //if (empty($date[4])) print 'Error bad date: '.$ical_date.' - date1='.$date[1];
//print dol_print_date($ntime,'dayhour');exit; //print dol_print_date($ntime,'dayhour');exit;
@ -344,8 +342,7 @@ class ICal
// Analyse TZID // Analyse TZID
$temp = explode(";", $key); $temp = explode(";", $key);
if (empty($temp[1])) // not TZID if (empty($temp[1])) { // not TZID
{
$value = str_replace('T', '', $value); $value = str_replace('T', '', $value);
return array($key, $value); return array($key, $value);
} }
@ -368,8 +365,7 @@ class ICal
{ {
// phpcs:enable // phpcs:enable
$temp = $this->get_event_list(); $temp = $this->get_event_list();
if (!empty($temp)) if (!empty($temp)) {
{
usort($temp, array(&$this, "ical_dtstart_compare")); usort($temp, array(&$this, "ical_dtstart_compare"));
return $temp; return $temp;
} else { } else {

View File

@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if (!empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('companies', 'commercial', 'other', 'bills')); $langs->loadLangs(array('companies', 'commercial', 'other', 'bills'));
@ -45,9 +47,10 @@ $confirm = GETPOST('confirm', 'alpha');
// Security check // Security check
$socid = GETPOST('socid', 'int'); $socid = GETPOST('socid', 'int');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
if ($user->socid > 0) $socid = $user->socid;
{ }
if ($user->socid > 0) {
unset($_GET["action"]); unset($_GET["action"]);
$action = ''; $action = '';
} }
@ -55,8 +58,7 @@ $result = restrictedArea($user, 'agenda', $id, 'actioncomm&societe', 'myactions|
$object = new ActionComm($db); $object = new ActionComm($db);
if ($id > 0) if ($id > 0) {
{
$ret = $object->fetch($id); $ret = $object->fetch($id);
$object->fetch_thirdparty(); $object->fetch_thirdparty();
} }
@ -66,12 +68,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "name";
}
$upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
$modulepart = 'actions'; $modulepart = 'actions';
@ -93,22 +101,24 @@ $help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda';
llxHeader('', $langs->trans("Agenda"), $help_url); llxHeader('', $langs->trans("Agenda"), $help_url);
if ($object->id > 0) if ($object->id > 0) {
{
$result1 = $object->fetch($id); $result1 = $object->fetch($id);
$result2 = $object->fetch_thirdparty(); $result2 = $object->fetch_thirdparty();
$result3 = $object->fetch_contact(); $result3 = $object->fetch_contact();
$result4 = $object->fetch_userassigned(); $result4 = $object->fetch_userassigned();
$result5 = $object->fetch_optionals(); $result5 = $object->fetch_optionals();
if ($result1 < 0 || $result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) if ($result1 < 0 || $result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) {
{
dol_print_error($db, $object->error); dol_print_error($db, $object->error);
exit; exit;
} }
if ($object->authorid > 0) { $tmpuser = new User($db); $res = $tmpuser->fetch($object->authorid); $object->author = $tmpuser; } if ($object->authorid > 0) {
if ($object->usermodid > 0) { $tmpuser = new User($db); $res = $tmpuser->fetch($object->usermodid); $object->usermod = $tmpuser; } $tmpuser = new User($db); $res = $tmpuser->fetch($object->authorid); $object->author = $tmpuser;
}
if ($object->usermodid > 0) {
$tmpuser = new User($db); $res = $tmpuser->fetch($object->usermodid); $object->usermod = $tmpuser;
}
$author = new User($db); $author = new User($db);
$author->fetch($object->author->id); $author->fetch($object->author->id);
@ -142,8 +152,7 @@ if ($object->id > 0)
// Thirdparty // Thirdparty
//$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); //$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
// Project // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
//$morehtmlref.='<br>'.$langs->trans('Project') . ' '; //$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
$morehtmlref .= $langs->trans('Project').': '; $morehtmlref .= $langs->trans('Project').': ';
@ -153,7 +162,9 @@ if ($object->id > 0)
$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">'; $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
$morehtmlref .= $proj->ref; $morehtmlref .= $proj->ref;
$morehtmlref .= '</a>'; $morehtmlref .= '</a>';
if ($proj->title) $morehtmlref .= ' - '.$proj->title; if ($proj->title) {
$morehtmlref .= ' - '.$proj->title;
}
} else { } else {
$morehtmlref .= ''; $morehtmlref .= '';
} }
@ -170,8 +181,7 @@ if ($object->id > 0)
print '<table class="border tableforfield centpercent">'; print '<table class="border tableforfield centpercent">';
// Type // Type
if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
{
print '<tr><td class="titlefield">'.$langs->trans("Type").'</td><td colspan="3">'.$object->type.'</td></tr>'; print '<tr><td class="titlefield">'.$langs->trans("Type").'</td><td colspan="3">'.$object->type.'</td></tr>';
} }
@ -180,44 +190,53 @@ if ($object->id > 0)
// Date start // Date start
print '<tr><td>'.$langs->trans("DateActionStart").'</td><td colspan="3">'; print '<tr><td>'.$langs->trans("DateActionStart").'</td><td colspan="3">';
if (!$object->fulldayevent) print dol_print_date($object->datep, 'dayhour'); if (!$object->fulldayevent) {
else print dol_print_date($object->datep, 'day'); print dol_print_date($object->datep, 'dayhour');
if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); } else {
print dol_print_date($object->datep, 'day');
}
if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) {
print img_warning($langs->trans("Late"));
}
print '</td>'; print '</td>';
print '</tr>'; print '</tr>';
// Date end // Date end
print '<tr><td>'.$langs->trans("DateActionEnd").'</td><td colspan="3">'; print '<tr><td>'.$langs->trans("DateActionEnd").'</td><td colspan="3">';
if (!$object->fulldayevent) print dol_print_date($object->datef, 'dayhour'); if (!$object->fulldayevent) {
else print dol_print_date($object->datef, 'day'); print dol_print_date($object->datef, 'dayhour');
if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now - $delay_warning)) print img_warning($langs->trans("Late")); } else {
print dol_print_date($object->datef, 'day');
}
if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now - $delay_warning)) {
print img_warning($langs->trans("Late"));
}
print '</td></tr>'; print '</td></tr>';
// Location // Location
if (empty($conf->global->AGENDA_DISABLE_LOCATION)) if (empty($conf->global->AGENDA_DISABLE_LOCATION)) {
{
print '<tr><td>'.$langs->trans("Location").'</td><td colspan="3">'.$object->location.'</td></tr>'; print '<tr><td>'.$langs->trans("Location").'</td><td colspan="3">'.$object->location.'</td></tr>';
} }
// Assigned to // Assigned to
print '<tr><td class="nowrap">'.$langs->trans("ActionAffectedTo").'</td><td colspan="3">'; print '<tr><td class="nowrap">'.$langs->trans("ActionAffectedTo").'</td><td colspan="3">';
$listofuserid = array(); $listofuserid = array();
if (empty($donotclearsession)) if (empty($donotclearsession)) {
{ if ($object->userownerid > 0) {
if ($object->userownerid > 0) $listofuserid[$object->userownerid] = array('id'=>$object->userownerid, 'transparency'=>$object->transparency); // Owner first $listofuserid[$object->userownerid] = array('id'=>$object->userownerid, 'transparency'=>$object->transparency); // Owner first
if (!empty($object->userassigned)) // Now concat assigned users }
{ if (!empty($object->userassigned)) { // Now concat assigned users
// Restore array with key with same value than param 'id' // Restore array with key with same value than param 'id'
$tmplist1 = $object->userassigned; $tmplist1 = $object->userassigned;
foreach ($tmplist1 as $key => $val) foreach ($tmplist1 as $key => $val) {
{ if ($val['id'] && $val['id'] != $object->userownerid) {
if ($val['id'] && $val['id'] != $object->userownerid) $listofuserid[$val['id']] = $val; $listofuserid[$val['id']] = $val;
}
} }
} }
$_SESSION['assignedtouser'] = json_encode($listofuserid); $_SESSION['assignedtouser'] = json_encode($listofuserid);
} else { } else {
if (!empty($_SESSION['assignedtouser'])) if (!empty($_SESSION['assignedtouser'])) {
{
$listofuserid = json_decode($_SESSION['assignedtouser'], true); $listofuserid = json_decode($_SESSION['assignedtouser'], true);
} }
} }
@ -241,8 +260,7 @@ if ($object->id > 0)
// Build file list // Build file list
$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
$totalsize = 0; $totalsize = 0;
foreach ($filearray as $key => $file) foreach ($filearray as $key => $file) {
{
$totalsize += $file['size']; $totalsize += $file['size'];
} }

File diff suppressed because it is too large Load Diff

View File

@ -39,8 +39,7 @@ $langs->load("commercial");
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
// Security check // Security check
if ($user->socid > 0) if ($user->socid > 0) {
{
$action = ''; $action = '';
$socid = $user->socid; $socid = $user->socid;
} }
@ -84,8 +83,7 @@ $morehtmlref = '<div class="refidno">';
// Thirdparty // Thirdparty
//$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); //$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
// Project // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
//$morehtmlref.='<br>'.$langs->trans('Project') . ' '; //$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
$morehtmlref .= $langs->trans('Project').': '; $morehtmlref .= $langs->trans('Project').': ';
@ -95,7 +93,9 @@ if (!empty($conf->projet->enabled))
$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">'; $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
$morehtmlref .= $proj->ref; $morehtmlref .= $proj->ref;
$morehtmlref .= '</a>'; $morehtmlref .= '</a>';
if ($proj->title) $morehtmlref .= ' - '.$proj->title; if ($proj->title) {
$morehtmlref .= ' - '.$proj->title;
}
} else { } else {
$morehtmlref .= ''; $morehtmlref .= '';
} }

View File

@ -27,7 +27,9 @@
* \brief Page to list actions * \brief Page to list actions
*/ */
if (!defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); if (!defined("NOREDIRECTBYMAINTOLOGIN")) {
define('NOREDIRECTBYMAINTOLOGIN', 1);
}
require '../../main.inc.php'; require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
@ -55,14 +57,17 @@ $toselect = GETPOST('toselect', 'array');
$confirm = GETPOST('confirm', 'alpha'); $confirm = GETPOST('confirm', 'alpha');
// Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index)
if (GETPOST('search_actioncode', 'array')) if (GETPOST('search_actioncode', 'array')) {
{
$actioncode = GETPOST('search_actioncode', 'array', 3); $actioncode = GETPOST('search_actioncode', 'array', 3);
if (!count($actioncode)) $actioncode = '0'; if (!count($actioncode)) {
$actioncode = '0';
}
} else { } else {
$actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE));
} }
if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); if ($actioncode == '' && empty($actioncodearray)) {
$actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE);
}
$search_id = GETPOST('search_id', 'alpha'); $search_id = GETPOST('search_id', 'alpha');
$search_title = GETPOST('search_title', 'alpha'); $search_title = GETPOST('search_title', 'alpha');
$search_note = GETPOST('search_note', 'alpha'); $search_note = GETPOST('search_note', 'alpha');
@ -70,8 +75,12 @@ $search_note = GETPOST('search_note', 'alpha');
$dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int'), 'tzuserrel'); $dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int'), 'tzuserrel');
$datestart = dol_mktime(0, 0, 0, GETPOST('datestartmonth', 'int'), GETPOST('datestartday', 'int'), GETPOST('datestartyear', 'int'), 'tzuserrel'); $datestart = dol_mktime(0, 0, 0, GETPOST('datestartmonth', 'int'), GETPOST('datestartday', 'int'), GETPOST('datestartyear', 'int'), 'tzuserrel');
$dateend = dol_mktime(0, 0, 0, GETPOST('dateendmonth', 'int'), GETPOST('dateendday', 'int'), GETPOST('dateendyear', 'int'), 'tzuserrel'); $dateend = dol_mktime(0, 0, 0, GETPOST('dateendmonth', 'int'), GETPOST('dateendday', 'int'), GETPOST('dateendyear', 'int'), 'tzuserrel');
if ($search_status == '' && !GETPOSTISSET('search_status')) $search_status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); if ($search_status == '' && !GETPOSTISSET('search_status')) {
if (empty($action) && !GETPOSTISSET('action')) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); $search_status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS);
}
if (empty($action) && !GETPOSTISSET('action')) {
$action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW);
}
$filter = GETPOST("search_filter", 'alpha', 3) ?GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); $filter = GETPOST("search_filter", 'alpha', 3) ?GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3);
$filtert = GETPOST("search_filtert", "int", 3) ?GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); $filtert = GETPOST("search_filtert", "int", 3) ?GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3);
@ -89,8 +98,7 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// If not choice done on calendar owner, we filter on user. // If not choice done on calendar owner, we filter on user.
if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) {
{
$filtert = $user->id; $filtert = $user->id;
} }
@ -98,30 +106,41 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if ($page == -1 || $page == null) { $page = 0; } if ($page == -1 || $page == null) {
$offset = $limit * $page; $page = 0;
if (!$sortorder)
{
$sortorder = "DESC,DESC";
if ($search_status == 'todo') $sortorder = "DESC,DESC";
} }
if (!$sortfield) $offset = $limit * $page;
{ if (!$sortorder) {
$sortorder = "DESC,DESC";
if ($search_status == 'todo') {
$sortorder = "DESC,DESC";
}
}
if (!$sortfield) {
$sortfield = "a.datep,a.id"; $sortfield = "a.datep,a.id";
if ($search_status == 'todo') $sortfield = "a.datep,a.id"; if ($search_status == 'todo') {
$sortfield = "a.datep,a.id";
}
} }
// Security check // Security check
$socid = GETPOST("search_socid", 'int') ?GETPOST("search_socid", 'int') : GETPOST("socid", 'int'); $socid = GETPOST("search_socid", 'int') ?GETPOST("search_socid", 'int') : GETPOST("socid", 'int');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'agenda', 0, '', 'myactions'); $result = restrictedArea($user, 'agenda', 0, '', 'myactions');
if ($socid < 0) $socid = ''; if ($socid < 0) {
$socid = '';
}
$canedit = 1; $canedit = 1;
if (!$user->rights->agenda->myactions->read) accessforbidden(); if (!$user->rights->agenda->myactions->read) {
if (!$user->rights->agenda->allactions->read) $canedit = 0; accessforbidden();
if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no permission to see all, we show only affected to me }
{ if (!$user->rights->agenda->allactions->read) {
$canedit = 0;
}
if (!$user->rights->agenda->allactions->read || $filter == 'mine') { // If no permission to see all, we show only affected to me
$filtert = $user->id; $filtert = $user->id;
} }
@ -152,18 +171,14 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) if (GETPOST('cancel', 'alpha')) {
{
$action = 'list'; $massaction = ''; $action = 'list'; $massaction = '';
} }
if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) {
{
$param = ''; $param = '';
if (is_array($_POST)) if (is_array($_POST)) {
{ foreach ($_POST as $key => $val) {
foreach ($_POST as $key => $val)
{
$param .= '&'.$key.'='.urlencode($val); $param .= '&'.$key.'='.urlencode($val);
} }
} }
@ -174,13 +189,14 @@ if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday"))
$parameters = array('id'=>$socid); $parameters = array('id'=>$socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
//$actioncode=''; //$actioncode='';
$search_id = ''; $search_id = '';
$search_title = ''; $search_title = '';
@ -192,12 +208,10 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
$search_array_options = array(); $search_array_options = array();
} }
if (empty($reshook) && !empty($massaction)) if (empty($reshook) && !empty($massaction)) {
{
unset($percent); unset($percent);
switch ($massaction) switch ($massaction) {
{
case 'set_all_events_to_todo': case 'set_all_events_to_todo':
$percent = ActionComm::EVENT_TODO; $percent = ActionComm::EVENT_TODO;
break; break;
@ -211,13 +225,10 @@ if (empty($reshook) && !empty($massaction))
break; break;
} }
if (isset($percent)) if (isset($percent)) {
{ foreach ($toselect as $toselectid) {
foreach ($toselect as $toselectid)
{
$result = $object->updatePercent($toselectid, $percent); $result = $object->updatePercent($toselectid, $percent);
if ($result < 0) if ($result < 0) {
{
dol_print_error($db); dol_print_error($db);
break; break;
} }
@ -226,8 +237,7 @@ if (empty($reshook) && !empty($massaction))
} }
// As mass deletion happens with a confirm step, $massaction is not use for the final step (deletion). // As mass deletion happens with a confirm step, $massaction is not use for the final step (deletion).
if (empty($reshook)) if (empty($reshook)) {
{
$objectclass = 'ActionComm'; $objectclass = 'ActionComm';
$objectlabel = 'Events'; $objectlabel = 'Events';
$uploaddir = true; $uploaddir = true;
@ -258,32 +268,78 @@ llxHeader('', $langs->trans("Agenda"), $help_url);
$listofextcals = array(); $listofextcals = array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
if ($actioncode != '') { if ($actioncode != '') {
if (is_array($actioncode)) { if (is_array($actioncode)) {
foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action); foreach ($actioncode as $str_action) {
} else $param .= "&search_actioncode=".urlencode($actioncode); $param .= "&search_actioncode[]=".urlencode($str_action);
}
} else {
$param .= "&search_actioncode=".urlencode($actioncode);
}
}
if ($resourceid > 0) {
$param .= "&search_resourceid=".urlencode($resourceid);
}
if ($search_status != '' && $search_status > -1) {
$param .= "&search_status=".urlencode($search_status);
}
if ($filter) {
$param .= "&search_filter=".urlencode($filter);
}
if ($filtert) {
$param .= "&search_filtert=".urlencode($filtert);
}
if ($usergroup > 0) {
$param .= "&search_usergroup=".urlencode($usergroup);
}
if ($socid > 0) {
$param .= "&search_socid=".urlencode($socid);
}
if ($showbirthday) {
$param .= "&search_showbirthday=1";
}
if ($pid) {
$param .= "&search_projectid=".urlencode($pid);
}
if ($type) {
$param .= "&search_type=".urlencode($type);
}
if ($search_id != '') {
$param .= '&search_title='.urlencode($search_id);
}
if ($search_title != '') {
$param .= '&search_title='.urlencode($search_title);
}
if ($search_note != '') {
$param .= '&search_note='.$search_note;
}
if (GETPOST('datestartday', 'int')) {
$param .= '&datestartday='.GETPOST('datestartday', 'int');
}
if (GETPOST('datestartmonth', 'int')) {
$param .= '&datestartmonth='.GETPOST('datestartmonth', 'int');
}
if (GETPOST('datestartyear', 'int')) {
$param .= '&datestartyear='.GETPOST('datestartyear', 'int');
}
if (GETPOST('dateendday', 'int')) {
$param .= '&dateendday='.GETPOST('dateendday', 'int');
}
if (GETPOST('dateendmonth', 'int')) {
$param .= '&dateendmonth='.GETPOST('dateendmonth', 'int');
}
if (GETPOST('dateendyear', 'int')) {
$param .= '&dateendyear='.GETPOST('dateendyear', 'int');
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
} }
if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid);
if ($search_status != '' && $search_status > -1) $param .= "&search_status=".urlencode($search_status);
if ($filter) $param .= "&search_filter=".urlencode($filter);
if ($filtert) $param .= "&search_filtert=".urlencode($filtert);
if ($usergroup > 0) $param .= "&search_usergroup=".urlencode($usergroup);
if ($socid > 0) $param .= "&search_socid=".urlencode($socid);
if ($showbirthday) $param .= "&search_showbirthday=1";
if ($pid) $param .= "&search_projectid=".urlencode($pid);
if ($type) $param .= "&search_type=".urlencode($type);
if ($search_id != '') $param .= '&search_title='.urlencode($search_id);
if ($search_title != '') $param .= '&search_title='.urlencode($search_title);
if ($search_note != '') $param .= '&search_note='.$search_note;
if (GETPOST('datestartday', 'int')) $param .= '&datestartday='.GETPOST('datestartday', 'int');
if (GETPOST('datestartmonth', 'int')) $param .= '&datestartmonth='.GETPOST('datestartmonth', 'int');
if (GETPOST('datestartyear', 'int')) $param .= '&datestartyear='.GETPOST('datestartyear', 'int');
if (GETPOST('dateendday', 'int')) $param .= '&dateendday='.GETPOST('dateendday', 'int');
if (GETPOST('dateendmonth', 'int')) $param .= '&dateendmonth='.GETPOST('dateendmonth', 'int');
if (GETPOST('dateendyear', 'int')) $param .= '&dateendyear='.GETPOST('dateendyear', 'int');
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -295,16 +351,21 @@ $arrayofmassactions = array(
'set_all_events_to_in_progress' => $langs->trans("SetAllEventsToInProgress"), 'set_all_events_to_in_progress' => $langs->trans("SetAllEventsToInProgress"),
'set_all_events_to_finished' => $langs->trans("SetAllEventsToFinished"), 'set_all_events_to_finished' => $langs->trans("SetAllEventsToFinished"),
); );
if ($user->rights->agenda->allactions->delete) if ($user->rights->agenda->allactions->delete) {
{
$arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
} }
if ($user->rights->agenda->myactions->create) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); if ($user->rights->agenda->myactions->create) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
$sql = "SELECT"; $sql = "SELECT";
if ($usergroup > 0) $sql .= " DISTINCT"; if ($usergroup > 0) {
$sql .= " DISTINCT";
}
$sql .= " s.nom as societe, s.rowid as socid, s.client, s.email as socemail,"; $sql .= " s.nom as societe, s.rowid as socid, s.client, s.email as socemail,";
$sql .= " a.id, a.code, a.label, a.note, a.datep as dp, a.datep2 as dp2, a.fulldayevent, a.location,"; $sql .= " a.id, a.code, a.label, a.note, a.datep as dp, a.datep2 as dp2, a.fulldayevent, a.location,";
$sql .= ' a.fk_user_author,a.fk_user_action,'; $sql .= ' a.fk_user_author,a.fk_user_action,';
@ -315,7 +376,9 @@ $sql .= " sp.lastname, sp.firstname, sp.email, sp.phone, sp.address, sp.phone as
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
}
} }
// Add fields from hooks // Add fields from hooks
@ -325,34 +388,47 @@ $sql .= $hookmanager->resPrint;
$sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_extrafields as ef ON (a.id = ef.fk_object) "; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_extrafields as ef ON (a.id = ef.fk_object) ";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
$sql .= " ,".MAIN_DB_PREFIX."c_actioncomm as c"; $sql .= " ,".MAIN_DB_PREFIX."c_actioncomm as c";
// We must filter on resource table // We must filter on resource table
if ($resourceid > 0) $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; if ($resourceid > 0) {
$sql .= ", ".MAIN_DB_PREFIX."element_resources as r";
}
// We must filter on assignement table // We must filter on assignement table
if ($filtert > 0 || $usergroup > 0) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; if ($filtert > 0 || $usergroup > 0) {
if ($usergroup > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
}
if ($usergroup > 0) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element";
}
$sql .= " WHERE c.id = a.fk_action"; $sql .= " WHERE c.id = a.fk_action";
$sql .= ' AND a.entity IN ('.getEntity('agenda').')'; $sql .= ' AND a.entity IN ('.getEntity('agenda').')';
// Condition on actioncode // Condition on actioncode
if (!empty($actioncode)) if (!empty($actioncode)) {
{ if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) if ($actioncode == 'AC_NON_AUTO') {
{ $sql .= " AND c.type != 'systemauto'";
if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; } elseif ($actioncode == 'AC_ALL_AUTO') {
elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; $sql .= " AND c.type = 'systemauto'";
else { } else {
if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'"; if ($actioncode == 'AC_OTH') {
if ($actioncode == 'AC_OTH_AUTO') $sql .= " AND c.type = 'systemauto'"; $sql .= " AND c.type != 'systemauto'";
}
if ($actioncode == 'AC_OTH_AUTO') {
$sql .= " AND c.type = 'systemauto'";
}
} }
} else { } else {
if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; if ($actioncode == 'AC_NON_AUTO') {
elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; $sql .= " AND c.type != 'systemauto'";
else { } elseif ($actioncode == 'AC_ALL_AUTO') {
if (is_array($actioncode)) $sql .= " AND c.type = 'systemauto'";
{ } else {
if (is_array($actioncode)) {
$sql .= " AND c.code IN ('".implode("','", $actioncode)."')"; $sql .= " AND c.code IN ('".implode("','", $actioncode)."')";
} else { } else {
$sql .= " AND c.code IN ('".implode("','", explode(',', $actioncode))."')"; $sql .= " AND c.code IN ('".implode("','", explode(',', $actioncode))."')";
@ -360,35 +436,74 @@ if (!empty($actioncode))
} }
} }
} }
if ($resourceid > 0) $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); if ($resourceid > 0) {
if ($pid) $sql .= " AND a.fk_project=".$db->escape($pid); $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid);
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; }
if ($socid > 0) $sql .= " AND s.rowid = ".$socid; if ($pid) {
$sql .= " AND a.fk_project=".$db->escape($pid);
}
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")";
}
if ($socid > 0) {
$sql .= " AND s.rowid = ".$socid;
}
// We must filter on assignement table // We must filter on assignement table
if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; if ($filtert > 0 || $usergroup > 0) {
if ($type) $sql .= " AND c.id = ".(int) $type; $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
if ($search_status == '0') { $sql .= " AND a.percent = 0"; } }
if ($search_status == 'na') { $sql .= " AND a.percent = -1"; } // Not applicable if ($type) {
if ($search_status == '50') { $sql .= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started $sql .= " AND c.id = ".(int) $type;
if ($search_status == '100') { $sql .= " AND a.percent = 100"; } }
if ($search_status == 'done') { $sql .= " AND (a.percent = 100)"; } if ($search_status == '0') {
if ($search_status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } $sql .= " AND a.percent = 0";
if ($search_id) $sql .= natural_search("a.id", $search_id, 1); }
if ($search_title) $sql .= natural_search("a.label", $search_title); if ($search_status == 'na') {
if ($search_note) $sql .= natural_search('a.note', $search_note); $sql .= " AND a.percent = -1";
} // Not applicable
if ($search_status == '50') {
$sql .= " AND (a.percent > 0 AND a.percent < 100)";
} // Running already started
if ($search_status == '100') {
$sql .= " AND a.percent = 100";
}
if ($search_status == 'done') {
$sql .= " AND (a.percent = 100)";
}
if ($search_status == 'todo') {
$sql .= " AND (a.percent >= 0 AND a.percent < 100)";
}
if ($search_id) {
$sql .= natural_search("a.id", $search_id, 1);
}
if ($search_title) {
$sql .= natural_search("a.label", $search_title);
}
if ($search_note) {
$sql .= natural_search('a.note', $search_note);
}
// We must filter on assignement table // We must filter on assignement table
if ($filtert > 0 || $usergroup > 0) if ($filtert > 0 || $usergroup > 0) {
{
$sql .= " AND ("; $sql .= " AND (";
if ($filtert > 0) $sql .= "(ar.fk_element = ".$filtert." OR (ar.fk_element IS NULL AND a.fk_user_action=".$filtert."))"; // The OR is for backward compatibility if ($filtert > 0) {
if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; $sql .= "(ar.fk_element = ".$filtert." OR (ar.fk_element IS NULL AND a.fk_user_action=".$filtert."))"; // The OR is for backward compatibility
}
if ($usergroup > 0) {
$sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup;
}
$sql .= ")"; $sql .= ")";
} }
// The second or of next test is to take event with no end date (we suppose duration is 1 hour in such case) // The second or of next test is to take event with no end date (we suppose duration is 1 hour in such case)
if ($dateselect > 0) $sql .= " AND ((a.datep2 >= '".$db->idate($dateselect)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."') OR (a.datep2 IS NULL AND a.datep > '".$db->idate($dateselect - 3600)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."'))"; if ($dateselect > 0) {
if ($datestart > 0) $sql .= " AND a.datep BETWEEN '".$db->idate($datestart)."' AND '".$db->idate($datestart + 3600 * 24 - 1)."'"; $sql .= " AND ((a.datep2 >= '".$db->idate($dateselect)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."') OR (a.datep2 IS NULL AND a.datep > '".$db->idate($dateselect - 3600)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."'))";
if ($dateend > 0) $sql .= " AND a.datep2 BETWEEN '".$db->idate($dateend)."' AND '".$db->idate($dateend + 3600 * 24 - 1)."'"; }
if ($datestart > 0) {
$sql .= " AND a.datep BETWEEN '".$db->idate($datestart)."' AND '".$db->idate($datestart + 3600 * 24 - 1)."'";
}
if ($dateend > 0) {
$sql .= " AND a.datep2 BETWEEN '".$db->idate($dateend)."' AND '".$db->idate($dateend + 3600 * 24 - 1)."'";
}
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@ -401,12 +516,10 @@ $sql .= $hookmanager->resPrint;
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@ -417,8 +530,7 @@ $sql .= $db->plimit($limit + 1, $offset);
dol_syslog("comm/action/list.php", LOG_DEBUG); dol_syslog("comm/action/list.php", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$actionstatic = new ActionComm($db); $actionstatic = new ActionComm($db);
$societestatic = new Societe($db); $societestatic = new Societe($db);
@ -438,7 +550,9 @@ if ($resql)
print '<form method="POST" id="searchFormList" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'">'."\n"; print '<form method="POST" id="searchFormList" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'">'."\n";
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@ -446,8 +560,12 @@ if ($resql)
print '<input type="hidden" name="type" value="'.$type.'">'; print '<input type="hidden" name="type" value="'.$type.'">';
$nav = ''; $nav = '';
if ($filter) $nav .= '<input type="hidden" name="search_filter" value="'.$filter.'">'; if ($filter) {
if ($showbirthday) $nav .= '<input type="hidden" name="search_showbirthday" value="1">'; $nav .= '<input type="hidden" name="search_filter" value="'.$filter.'">';
}
if ($showbirthday) {
$nav .= '<input type="hidden" name="search_showbirthday" value="1">';
}
print $nav; print $nav;
//print dol_get_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); //print dol_get_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action');
@ -550,7 +668,9 @@ if ($resql)
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); if ($massactionbutton) {
$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
}
$i = 0; $i = 0;
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
@ -561,11 +681,21 @@ if ($resql)
print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
if (!empty($arrayfields['a.id']['checked'])) print '<td class="liste_titre"><input type="text" class="maxwidth50" name="search_id" value="'.$search_id.'"></td>'; if (!empty($arrayfields['a.id']['checked'])) {
if (!empty($arrayfields['owner']['checked'])) print '<td class="liste_titre"></td>'; print '<td class="liste_titre"><input type="text" class="maxwidth50" name="search_id" value="'.$search_id.'"></td>';
if (!empty($arrayfields['c.libelle']['checked'])) print '<td class="liste_titre"></td>'; }
if (!empty($arrayfields['a.label']['checked'])) print '<td class="liste_titre"><input type="text" class="maxwidth75" name="search_title" value="'.$search_title.'"></td>'; if (!empty($arrayfields['owner']['checked'])) {
if (!empty($arrayfields['a.note']['checked'])) print '<td class="liste_titre"><input type="text" class="maxwidth75" name="search_note" value="'.$search_note.'"></td>'; print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['c.libelle']['checked'])) {
print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['a.label']['checked'])) {
print '<td class="liste_titre"><input type="text" class="maxwidth75" name="search_title" value="'.$search_title.'"></td>';
}
if (!empty($arrayfields['a.note']['checked'])) {
print '<td class="liste_titre"><input type="text" class="maxwidth75" name="search_note" value="'.$search_note.'"></td>';
}
if (!empty($arrayfields['a.datep']['checked'])) { if (!empty($arrayfields['a.datep']['checked'])) {
print '<td class="liste_titre nowraponall" align="center">'; print '<td class="liste_titre nowraponall" align="center">';
print $form->selectDate($datestart, 'datestart', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel'); print $form->selectDate($datestart, 'datestart', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel');
@ -579,8 +709,12 @@ if ($resql)
if (!empty($arrayfields['s.nom']['checked'])) { if (!empty($arrayfields['s.nom']['checked'])) {
print '<td class="liste_titre"></td>'; print '<td class="liste_titre"></td>';
} }
if (!empty($arrayfields['a.fk_contact']['checked'])) print '<td class="liste_titre"></td>'; if (!empty($arrayfields['a.fk_contact']['checked'])) {
if (!empty($arrayfields['a.fk_element']['checked'])) print '<td class="liste_titre"></td>'; print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['a.fk_element']['checked'])) {
print '<td class="liste_titre"></td>';
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
@ -590,8 +724,12 @@ if ($resql)
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if (!empty($arrayfields['a.datec']['checked'])) print '<td class="liste_titre"></td>'; if (!empty($arrayfields['a.datec']['checked'])) {
if (!empty($arrayfields['a.tms']['checked'])) print '<td class="liste_titre"></td>'; print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['a.tms']['checked'])) {
print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['a.percent']['checked'])) { if (!empty($arrayfields['a.percent']['checked'])) {
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
$formactions->form_select_status_action('formaction', $search_status, 1, 'search_status', 1, 2, 'minwidth100imp maxwidth125'); $formactions->form_select_status_action('formaction', $search_status, 1, 'search_status', 1, 2, 'minwidth100imp maxwidth125');
@ -606,17 +744,37 @@ if ($resql)
print "</tr>\n"; print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['a.id']['checked'])) print_liste_field_titre($arrayfields['a.id']['label'], $_SERVER["PHP_SELF"], "a.id", $param, "", "", $sortfield, $sortorder); if (!empty($arrayfields['a.id']['checked'])) {
if (!empty($arrayfields['owner']['checked'])) print_liste_field_titre($arrayfields['owner']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['a.id']['label'], $_SERVER["PHP_SELF"], "a.id", $param, "", "", $sortfield, $sortorder);
if (!empty($arrayfields['c.libelle']['checked'])) print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], "c.libelle", $param, "", "", $sortfield, $sortorder); }
if (!empty($arrayfields['a.label']['checked'])) print_liste_field_titre($arrayfields['a.label']['label'], $_SERVER["PHP_SELF"], "a.label", $param, "", "", $sortfield, $sortorder); if (!empty($arrayfields['owner']['checked'])) {
if (!empty($arrayfields['a.note']['checked'])) print_liste_field_titre($arrayfields['a.note']['label'], $_SERVER["PHP_SELF"], "a.note", $param, "", "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['owner']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['c.libelle']['checked'])) {
print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], "c.libelle", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['a.label']['checked'])) {
print_liste_field_titre($arrayfields['a.label']['label'], $_SERVER["PHP_SELF"], "a.label", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['a.note']['checked'])) {
print_liste_field_titre($arrayfields['a.note']['label'], $_SERVER["PHP_SELF"], "a.note", $param, "", "", $sortfield, $sortorder);
}
//if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))
if (!empty($arrayfields['a.datep']['checked'])) print_liste_field_titre($arrayfields['a.datep']['label'], $_SERVER["PHP_SELF"], "a.datep,a.id", $param, '', 'align="center"', $sortfield, $sortorder); if (!empty($arrayfields['a.datep']['checked'])) {
if (!empty($arrayfields['a.datep2']['checked'])) print_liste_field_titre($arrayfields['a.datep2']['label'], $_SERVER["PHP_SELF"], "a.datep2", $param, '', 'align="center"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['a.datep']['label'], $_SERVER["PHP_SELF"], "a.datep,a.id", $param, '', 'align="center"', $sortfield, $sortorder);
if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $param, "", "", $sortfield, $sortorder); }
if (!empty($arrayfields['a.fk_contact']['checked'])) print_liste_field_titre($arrayfields['a.fk_contact']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); if (!empty($arrayfields['a.datep2']['checked'])) {
if (!empty($arrayfields['a.fk_element']['checked'])) print_liste_field_titre($arrayfields['a.fk_element']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['a.datep2']['label'], $_SERVER["PHP_SELF"], "a.datep2", $param, '', 'align="center"', $sortfield, $sortorder);
}
if (!empty($arrayfields['s.nom']['checked'])) {
print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['a.fk_contact']['checked'])) {
print_liste_field_titre($arrayfields['a.fk_contact']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['a.fk_element']['checked'])) {
print_liste_field_titre($arrayfields['a.fk_element']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder);
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
@ -626,10 +784,16 @@ if ($resql)
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if (!empty($arrayfields['a.datec']['checked'])) print_liste_field_titre($arrayfields['a.datec']['label'], $_SERVER["PHP_SELF"], "a.datec,a.id", $param, "", 'align="center"', $sortfield, $sortorder); if (!empty($arrayfields['a.datec']['checked'])) {
if (!empty($arrayfields['a.tms']['checked'])) print_liste_field_titre($arrayfields['a.tms']['label'], $_SERVER["PHP_SELF"], "a.tms,a.id", $param, "", 'align="center"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['a.datec']['label'], $_SERVER["PHP_SELF"], "a.datec,a.id", $param, "", 'align="center"', $sortfield, $sortorder);
}
if (!empty($arrayfields['a.tms']['checked'])) {
print_liste_field_titre($arrayfields['a.tms']['label'], $_SERVER["PHP_SELF"], "a.tms,a.id", $param, "", 'align="center"', $sortfield, $sortorder);
}
if (!empty($arrayfields['a.percent']['checked']))print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "a.percent", $param, "", 'align="center"', $sortfield, $sortorder); if (!empty($arrayfields['a.percent']['checked'])) {
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "a.percent", $param, "", 'align="center"', $sortfield, $sortorder);
}
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
print "</tr>\n"; print "</tr>\n";
@ -642,13 +806,11 @@ if ($resql)
$arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1); $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1);
$contactListCache = array(); $contactListCache = array();
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
// Discard auto action if option is on // Discard auto action if option is on
if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') {
{
$i++; $i++;
continue; continue;
} }
@ -676,29 +838,34 @@ if ($resql)
} }
// User owner // User owner
if (!empty($arrayfields['owner']['checked'])) if (!empty($arrayfields['owner']['checked'])) {
{
print '<td class="tdoverflowmax150">'; // With edge and chrome the td overflow is not supported correctly when content is not full text. print '<td class="tdoverflowmax150">'; // With edge and chrome the td overflow is not supported correctly when content is not full text.
if ($obj->fk_user_action > 0) if ($obj->fk_user_action > 0) {
{
$userstatic->fetch($obj->fk_user_action); $userstatic->fetch($obj->fk_user_action);
print $userstatic->getNomUrl(-1); print $userstatic->getNomUrl(-1);
} else print '&nbsp;'; } else {
print '&nbsp;';
}
print '</td>'; print '</td>';
} }
// Type // Type
if (!empty($arrayfields['c.libelle']['checked'])) if (!empty($arrayfields['c.libelle']['checked'])) {
{
print '<td class="nowraponall">'; print '<td class="nowraponall">';
print $actionstatic->getTypePicto(); print $actionstatic->getTypePicto();
$labeltype = $obj->type_code; $labeltype = $obj->type_code;
if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) {
$labeltype = 'AC_OTH';
}
if ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') { if ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') {
$labeltype = $langs->trans("Message"); $labeltype = $langs->trans("Message");
} else { } else {
if (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; if (!empty($arraylist[$labeltype])) {
if ($obj->type_code == 'AC_OTH_AUTO' && ($obj->type_code != $obj->code) && $labeltype && !empty($arraylist[$obj->code])) $labeltype .= ' - '.$arraylist[$obj->code]; // Use code in priority on type_code $labeltype = $arraylist[$labeltype];
}
if ($obj->type_code == 'AC_OTH_AUTO' && ($obj->type_code != $obj->code) && $labeltype && !empty($arraylist[$obj->code])) {
$labeltype .= ' - '.$arraylist[$obj->code]; // Use code in priority on type_code
}
} }
print dol_trunc($labeltype, 28); print dol_trunc($labeltype, 28);
print '</td>'; print '</td>';
@ -726,11 +893,21 @@ if ($resql)
print '<td class="center nowraponall">'; print '<td class="center nowraponall">';
print dol_print_date($db->jdate($obj->dp), $formatToUse, 'tzuser'); print dol_print_date($db->jdate($obj->dp), $formatToUse, 'tzuser');
$late = 0; $late = 0;
if ($obj->percent == 0 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; if ($obj->percent == 0 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) {
if ($obj->percent == 0 && !$obj->dp && $obj->dp2 && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; $late = 1;
if ($obj->percent > 0 && $obj->percent < 100 && $obj->dp2 && $db->jdate($obj->dp2) < ($now - $delay_warning)) $late = 1; }
if ($obj->percent > 0 && $obj->percent < 100 && !$obj->dp2 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; if ($obj->percent == 0 && !$obj->dp && $obj->dp2 && $db->jdate($obj->dp) < ($now - $delay_warning)) {
if ($late) print img_warning($langs->trans("Late")).' '; $late = 1;
}
if ($obj->percent > 0 && $obj->percent < 100 && $obj->dp2 && $db->jdate($obj->dp2) < ($now - $delay_warning)) {
$late = 1;
}
if ($obj->percent > 0 && $obj->percent < 100 && !$obj->dp2 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) {
$late = 1;
}
if ($late) {
print img_warning($langs->trans("Late")).' ';
}
print '</td>'; print '</td>';
} }
@ -744,15 +921,16 @@ if ($resql)
// Third party // Third party
if (!empty($arrayfields['s.nom']['checked'])) { if (!empty($arrayfields['s.nom']['checked'])) {
print '<td class="tdoverflowmax150">'; print '<td class="tdoverflowmax150">';
if ($obj->socid > 0) if ($obj->socid > 0) {
{
$societestatic->id = $obj->socid; $societestatic->id = $obj->socid;
$societestatic->client = $obj->client; $societestatic->client = $obj->client;
$societestatic->name = $obj->societe; $societestatic->name = $obj->societe;
$societestatic->email = $obj->socemail; $societestatic->email = $obj->socemail;
print $societestatic->getNomUrl(1, '', 28); print $societestatic->getNomUrl(1, '', 28);
} else print '&nbsp;'; } else {
print '&nbsp;';
}
print '</td>'; print '</td>';
} }
@ -760,17 +938,13 @@ if ($resql)
if (!empty($arrayfields['a.fk_contact']['checked'])) { if (!empty($arrayfields['a.fk_contact']['checked'])) {
print '<td class="tdoverflowmax100">'; print '<td class="tdoverflowmax100">';
if (!empty($actionstatic->socpeopleassigned)) if (!empty($actionstatic->socpeopleassigned)) {
{
$contactList = array(); $contactList = array();
foreach ($actionstatic->socpeopleassigned as $socpeopleassigned) foreach ($actionstatic->socpeopleassigned as $socpeopleassigned) {
{ if (!isset($contactListCache[$socpeopleassigned['id']])) {
if (!isset($contactListCache[$socpeopleassigned['id']]))
{
// if no cache found we fetch it // if no cache found we fetch it
$contact = new Contact($db); $contact = new Contact($db);
if ($contact->fetch($socpeopleassigned['id']) > 0) if ($contact->fetch($socpeopleassigned['id']) > 0) {
{
$contactListCache[$socpeopleassigned['id']] = $contact->getNomUrl(1, '', 0); $contactListCache[$socpeopleassigned['id']] = $contact->getNomUrl(1, '', 0);
$contactList[] = $contact->getNomUrl(1, '', 0); $contactList[] = $contact->getNomUrl(1, '', 0);
} }
@ -782,8 +956,7 @@ if ($resql)
if (!empty($contactList)) { if (!empty($contactList)) {
print implode(', ', $contactList); print implode(', ', $contactList);
} }
} elseif ($obj->fk_contact > 0) //keep for retrocompatibility with faraway event } elseif ($obj->fk_contact > 0) { //keep for retrocompatibility with faraway event
{
$contactstatic->id = $obj->fk_contact; $contactstatic->id = $obj->fk_contact;
$contactstatic->email = $obj->email; $contactstatic->email = $obj->email;
$contactstatic->lastname = $obj->lastname; $contactstatic->lastname = $obj->lastname;
@ -835,10 +1008,11 @@ if ($resql)
} }
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->id, $arrayofselected)) $selected = 1; if (in_array($obj->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';

View File

@ -39,7 +39,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3; if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) {
$conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3;
}
$filter = GETPOST("search_filter", 'alpha', 3) ? GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); $filter = GETPOST("search_filter", 'alpha', 3) ? GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3);
$filtert = GETPOST("search_filtert", "int", 3) ? GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); $filtert = GETPOST("search_filtert", "int", 3) ? GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3);
@ -49,31 +51,43 @@ $usergroup = GETPOST("search_usergroup", "int", 3) ? GETPOST("search_usergroup",
$showbirthday = 0; $showbirthday = 0;
// If not choice done on calendar owner, we filter on user. // If not choice done on calendar owner, we filter on user.
if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) {
{
$filtert = $user->id; $filtert = $user->id;
} }
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$offset = $limit * $page; $offset = $limit * $page;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "a.datec"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "a.datec";
}
// Security check // Security check
$socid = GETPOST("search_socid", "int") ?GETPOST("search_socid", "int") : GETPOST("socid", "int"); $socid = GETPOST("search_socid", "int") ?GETPOST("search_socid", "int") : GETPOST("socid", "int");
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'agenda', 0, '', 'myactions'); $result = restrictedArea($user, 'agenda', 0, '', 'myactions');
if ($socid < 0) $socid = ''; if ($socid < 0) {
$socid = '';
}
$canedit = 1; $canedit = 1;
if (!$user->rights->agenda->myactions->read) accessforbidden(); if (!$user->rights->agenda->myactions->read) {
if (!$user->rights->agenda->allactions->read) $canedit = 0; accessforbidden();
if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no permission to see all, we show only affected to me }
{ if (!$user->rights->agenda->allactions->read) {
$canedit = 0;
}
if (!$user->rights->agenda->allactions->read || $filter == 'mine') { // If no permission to see all, we show only affected to me
$filtert = $user->id; $filtert = $user->id;
} }
@ -90,18 +104,20 @@ $type = GETPOST("search_type", 'alpha') ?GETPOST("search_type", 'alpha') : GETPO
$maxprint = ((GETPOST("maxprint", 'int') != '') ?GETPOST("maxprint", 'int') : $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); $maxprint = ((GETPOST("maxprint", 'int') != '') ?GETPOST("maxprint", 'int') : $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW);
$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
// Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index)
if (GETPOST('search_actioncode', 'array')) if (GETPOST('search_actioncode', 'array')) {
{
$actioncode = GETPOST('search_actioncode', 'array', 3); $actioncode = GETPOST('search_actioncode', 'array', 3);
if (!count($actioncode)) $actioncode = '0'; if (!count($actioncode)) {
$actioncode = '0';
}
} else { } else {
$actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE));
} }
if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); if ($actioncode == '' && empty($actioncodearray)) {
$actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE);
}
$dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); $dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int'));
if ($dateselect > 0) if ($dateselect > 0) {
{
$day = GETPOST('dateselectday', 'int'); $day = GETPOST('dateselectday', 'int');
$month = GETPOST('dateselectmonth', 'int'); $month = GETPOST('dateselectmonth', 'int');
$year = GETPOST('dateselectyear', 'int'); $year = GETPOST('dateselectyear', 'int');
@ -112,9 +128,15 @@ $tmp = str_replace(' ', '', $tmp); // FIX 7533
$tmparray = explode('-', $tmp); $tmparray = explode('-', $tmp);
$begin_h = GETPOST('begin_h', 'int') != '' ?GETPOST('begin_h', 'int') : ($tmparray[0] != '' ? $tmparray[0] : 9); $begin_h = GETPOST('begin_h', 'int') != '' ?GETPOST('begin_h', 'int') : ($tmparray[0] != '' ? $tmparray[0] : 9);
$end_h = GETPOST('end_h', 'int') ?GETPOST('end_h', 'int') : ($tmparray[1] != '' ? $tmparray[1] : 18); $end_h = GETPOST('end_h', 'int') ?GETPOST('end_h', 'int') : ($tmparray[1] != '' ? $tmparray[1] : 18);
if ($begin_h < 0 || $begin_h > 23) $begin_h = 9; if ($begin_h < 0 || $begin_h > 23) {
if ($end_h < 1 || $end_h > 24) $end_h = 18; $begin_h = 9;
if ($end_h <= $begin_h) $end_h = $begin_h + 1; }
if ($end_h < 1 || $end_h > 24) {
$end_h = 18;
}
if ($end_h <= $begin_h) {
$end_h = $begin_h + 1;
}
$tmp = empty($conf->global->MAIN_DEFAULT_WORKING_DAYS) ? '1-5' : $conf->global->MAIN_DEFAULT_WORKING_DAYS; $tmp = empty($conf->global->MAIN_DEFAULT_WORKING_DAYS) ? '1-5' : $conf->global->MAIN_DEFAULT_WORKING_DAYS;
$tmp = str_replace(' ', '', $tmp); // FIX 7533 $tmp = str_replace(' ', '', $tmp); // FIX 7533
@ -122,8 +144,12 @@ $tmparray = explode('-', $tmp);
$begin_d = 1; $begin_d = 1;
$end_d = 53; $end_d = 53;
if ($status == '' && !GETPOSTISSET('status')) $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); if ($status == '' && !GETPOSTISSET('status')) {
if (empty($action) && !GETPOSTISSET('action')) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS);
}
if (empty($action) && !GETPOSTISSET('action')) {
$action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW);
}
if (GETPOST('viewcal', 'alpha') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { if (GETPOST('viewcal', 'alpha') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') {
$action = 'show_month'; $day = ''; $action = 'show_month'; $day = '';
@ -149,8 +175,7 @@ $hookmanager->initHooks(array('agenda'));
* Actions * Actions
*/ */
if ($action == 'delete_action') if ($action == 'delete_action') {
{
$event = new ActionComm($db); $event = new ActionComm($db);
$event->fetch($actionid); $event->fetch($actionid);
$event->fetch_optionals(); $event->fetch_optionals();
@ -185,7 +210,9 @@ $parameters = array(
'usergroup' => $usergroup, 'usergroup' => $usergroup,
); );
$reshook = $hookmanager->executeHooks('beforeAgendaPerType', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('beforeAgendaPerType', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$form = new Form($db); $form = new Form($db);
$companystatic = new Societe($db); $companystatic = new Societe($db);
@ -223,29 +250,65 @@ $tmpday = $first_day;
//print 'xx'.$next_year.'-'.$next_month.'-'.$next_day; //print 'xx'.$next_year.'-'.$next_month.'-'.$next_day;
$title = $langs->trans("DoneAndToDoActions"); $title = $langs->trans("DoneAndToDoActions");
if ($status == 'done') $title = $langs->trans("DoneActions"); if ($status == 'done') {
if ($status == 'todo') $title = $langs->trans("ToDoActions"); $title = $langs->trans("DoneActions");
}
if ($status == 'todo') {
$title = $langs->trans("ToDoActions");
}
$param = ''; $param = '';
if ($actioncode || GETPOSTISSET('search_actioncode')) { if ($actioncode || GETPOSTISSET('search_actioncode')) {
if (is_array($actioncode)) { if (is_array($actioncode)) {
foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action); foreach ($actioncode as $str_action) {
} else $param .= "&search_actioncode=".urlencode($actioncode); $param .= "&search_actioncode[]=".urlencode($str_action);
}
} else {
$param .= "&search_actioncode=".urlencode($actioncode);
}
}
if ($resourceid > 0) {
$param .= "&search_resourceid=".urlencode($resourceid);
}
if ($status || GETPOSTISSET('status')) {
$param .= "&search_status=".urlencode($status);
}
if ($filter) {
$param .= "&search_filter=".urlencode($filter);
}
if ($filtert) {
$param .= "&search_filtert=".urlencode($filtert);
}
if ($usergroup > 0) {
$param .= "&search_usergroup=".urlencode($usergroup);
}
if ($socid > 0) {
$param .= "&search_socid=".urlencode($socid);
}
if ($showbirthday) {
$param .= "&search_showbirthday=1";
}
if ($pid) {
$param .= "&search_projectid=".urlencode($pid);
}
if ($type) {
$param .= "&search_type=".urlencode($type);
}
if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') {
$param .= '&action='.urlencode($action);
}
if ($begin_h != '') {
$param .= '&begin_h='.urlencode($begin_h);
}
if ($end_h != '') {
$param .= '&end_h='.urlencode($end_h);
}
if ($begin_d != '') {
$param .= '&begin_d='.urlencode($begin_d);
}
if ($end_d != '') {
$param .= '&end_d='.urlencode($end_d);
} }
if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid);
if ($status || GETPOSTISSET('status')) $param .= "&search_status=".urlencode($status);
if ($filter) $param .= "&search_filter=".urlencode($filter);
if ($filtert) $param .= "&search_filtert=".urlencode($filtert);
if ($usergroup > 0) $param .= "&search_usergroup=".urlencode($usergroup);
if ($socid > 0) $param .= "&search_socid=".urlencode($socid);
if ($showbirthday) $param .= "&search_showbirthday=1";
if ($pid) $param .= "&search_projectid=".urlencode($pid);
if ($type) $param .= "&search_type=".urlencode($type);
if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param .= '&action='.urlencode($action);
if ($begin_h != '') $param .= '&begin_h='.urlencode($begin_h);
if ($end_h != '') $param .= '&end_h='.urlencode($end_h);
if ($begin_d != '') $param .= '&begin_d='.urlencode($begin_d);
if ($end_d != '') $param .= '&end_d='.urlencode($end_d);
$param .= "&maxprint=".urlencode($maxprint); $param .= "&maxprint=".urlencode($maxprint);
$paramnoactionodate = $param; $paramnoactionodate = $param;
@ -301,28 +364,23 @@ print '<form method="POST" id="searchFormList" class="listactionsfilter" action=
$showextcals = $listofextcals; $showextcals = $listofextcals;
// Legend // Legend
if ($conf->use_javascript_ajax) if ($conf->use_javascript_ajax) {
{
$s = ''; $s = '';
$s .= '<script type="text/javascript">'."\n"; $s .= '<script type="text/javascript">'."\n";
$s .= 'jQuery(document).ready(function () {'."\n"; $s .= 'jQuery(document).ready(function () {'."\n";
$s .= 'jQuery("#check_mytasks").click(function() { jQuery(".family_mytasks").toggle(); jQuery(".family_other").toggle(); });'."\n"; $s .= 'jQuery("#check_mytasks").click(function() { jQuery(".family_mytasks").toggle(); jQuery(".family_other").toggle(); });'."\n";
$s .= 'jQuery("#check_birthday").click(function() { jQuery(".family_birthday").toggle(); });'."\n"; $s .= 'jQuery("#check_birthday").click(function() { jQuery(".family_birthday").toggle(); });'."\n";
$s .= 'jQuery(".family_birthday").toggle();'."\n"; $s .= 'jQuery(".family_birthday").toggle();'."\n";
if ($action == "show_week" || $action == "show_month" || empty($action)) if ($action == "show_week" || $action == "show_month" || empty($action)) {
{
$s .= 'jQuery( "td.sortable" ).sortable({connectWith: ".sortable",placeholder: "ui-state-highlight",items: "div:not(.unsortable)", receive: function( event, ui ) {'; $s .= 'jQuery( "td.sortable" ).sortable({connectWith: ".sortable",placeholder: "ui-state-highlight",items: "div:not(.unsortable)", receive: function( event, ui ) {';
$s .= 'var frm=jQuery("#move_event");frm.attr("action",ui.item.find("a.cal_event").attr("href")).children("#newdate").val(jQuery(event.target).closest("div").attr("id"));frm.submit();}});'."\n"; $s .= 'var frm=jQuery("#move_event");frm.attr("action",ui.item.find("a.cal_event").attr("href")).children("#newdate").val(jQuery(event.target).closest("div").attr("id"));frm.submit();}});'."\n";
} }
$s .= '});'."\n"; $s .= '});'."\n";
$s .= '</script>'."\n"; $s .= '</script>'."\n";
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
$s .= '<div class="nowrap clear float"><input type="checkbox" id="check_mytasks" name="check_mytasks" checked disabled> '.$langs->trans("LocalAgenda").' &nbsp; </div>'; $s .= '<div class="nowrap clear float"><input type="checkbox" id="check_mytasks" name="check_mytasks" checked disabled> '.$langs->trans("LocalAgenda").' &nbsp; </div>';
if (is_array($showextcals) && count($showextcals) > 0) if (is_array($showextcals) && count($showextcals) > 0) {
{ foreach ($showextcals as $val) {
foreach ($showextcals as $val)
{
$htmlname = md5($val['name']); $htmlname = md5($val['name']);
$s .= '<script type="text/javascript">'."\n"; $s .= '<script type="text/javascript">'."\n";
$s .= 'jQuery(document).ready(function () {'."\n"; $s .= 'jQuery(document).ready(function () {'."\n";
@ -341,11 +399,9 @@ if ($conf->use_javascript_ajax)
// Calendars from hooks // Calendars from hooks
$parameters = array(); $object = null; $parameters = array(); $object = null;
$reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action);
if (empty($reshook)) if (empty($reshook)) {
{
$s .= $hookmanager->resPrint; $s .= $hookmanager->resPrint;
} elseif ($reshook > 1) } elseif ($reshook > 1) {
{
$s = $hookmanager->resPrint; $s = $hookmanager->resPrint;
} }
} }
@ -397,8 +453,7 @@ if (empty($reshook)) {
$newcardbutton = ''; $newcardbutton = '';
if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) {
{
$tmpforcreatebutton = dol_getdate(dol_now(), true); $tmpforcreatebutton = dol_getdate(dol_now(), true);
$newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year']; $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year'];
@ -435,7 +490,9 @@ $eventarray = array();
// DEFAULT CALENDAR + AUTOEVENT CALENDAR + CONFERENCEBOOTH CALENDAR // DEFAULT CALENDAR + AUTOEVENT CALENDAR + CONFERENCEBOOTH CALENDAR
$sql = 'SELECT'; $sql = 'SELECT';
if ($usergroup > 0) $sql .= " DISTINCT"; if ($usergroup > 0) {
$sql .= " DISTINCT";
}
$sql .= ' a.id, a.label,'; $sql .= ' a.id, a.label,';
$sql .= ' a.datep,'; $sql .= ' a.datep,';
$sql .= ' a.datep2,'; $sql .= ' a.datep2,';
@ -445,31 +502,44 @@ $sql .= ' a.transparency, a.priority, a.fulldayevent, a.location,';
$sql .= ' a.fk_soc, a.fk_contact, a.fk_element, a.elementtype, a.fk_project,'; $sql .= ' a.fk_soc, a.fk_contact, a.fk_element, a.elementtype, a.fk_project,';
$sql .= ' ca.code, ca.libelle as type_label, ca.color, ca.type as type_type, ca.picto as type_picto'; $sql .= ' ca.code, ca.libelle as type_label, ca.color, ca.type as type_type, ca.picto as type_picto';
$sql .= ' FROM '.MAIN_DB_PREFIX.'c_actioncomm as ca, '.MAIN_DB_PREFIX."actioncomm as a"; $sql .= ' FROM '.MAIN_DB_PREFIX.'c_actioncomm as ca, '.MAIN_DB_PREFIX."actioncomm as a";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
}
// We must filter on resource table // We must filter on resource table
if ($resourceid > 0) $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; if ($resourceid > 0) {
$sql .= ", ".MAIN_DB_PREFIX."element_resources as r";
}
// We must filter on assignement table // We must filter on assignement table
if ($filtert > 0 || $usergroup > 0) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; if ($filtert > 0 || $usergroup > 0) {
if ($usergroup > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
}
if ($usergroup > 0) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element";
}
$sql .= ' WHERE a.fk_action = ca.id'; $sql .= ' WHERE a.fk_action = ca.id';
$sql .= ' AND a.entity IN ('.getEntity('agenda').')'; $sql .= ' AND a.entity IN ('.getEntity('agenda').')';
// Condition on actioncode // Condition on actioncode
if (!empty($actioncode)) if (!empty($actioncode)) {
{ if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) if ($actioncode == 'AC_NON_AUTO') {
{ $sql .= " AND ca.type != 'systemauto'";
if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; } elseif ($actioncode == 'AC_ALL_AUTO') {
elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; $sql .= " AND ca.type = 'systemauto'";
else { } else {
if ($actioncode == 'AC_OTH') $sql .= " AND ca.type != 'systemauto'"; if ($actioncode == 'AC_OTH') {
if ($actioncode == 'AC_OTH_AUTO') $sql .= " AND ca.type = 'systemauto'"; $sql .= " AND ca.type != 'systemauto'";
}
if ($actioncode == 'AC_OTH_AUTO') {
$sql .= " AND ca.type = 'systemauto'";
}
} }
} else { } else {
if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; if ($actioncode == 'AC_NON_AUTO') {
elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; $sql .= " AND ca.type != 'systemauto'";
else { } elseif ($actioncode == 'AC_ALL_AUTO') {
if (is_array($actioncode)) $sql .= " AND ca.type = 'systemauto'";
{ } else {
if (is_array($actioncode)) {
$sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')";
} else { } else {
$sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; $sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')";
@ -477,14 +547,23 @@ if (!empty($actioncode))
} }
} }
} }
if ($resourceid > 0) $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); if ($resourceid > 0) {
if ($pid) $sql .= " AND a.fk_project=".$db->escape($pid); $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid);
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; }
if ($socid > 0) $sql .= ' AND a.fk_soc = '.$socid; if ($pid) {
$sql .= " AND a.fk_project=".$db->escape($pid);
}
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")";
}
if ($socid > 0) {
$sql .= ' AND a.fk_soc = '.$socid;
}
// We must filter on assignement table // We must filter on assignement table
if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; if ($filtert > 0 || $usergroup > 0) {
if ($action == 'show_day') $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
{ }
if ($action == 'show_day') {
$sql .= " AND ("; $sql .= " AND (";
$sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year, 'tzuserrel'))."'"; $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year, 'tzuserrel'))."'";
$sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')";
@ -508,18 +587,33 @@ if ($action == 'show_day')
$sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, 12, 31, $year) + (60 * 60 * 24 * 7))."')"; $sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, 12, 31, $year) + (60 * 60 * 24 * 7))."')";
$sql .= ')'; $sql .= ')';
} }
if ($type) $sql .= " AND ca.id = ".$type; if ($type) {
if ($status == '0') { $sql .= " AND a.percent = 0"; } $sql .= " AND ca.id = ".$type;
if ($status == '-1') { $sql .= " AND a.percent = -1"; } // Not applicable }
if ($status == '50') { $sql .= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started if ($status == '0') {
if ($status == 'done' || $status == '100') { $sql .= " AND (a.percent = 100)"; } $sql .= " AND a.percent = 0";
if ($status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } }
if ($status == '-1') {
$sql .= " AND a.percent = -1";
} // Not applicable
if ($status == '50') {
$sql .= " AND (a.percent > 0 AND a.percent < 100)";
} // Running already started
if ($status == 'done' || $status == '100') {
$sql .= " AND (a.percent = 100)";
}
if ($status == 'todo') {
$sql .= " AND (a.percent >= 0 AND a.percent < 100)";
}
// We must filter on assignement table // We must filter on assignement table
if ($filtert > 0 || $usergroup > 0) if ($filtert > 0 || $usergroup > 0) {
{
$sql .= " AND ("; $sql .= " AND (";
if ($filtert > 0) $sql .= "ar.fk_element = ".$filtert; if ($filtert > 0) {
if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; $sql .= "ar.fk_element = ".$filtert;
}
if ($usergroup > 0) {
$sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup;
}
$sql .= ")"; $sql .= ")";
} }
// Sort on date // Sort on date
@ -528,17 +622,14 @@ $sql .= ' ORDER BY fk_user_action, datep'; //fk_user_action
dol_syslog("comm/action/pertype.php", LOG_DEBUG); dol_syslog("comm/action/pertype.php", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
// Discard auto action if option is on // Discard auto action if option is on
if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->code == 'AC_OTH_AUTO') if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->code == 'AC_OTH_AUTO') {
{
$i++; $i++;
continue; continue;
} }
@ -572,34 +663,41 @@ if ($resql)
// Defined date_start_in_calendar and date_end_in_calendar property // 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. // They are date start and end of action but modified to not be outside calendar view.
if ($event->percentage <= 0) if ($event->percentage <= 0) {
{
$event->date_start_in_calendar = $datep; $event->date_start_in_calendar = $datep;
if ($datep2 != '' && $datep2 >= $datep) $event->date_end_in_calendar = $datep2; if ($datep2 != '' && $datep2 >= $datep) {
else $event->date_end_in_calendar = $datep; $event->date_end_in_calendar = $datep2;
} else {
$event->date_end_in_calendar = $datep;
}
} else { } else {
$event->date_start_in_calendar = $datep; $event->date_start_in_calendar = $datep;
if ($datep2 != '' && $datep2 >= $datep) $event->date_end_in_calendar = $datep2; if ($datep2 != '' && $datep2 >= $datep) {
else $event->date_end_in_calendar = $datep; $event->date_end_in_calendar = $datep2;
} else {
$event->date_end_in_calendar = $datep;
}
} }
// Define ponctual property // Define ponctual property
if ($event->date_start_in_calendar == $event->date_end_in_calendar) if ($event->date_start_in_calendar == $event->date_end_in_calendar) {
{
$event->ponctuel = 1; $event->ponctuel = 1;
} }
// Check values // Check values
if ($event->date_end_in_calendar < $firstdaytoshow || if ($event->date_end_in_calendar < $firstdaytoshow ||
$event->date_start_in_calendar >= $lastdaytoshow) $event->date_start_in_calendar >= $lastdaytoshow) {
{
// This record is out of visible range // This record is out of visible range
unset($event); unset($event);
} else { } else {
//print $i.' - '.dol_print_date($this->date_start_in_calendar, 'dayhour').' - '.dol_print_date($this->date_end_in_calendar, 'dayhour').'<br>'."\n"; //print $i.' - '.dol_print_date($this->date_start_in_calendar, 'dayhour').' - '.dol_print_date($this->date_end_in_calendar, 'dayhour').'<br>'."\n";
$event->fetch_userassigned(); // This load $event->userassigned $event->fetch_userassigned(); // This load $event->userassigned
if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; if ($event->date_start_in_calendar < $firstdaytoshow) {
if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); $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 // Add an entry in actionarray for each day
$daycursor = $event->date_start_in_calendar; $daycursor = $event->date_start_in_calendar;
@ -617,7 +715,9 @@ if ($resql)
$j++; $j++;
$daykey += 60 * 60 * 24; $daykey += 60 * 60 * 24;
if ($daykey > $event->date_end_in_calendar) $loop = false; if ($daykey > $event->date_end_in_calendar) {
$loop = false;
}
} while ($loop); } while ($loop);
//print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef);
@ -637,11 +737,12 @@ $cacheusers = array();
// Define theme_datacolor array // Define theme_datacolor array
$color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php";
if (is_readable($color_file)) if (is_readable($color_file)) {
{
include_once $color_file; include_once $color_file;
} }
if (!is_array($theme_datacolor)) $theme_datacolor = array(array(120, 130, 150), array(200, 160, 180), array(190, 190, 220)); if (!is_array($theme_datacolor)) {
$theme_datacolor = array(array(120, 130, 150), array(200, 160, 180), array(190, 190, 220));
}
$newparam = $param; // newparam is for birthday links $newparam = $param; // newparam is for birthday links
@ -681,8 +782,7 @@ echo "</tr>\n";
echo '<tr class="liste_titre">'; echo '<tr class="liste_titre">';
echo '<td></td>'; echo '<td></td>';
$i = 0; $i = 0;
for ($h = $begin_d; $h < $end_d; $h++) for ($h = $begin_d; $h < $end_d; $h++) {
{
echo '<td class="center">'; echo '<td class="center">';
print '<small style="font-family: courier">'.sprintf("%02d", $h).'</small>'; print '<small style="font-family: courier">'.sprintf("%02d", $h).'</small>';
print "</td>"; print "</td>";
@ -698,8 +798,7 @@ $colorsbytype = array();
$labelbytype = array(); $labelbytype = array();
$sql = "SELECT code, color, libelle as label FROM ".MAIN_DB_PREFIX."c_actioncomm ORDER BY position"; $sql = "SELECT code, color, libelle as label FROM ".MAIN_DB_PREFIX."c_actioncomm ORDER BY position";
$resql = $db->query($sql); $resql = $db->query($sql);
while ($obj = $db->fetch_object($resql)) while ($obj = $db->fetch_object($resql)) {
{
$typeofevents[$obj->code] = $obj->code; $typeofevents[$obj->code] = $obj->code;
$colorsbytype[$obj->code] = $obj->color; $colorsbytype[$obj->code] = $obj->color;
$labelbytype[$obj->code] = $obj->label; $labelbytype[$obj->code] = $obj->label;
@ -710,8 +809,7 @@ $todayarray = dol_getdate($now, 'fast');
$sav = $tmpday; $sav = $tmpday;
$showheader = true; $showheader = true;
$var = false; $var = false;
foreach ($typeofevents as $typeofevent) foreach ($typeofevents as $typeofevent) {
{
$var = !$var; $var = !$var;
echo "<tr>"; echo "<tr>";
echo '<td class="cal_current_month cal_peruserviewname'.($var ? ' cal_impair' : '').'">'.$typeofevent.'</td>'; echo '<td class="cal_current_month cal_peruserviewname'.($var ? ' cal_impair' : '').'">'.$typeofevent.'</td>';
@ -719,10 +817,8 @@ foreach ($typeofevents as $typeofevent)
// Lopp on each day of week // Lopp on each day of week
$i = 0; $i = 0;
for ($iter_day = 0; $iter_day < 8; $iter_day++) for ($iter_day = 0; $iter_day < 8; $iter_day++) {
{ if (($i + 1) < $begin_d || ($i + 1) > $end_d) {
if (($i + 1) < $begin_d || ($i + 1) > $end_d)
{
$i++; $i++;
continue; continue;
} }
@ -735,10 +831,16 @@ foreach ($typeofevents as $typeofevent)
$tmpyear = $tmparray['year']; $tmpyear = $tmparray['year'];
$style = 'cal_current_month'; $style = 'cal_current_month';
if ($iter_day == 6) $style .= ' cal_other_month'; if ($iter_day == 6) {
$style .= ' cal_other_month';
}
$today = 0; $today = 0;
if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) {
if ($today) $style = 'cal_today_peruser'; $today = 1;
}
if ($today) {
$style = 'cal_today_peruser';
}
show_day_events_pertype($typeofevent, $tmpday, $tmpmonth, $tmpyear, 0, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); show_day_events_pertype($typeofevent, $tmpday, $tmpmonth, $tmpyear, 0, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var);
@ -751,14 +853,11 @@ foreach ($typeofevents as $typeofevent)
echo "</table>\n"; echo "</table>\n";
echo "<br>"; echo "<br>";
if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
{
$langs->load("commercial"); $langs->load("commercial");
print '<br>'.$langs->trans("Legend").': <br>'; print '<br>'.$langs->trans("Legend").': <br>';
foreach ($colorsbytype as $code => $color) foreach ($colorsbytype as $code => $color) {
{ if ($color) {
if ($color)
{
print '<div style="float: left; padding: 2px; margin-right: 6px;"><div style="'.($color ? 'background: #'.$color.';' : '').'width:16px; float: left; margin-right: 4px;">&nbsp;</div>'; print '<div style="float: left; padding: 2px; margin-right: 6px;"><div style="'.($color ? 'background: #'.$color.';' : '').'width:16px; float: left; margin-right: 4px;">&nbsp;</div>';
print $langs->trans("Action".$code) != "Action".$code ? $langs->trans("Action".$code) : $labelbytype[$code]; print $langs->trans("Action".$code) != "Action".$code ? $langs->trans("Action".$code) : $labelbytype[$code];
//print $code; //print $code;
@ -860,41 +959,41 @@ function show_day_events_pertype($username, $day, $month, $year, $monthshown, $s
//if ($username->id && $day==1) var_dump($eventarray); //if ($username->id && $day==1) var_dump($eventarray);
// We are in a particular day for $username, now we scan all events // We are in a particular day for $username, now we scan all events
foreach ($eventarray as $daykey => $notused) foreach ($eventarray as $daykey => $notused) {
{
$annee = dol_print_date($daykey, '%Y'); $annee = dol_print_date($daykey, '%Y');
$mois = dol_print_date($daykey, '%m'); $mois = dol_print_date($daykey, '%m');
$jour = dol_print_date($daykey, '%d'); $jour = dol_print_date($daykey, '%d');
if ($day == $jour && $month == $mois && $year == $annee) // Is it the day we are looking for when calling function ? if ($day == $jour && $month == $mois && $year == $annee) { // Is it the day we are looking for when calling function ?
{
// Scan all event for this date // Scan all event for this date
foreach ($eventarray[$daykey] as $index => $event) foreach ($eventarray[$daykey] as $index => $event) {
{
//print $daykey.' '.$year.'-'.$month.'-'.$day.' -> '.$event->id.' '.$index.' '.$annee.'-'.$mois.'-'.$jour."<br>\n"; //print $daykey.' '.$year.'-'.$month.'-'.$day.' -> '.$event->id.' '.$index.' '.$annee.'-'.$mois.'-'.$jour."<br>\n";
//var_dump($event); //var_dump($event);
$keysofuserassigned = array_keys($event->userassigned); $keysofuserassigned = array_keys($event->userassigned);
if (!in_array($username->id, $keysofuserassigned)) continue; // We discard record if event is from another user than user we want to show if (!in_array($username->id, $keysofuserassigned)) {
continue; // We discard record if event is from another user than user we want to show
}
//if ($username->id != $event->userownerid) continue; // We discard record if event is from another user than user we want to show //if ($username->id != $event->userownerid) continue; // We discard record if event is from another user than user we want to show
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('formatEvent', $parameters, $event, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('formatEvent', $parameters, $event, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar);
// Define $color (Hex string like '0088FF') and $cssclass of event // Define $color (Hex string like '0088FF') and $cssclass of event
$color = -1; $cssclass = ''; $colorindex = -1; $color = -1; $cssclass = ''; $colorindex = -1;
if (in_array($user->id, $keysofuserassigned)) if (in_array($user->id, $keysofuserassigned)) {
{
$nummytasks++; $cssclass = 'family_mytasks'; $nummytasks++; $cssclass = 'family_mytasks';
if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $color = $event->type_color; if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
} elseif ($event->type_code == 'ICALEVENT') $color = $event->type_color;
{ }
} elseif ($event->type_code == 'ICALEVENT') {
$numical++; $numical++;
if (!empty($event->icalname)) if (!empty($event->icalname)) {
{
if (!isset($numicals[dol_string_nospecial($event->icalname)])) { if (!isset($numicals[dol_string_nospecial($event->icalname)])) {
$numicals[dol_string_nospecial($event->icalname)] = 0; $numicals[dol_string_nospecial($event->icalname)] = 0;
} }
@ -903,25 +1002,26 @@ function show_day_events_pertype($username, $day, $month, $year, $monthshown, $s
$color = $event->icalcolor; $color = $event->icalcolor;
$cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other unsortable'); $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other unsortable');
} elseif ($event->type_code == 'BIRTHDAY') } elseif ($event->type_code == 'BIRTHDAY') {
{
$numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unsortable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unsortable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]);
} else { } else {
$numother++; $cssclass = 'family_other'; $numother++; $cssclass = 'family_other';
if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $color = $event->type_color; if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
$color = $event->type_color;
}
} }
if ($color < 0) // Color was not set on user card. Set color according to color index. if ($color < 0) { // Color was not set on user card. Set color according to color index.
{
// Define color index if not yet defined // Define color index if not yet defined
$idusertouse = ($event->userownerid ? $event->userownerid : 0); $idusertouse = ($event->userownerid ? $event->userownerid : 0);
if (isset($colorindexused[$idusertouse])) if (isset($colorindexused[$idusertouse])) {
{
$colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user
} else { } else {
$colorindex = $nextindextouse; $colorindex = $nextindextouse;
$colorindexused[$idusertouse] = $colorindex; $colorindexused[$idusertouse] = $colorindex;
if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color if (!empty($theme_datacolor[$nextindextouse + 1])) {
$nextindextouse++; // Prepare to use next color
}
} }
// Define color // Define color
$color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]);
@ -929,60 +1029,57 @@ function show_day_events_pertype($username, $day, $month, $year, $monthshown, $s
//$cssclass=$cssclass.' '.$cssclass.'_day_'.$ymd; //$cssclass=$cssclass.' '.$cssclass.'_day_'.$ymd;
// Define all rects with event (cases1 is first half hour, cases2 is second half hour) // Define all rects with event (cases1 is first half hour, cases2 is second half hour)
for ($h = $begin_h; $h < $end_h; $h++) for ($h = $begin_h; $h < $end_h; $h++) {
{
//if ($username->id == 1 && $day==1) print 'h='.$h; //if ($username->id == 1 && $day==1) print 'h='.$h;
$newcolor = ''; //init $newcolor = ''; //init
if (empty($event->fulldayevent)) if (empty($event->fulldayevent)) {
{
$a = dol_mktime((int) $h, 0, 0, $month, $day, $year, 'tzuserrel', 0); $a = dol_mktime((int) $h, 0, 0, $month, $day, $year, 'tzuserrel', 0);
$b = dol_mktime((int) $h, 30, 0, $month, $day, $year, 'tzuserrel', 0); $b = dol_mktime((int) $h, 30, 0, $month, $day, $year, 'tzuserrel', 0);
$c = dol_mktime((int) $h + 1, 0, 0, $month, $day, $year, 'tzuserrel', 0); $c = dol_mktime((int) $h + 1, 0, 0, $month, $day, $year, 'tzuserrel', 0);
$dateendtouse = $event->date_end_in_calendar; $dateendtouse = $event->date_end_in_calendar;
if ($dateendtouse == $event->date_start_in_calendar) $dateendtouse++; if ($dateendtouse == $event->date_start_in_calendar) {
$dateendtouse++;
}
//print dol_print_date($event->date_start_in_calendar,'dayhour').'-'.dol_print_date($a,'dayhour').'-'.dol_print_date($b,'dayhour').'<br>'; //print dol_print_date($event->date_start_in_calendar,'dayhour').'-'.dol_print_date($a,'dayhour').'-'.dol_print_date($b,'dayhour').'<br>';
if ($event->date_start_in_calendar < $b && $dateendtouse > $a) if ($event->date_start_in_calendar < $b && $dateendtouse > $a) {
{
$busy = $event->transparency; $busy = $event->transparency;
$cases1[$h][$event->id]['busy'] = $busy; $cases1[$h][$event->id]['busy'] = $busy;
$cases1[$h][$event->id]['string'] = dol_print_date($event->date_start_in_calendar, 'dayhour', 'tzuserrel'); $cases1[$h][$event->id]['string'] = dol_print_date($event->date_start_in_calendar, 'dayhour', 'tzuserrel');
if ($event->date_end_in_calendar && $event->date_end_in_calendar != $event->date_start_in_calendar) if ($event->date_end_in_calendar && $event->date_end_in_calendar != $event->date_start_in_calendar) {
{
$tmpa = dol_getdate($event->date_start_in_calendar, true); $tmpa = dol_getdate($event->date_start_in_calendar, true);
$tmpb = dol_getdate($event->date_end_in_calendar, true); $tmpb = dol_getdate($event->date_end_in_calendar, true);
if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $cases1[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel'); if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
else $cases1[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'dayhour', 'tzuserrel'); $cases1[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel');
} else {
$cases1[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'dayhour', 'tzuserrel');
}
}
if ($event->label) {
$cases1[$h][$event->id]['string'] .= ' - '.$event->label;
} }
if ($event->label) $cases1[$h][$event->id]['string'] .= ' - '.$event->label;
$cases1[$h][$event->id]['typecode'] = $event->type_code; $cases1[$h][$event->id]['typecode'] = $event->type_code;
$cases1[$h][$event->id]['color'] = $color; $cases1[$h][$event->id]['color'] = $color;
if ($event->fk_project > 0) if ($event->fk_project > 0) {
{ if (empty($cacheprojects[$event->fk_project])) {
if (empty($cacheprojects[$event->fk_project]))
{
$tmpproj = new Project($db); $tmpproj = new Project($db);
$tmpproj->fetch($event->fk_project); $tmpproj->fetch($event->fk_project);
$cacheprojects[$event->fk_project] = $tmpproj; $cacheprojects[$event->fk_project] = $tmpproj;
} }
$cases1[$h][$event->id]['string'] .= ', '.$langs->trans("Project").': '.$cacheprojects[$event->fk_project]->ref.' - '.$cacheprojects[$event->fk_project]->title; $cases1[$h][$event->id]['string'] .= ', '.$langs->trans("Project").': '.$cacheprojects[$event->fk_project]->ref.' - '.$cacheprojects[$event->fk_project]->title;
} }
if ($event->socid > 0) if ($event->socid > 0) {
{ if (empty($cachethirdparties[$event->socid])) {
if (empty($cachethirdparties[$event->socid]))
{
$tmpthirdparty = new Societe($db); $tmpthirdparty = new Societe($db);
$tmpthirdparty->fetch($event->socid); $tmpthirdparty->fetch($event->socid);
$cachethirdparties[$event->socid] = $tmpthirdparty; $cachethirdparties[$event->socid] = $tmpthirdparty;
} }
$cases1[$h][$event->id]['string'] .= ', '.$cachethirdparties[$event->socid]->name; $cases1[$h][$event->id]['string'] .= ', '.$cachethirdparties[$event->socid]->name;
} }
if ($event->contact_id > 0) if ($event->contact_id > 0) {
{ if (empty($cachecontacts[$event->contact_id])) {
if (empty($cachecontacts[$event->contact_id]))
{
$tmpcontact = new Contact($db); $tmpcontact = new Contact($db);
$tmpcontact->fetch($event->contact_id); $tmpcontact->fetch($event->contact_id);
$cachecontacts[$event->contact_id] = $tmpcontact; $cachecontacts[$event->contact_id] = $tmpcontact;
@ -990,45 +1087,42 @@ function show_day_events_pertype($username, $day, $month, $year, $monthshown, $s
$cases1[$h][$event->id]['string'] .= ', '.$cachecontacts[$event->contact_id]->getFullName($langs); $cases1[$h][$event->id]['string'] .= ', '.$cachecontacts[$event->contact_id]->getFullName($langs);
} }
} }
if ($event->date_start_in_calendar < $c && $dateendtouse > $b) if ($event->date_start_in_calendar < $c && $dateendtouse > $b) {
{
$busy = $event->transparency; $busy = $event->transparency;
$cases2[$h][$event->id]['busy'] = $busy; $cases2[$h][$event->id]['busy'] = $busy;
$cases2[$h][$event->id]['string'] = dol_print_date($event->date_start_in_calendar, 'dayhour', 'tzuserrel'); $cases2[$h][$event->id]['string'] = dol_print_date($event->date_start_in_calendar, 'dayhour', 'tzuserrel');
if ($event->date_end_in_calendar && $event->date_end_in_calendar != $event->date_start_in_calendar) if ($event->date_end_in_calendar && $event->date_end_in_calendar != $event->date_start_in_calendar) {
{
$tmpa = dol_getdate($event->date_start_in_calendar, true); $tmpa = dol_getdate($event->date_start_in_calendar, true);
$tmpb = dol_getdate($event->date_end_in_calendar, true); $tmpb = dol_getdate($event->date_end_in_calendar, true);
if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $cases2[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel'); if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
else $cases2[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'dayhour', 'tzuserrel'); $cases2[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel');
} else {
$cases2[$h][$event->id]['string'] .= '-'.dol_print_date($event->date_end_in_calendar, 'dayhour', 'tzuserrel');
}
}
if ($event->label) {
$cases2[$h][$event->id]['string'] .= ' - '.$event->label;
} }
if ($event->label) $cases2[$h][$event->id]['string'] .= ' - '.$event->label;
$cases2[$h][$event->id]['typecode'] = $event->type_code; $cases2[$h][$event->id]['typecode'] = $event->type_code;
$cases2[$h][$event->id]['color'] = $color; $cases2[$h][$event->id]['color'] = $color;
if ($event->fk_project > 0) if ($event->fk_project > 0) {
{ if (empty($cacheprojects[$event->fk_project])) {
if (empty($cacheprojects[$event->fk_project]))
{
$tmpproj = new Project($db); $tmpproj = new Project($db);
$tmpproj->fetch($event->fk_project); $tmpproj->fetch($event->fk_project);
$cacheprojects[$event->fk_project] = $tmpproj; $cacheprojects[$event->fk_project] = $tmpproj;
} }
$cases2[$h][$event->id]['string'] .= ', '.$langs->trans("Project").': '.$cacheprojects[$event->fk_project]->ref.' - '.$cacheprojects[$event->fk_project]->title; $cases2[$h][$event->id]['string'] .= ', '.$langs->trans("Project").': '.$cacheprojects[$event->fk_project]->ref.' - '.$cacheprojects[$event->fk_project]->title;
} }
if ($event->socid > 0) if ($event->socid > 0) {
{ if (empty($cachethirdparties[$event->socid])) {
if (empty($cachethirdparties[$event->socid]))
{
$tmpthirdparty = new Societe($db); $tmpthirdparty = new Societe($db);
$tmpthirdparty->fetch($event->socid); $tmpthirdparty->fetch($event->socid);
$cachethirdparties[$event->socid] = $tmpthirdparty; $cachethirdparties[$event->socid] = $tmpthirdparty;
} }
$cases2[$h][$event->id]['string'] .= ', '.$cachethirdparties[$event->socid]->name; $cases2[$h][$event->id]['string'] .= ', '.$cachethirdparties[$event->socid]->name;
} }
if ($event->contact_id > 0) if ($event->contact_id > 0) {
{ if (empty($cachecontacts[$event->contact_id])) {
if (empty($cachecontacts[$event->contact_id]))
{
$tmpcontact = new Contact($db); $tmpcontact = new Contact($db);
$tmpcontact->fetch($event->contact_id); $tmpcontact->fetch($event->contact_id);
$cachecontacts[$event->contact_id] = $tmpcontact; $cachecontacts[$event->contact_id] = $tmpcontact;
@ -1056,63 +1150,83 @@ function show_day_events_pertype($username, $day, $month, $year, $monthshown, $s
} }
// Now output $casesX // Now output $casesX
for ($h = $begin_h; $h < $end_h; $h++) for ($h = $begin_h; $h < $end_h; $h++) {
{
$color1 = ''; $color2 = ''; $color1 = ''; $color2 = '';
$style1 = ''; $style2 = ''; $style1 = ''; $style2 = '';
$string1 = '&nbsp;'; $string2 = '&nbsp;'; $string1 = '&nbsp;'; $string2 = '&nbsp;';
$title1 = ''; $title2 = ''; $title1 = ''; $title2 = '';
if (isset($cases1[$h]) && $cases1[$h] != '') if (isset($cases1[$h]) && $cases1[$h] != '') {
{
//$title1.=count($cases1[$h]).' '.(count($cases1[$h])==1?$langs->trans("Event"):$langs->trans("Events")); //$title1.=count($cases1[$h]).' '.(count($cases1[$h])==1?$langs->trans("Event"):$langs->trans("Events"));
if (count($cases1[$h]) > 1) $title1 .= count($cases1[$h]).' '.(count($cases1[$h]) == 1 ? $langs->trans("Event") : $langs->trans("Events")); if (count($cases1[$h]) > 1) {
$title1 .= count($cases1[$h]).' '.(count($cases1[$h]) == 1 ? $langs->trans("Event") : $langs->trans("Events"));
}
$string1 = '&nbsp;'; $string1 = '&nbsp;';
if (empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) $style1 = 'peruser_notbusy'; if (empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) {
else $style1 = 'peruser_busy'; $style1 = 'peruser_notbusy';
foreach ($cases1[$h] as $id => $ev) } else {
{ $style1 = 'peruser_busy';
if ($ev['busy']) $style1 = 'peruser_busy'; }
foreach ($cases1[$h] as $id => $ev) {
if ($ev['busy']) {
$style1 = 'peruser_busy';
} }
} }
if (isset($cases2[$h]) && $cases2[$h] != '') }
{ if (isset($cases2[$h]) && $cases2[$h] != '') {
//$title2.=count($cases2[$h]).' '.(count($cases2[$h])==1?$langs->trans("Event"):$langs->trans("Events")); //$title2.=count($cases2[$h]).' '.(count($cases2[$h])==1?$langs->trans("Event"):$langs->trans("Events"));
if (count($cases2[$h]) > 1) $title2 .= count($cases2[$h]).' '.(count($cases2[$h]) == 1 ? $langs->trans("Event") : $langs->trans("Events")); if (count($cases2[$h]) > 1) {
$title2 .= count($cases2[$h]).' '.(count($cases2[$h]) == 1 ? $langs->trans("Event") : $langs->trans("Events"));
}
$string2 = '&nbsp;'; $string2 = '&nbsp;';
if (empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) $style2 = 'peruser_notbusy'; if (empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) {
else $style2 = 'peruser_busy'; $style2 = 'peruser_notbusy';
foreach ($cases2[$h] as $id => $ev) } else {
{ $style2 = 'peruser_busy';
if ($ev['busy']) $style2 = 'peruser_busy'; }
foreach ($cases2[$h] as $id => $ev) {
if ($ev['busy']) {
$style2 = 'peruser_busy';
}
} }
} }
$ids1 = ''; $ids2 = ''; $ids1 = ''; $ids2 = '';
if (count($cases1[$h]) && array_keys($cases1[$h])) $ids1 = join(',', array_keys($cases1[$h])); if (count($cases1[$h]) && array_keys($cases1[$h])) {
if (count($cases2[$h]) && array_keys($cases2[$h])) $ids2 = join(',', array_keys($cases2[$h])); $ids1 = join(',', array_keys($cases1[$h]));
}
if (count($cases2[$h]) && array_keys($cases2[$h])) {
$ids2 = join(',', array_keys($cases2[$h]));
}
if ($h == $begin_h) echo '<td class="'.$style.'_peruserleft cal_peruser'.($var ? ' cal_impair '.$style.'_impair' : '').'">'; if ($h == $begin_h) {
else echo '<td class="'.$style.' cal_peruser'.($var ? ' cal_impair '.$style.'_impair' : '').'">'; echo '<td class="'.$style.'_peruserleft cal_peruser'.($var ? ' cal_impair '.$style.'_impair' : '').'">';
if (count($cases1[$h]) == 1) // only 1 event } else {
{ echo '<td class="'.$style.' cal_peruser'.($var ? ' cal_impair '.$style.'_impair' : '').'">';
}
if (count($cases1[$h]) == 1) { // only 1 event
$output = array_slice($cases1[$h], 0, 1); $output = array_slice($cases1[$h], 0, 1);
$title1 = $langs->trans("Ref").' '.$ids1.($title1 ? ' - '.$title1 : ''); $title1 = $langs->trans("Ref").' '.$ids1.($title1 ? ' - '.$title1 : '');
if ($output[0]['string']) $title1 .= ($title1 ? ' - ' : '').$output[0]['string']; if ($output[0]['string']) {
if ($output[0]['color']) $color1 = $output[0]['color']; $title1 .= ($title1 ? ' - ' : '').$output[0]['string'];
} elseif (count($cases1[$h]) > 1) }
{ if ($output[0]['color']) {
$color1 = $output[0]['color'];
}
} elseif (count($cases1[$h]) > 1) {
$title1 = $langs->trans("Ref").' '.$ids1.($title1 ? ' - '.$title1 : ''); $title1 = $langs->trans("Ref").' '.$ids1.($title1 ? ' - '.$title1 : '');
$color1 = '222222'; $color1 = '222222';
} }
if (count($cases2[$h]) == 1) // only 1 event if (count($cases2[$h]) == 1) { // only 1 event
{
$output = array_slice($cases2[$h], 0, 1); $output = array_slice($cases2[$h], 0, 1);
$title2 = $langs->trans("Ref").' '.$ids2.($title2 ? ' - '.$title2 : ''); $title2 = $langs->trans("Ref").' '.$ids2.($title2 ? ' - '.$title2 : '');
if ($output[0]['string']) $title2 .= ($title2 ? ' - ' : '').$output[0]['string']; if ($output[0]['string']) {
if ($output[0]['color']) $color2 = $output[0]['color']; $title2 .= ($title2 ? ' - ' : '').$output[0]['string'];
} elseif (count($cases2[$h]) > 1) }
{ if ($output[0]['color']) {
$color2 = $output[0]['color'];
}
} elseif (count($cases2[$h]) > 1) {
$title2 = $langs->trans("Ref").' '.$ids2.($title2 ? ' - '.$title2 : ''); $title2 = $langs->trans("Ref").' '.$ids2.($title2 ? ' - '.$title2 : '');
$color2 = '222222'; $color2 = '222222';
} }

File diff suppressed because it is too large Load Diff

View File

@ -42,14 +42,22 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if ($page == -1 || $page == null) { $page = 0; } if ($page == -1 || $page == null) {
$page = 0;
}
$offset = $limit * $page; $offset = $limit * $page;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "a.datep"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "a.datep";
}
// Security check // Security check
$socid = GETPOST('socid', 'int'); $socid = GETPOST('socid', 'int');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'agenda', $socid, '', 'myactions'); $result = restrictedArea($user, 'agenda', $socid, '', 'myactions');
@ -57,12 +65,10 @@ $result = restrictedArea($user, 'agenda', $socid, '', 'myactions');
* Actions * Actions
*/ */
if ($action == 'builddoc') if ($action == 'builddoc') {
{
$cat = new CommActionRapport($db, $month, $year); $cat = new CommActionRapport($db, $month, $year);
$result = $cat->write_file(GETPOST('id', 'int')); $result = $cat->write_file(GETPOST('id', 'int'));
if ($result < 0) if ($result < 0) {
{
setEventMessages($cat->error, $cat->errors, 'errors'); setEventMessages($cat->error, $cat->errors, 'errors');
} }
} }
@ -89,12 +95,10 @@ $sql .= " GROUP BY year, month, df";
$sql .= " ORDER BY year DESC, month DESC, df DESC"; $sql .= " ORDER BY year DESC, month DESC, df DESC";
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@ -105,15 +109,18 @@ $sql .= $db->plimit($limit + 1, $offset);
//print $sql; //print $sql;
dol_syslog("select", LOG_DEBUG); dol_syslog("select", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$param = ''; $param = '';
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.$limit;
}
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -137,12 +144,10 @@ if ($resql)
print '<td class="center">'.$langs->trans("Size").'</td>'; print '<td class="center">'.$langs->trans("Size").'</td>';
print "</tr>\n"; print "</tr>\n";
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj) if ($obj) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// Date // Date
@ -161,10 +166,11 @@ if ($resql)
$file = $conf->agenda->dir_temp."/".$name; $file = $conf->agenda->dir_temp."/".$name;
$modulepart = 'actionsreport'; $modulepart = 'actionsreport';
$documenturl = DOL_URL_ROOT.'/document.php'; $documenturl = DOL_URL_ROOT.'/document.php';
if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl = $conf->global->DOL_URL_ROOT_DOCUMENT_PHP; // To use another wrapper if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) {
$documenturl = $conf->global->DOL_URL_ROOT_DOCUMENT_PHP; // To use another wrapper
}
if (file_exists($file)) if (file_exists($file)) {
{
print '<td class="tdoverflowmax300">'; print '<td class="tdoverflowmax300">';
//print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?page='.$page.'&amp;file='.urlencode($relativepath).'&amp;modulepart=actionsreport">'.img_pdf().'</a>'; //print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?page='.$page.'&amp;file='.urlencode($relativepath).'&amp;modulepart=actionsreport">'.img_pdf().'</a>';
@ -174,7 +180,9 @@ if ($resql)
// Show file name with link to download // Show file name with link to download
$out .= '<a href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param ? '&'.$param : '').'"'; $out .= '<a href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param ? '&'.$param : '').'"';
$mime = dol_mimetype($relativepath, '', 0); $mime = dol_mimetype($relativepath, '', 0);
if (preg_match('/text/', $mime)) $out .= ' target="_blank"'; if (preg_match('/text/', $mime)) {
$out .= ' target="_blank"';
}
$out .= ' target="_blank">'; $out .= ' target="_blank">';
$out .= img_mime($filearray["name"], $langs->trans("File").': '.$filearray["name"]); $out .= img_mime($filearray["name"], $langs->trans("File").': '.$filearray["name"]);
$out .= $filearray["name"]; $out .= $filearray["name"];

View File

@ -37,13 +37,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'propal'; //Must be the $table_element of the class that manage extrafield $elementtype = 'propal'; //Must be the $table_element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -76,8 +80,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("NewAttribute").'</a></div>'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("NewAttribute").'</a></div>';
print "</div>"; print "</div>";
@ -90,8 +93,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -103,8 +105,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -32,8 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadlangs(array('admin', 'other', 'propal')); $langs->loadlangs(array('admin', 'other', 'propal'));
@ -44,14 +45,18 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'propaldet'; //Must be the $table_element of the class that manage extrafield $elementtype = 'propaldet'; //Must be the $table_element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -83,8 +88,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -97,8 +101,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -110,8 +113,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -144,7 +144,6 @@ if ($id > 0 && empty($object->id)) {
} }
/* /*
* Actions * Actions
*/ */
@ -341,7 +340,7 @@ if ($object->id > 0) {
print '<tr><td>'; print '<tr><td>';
print $langs->trans('CustomerCode').'</td><td>'; print $langs->trans('CustomerCode').'</td><td>';
print $object->code_client; print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client));
$tmpcheck = $object->check_codeclient(); $tmpcheck = $object->check_codeclient();
if ($tmpcheck != 0 && $tmpcheck != -5) { if ($tmpcheck != 0 && $tmpcheck != -5) {
print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
@ -534,7 +533,7 @@ if ($object->id > 0) {
print '</tr>'; print '</tr>';
} }
// Warehouse // Warehouse
if (!empty($conf->stock->enabled)) { if (!empty($conf->stock->enabled) && !empty($conf->global->SOCIETE_ASK_FOR_WAREHOUSE)) {
$langs->load('stocks'); $langs->load('stocks');
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);

View File

@ -32,9 +32,15 @@ $langs->load("companies");
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "p.name"; $sortorder = "ASC";
if ($page < 0) { $page = 0; } }
if (!$sortfield) {
$sortfield = "p.name";
}
if ($page < 0) {
$page = 0;
}
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$offset = $limit * $page; $offset = $limit * $page;
@ -47,7 +53,9 @@ $begin = GETPOST('begin', 'alpha');
// Security check // Security check
$socid = GETPOST('socid', 'int'); $socid = GETPOST('socid', 'int');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'societe', $socid, ''); $result = restrictedArea($user, 'societe', $socid, '');
@ -57,13 +65,11 @@ $result = restrictedArea($user, 'societe', $socid, '');
llxHeader('', $langs->trans("Contacts")); llxHeader('', $langs->trans("Contacts"));
if ($type == "c" || $type == "p") if ($type == "c" || $type == "p") {
{
$label = $langs->trans("Customers"); $label = $langs->trans("Customers");
$urlfiche = "card.php"; $urlfiche = "card.php";
} }
if ($type == "f") if ($type == "f") {
{
$label = $langs->trans("Suppliers"); $label = $langs->trans("Suppliers");
$urlfiche = "card.php"; $urlfiche = "card.php";
} }
@ -75,39 +81,46 @@ if ($type == "f")
$sql = "SELECT s.rowid, s.nom as name, st.libelle as stcomm"; $sql = "SELECT s.rowid, s.nom as name, st.libelle as stcomm";
$sql .= ", p.rowid as cidp, p.name, p.firstname, p.email, p.phone"; $sql .= ", p.rowid as cidp, p.name, p.firstname, p.email, p.phone";
$sql .= " FROM ".MAIN_DB_PREFIX."c_stcomm as st,"; $sql .= " FROM ".MAIN_DB_PREFIX."c_stcomm as st,";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,";
}
$sql .= " ".MAIN_DB_PREFIX."socpeople as p"; $sql .= " ".MAIN_DB_PREFIX."socpeople as p";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
$sql .= " WHERE s.fk_stcomm = st.id"; $sql .= " WHERE s.fk_stcomm = st.id";
$sql .= " AND p.entity IN (".getEntity('socpeople').")"; $sql .= " AND p.entity IN (".getEntity('socpeople').")";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($type == "c") $sql .= " AND s.client IN (1, 3)"; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
if ($type == "p") $sql .= " AND s.client IN (2, 3)"; }
if ($type == "f") $sql .= " AND s.fournisseur = 1"; if ($type == "c") {
if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " AND s.client IN (1, 3)";
}
if ($type == "p") {
$sql .= " AND s.client IN (2, 3)";
}
if ($type == "f") {
$sql .= " AND s.fournisseur = 1";
}
if ($socid) {
$sql .= " AND s.rowid = ".$socid;
}
if (dol_strlen($stcomm)) if (dol_strlen($stcomm)) {
{
$sql .= " AND s.fk_stcomm=".$db->escape($stcomm); $sql .= " AND s.fk_stcomm=".$db->escape($stcomm);
} }
if (!empty($search_lastname)) if (!empty($search_lastname)) {
{
$sql .= " AND p.name LIKE '%".$db->escape($search_lastname)."%'"; $sql .= " AND p.name LIKE '%".$db->escape($search_lastname)."%'";
} }
if (!empty($search_firstname)) if (!empty($search_firstname)) {
{
$sql .= " AND p.firstname LIKE '%".$db->escape($search_firstname)."%'"; $sql .= " AND p.firstname LIKE '%".$db->escape($search_firstname)."%'";
} }
if (!empty($search_company)) if (!empty($search_company)) {
{
$sql .= " AND s.nom LIKE '%".$db->escape($search_company)."%'"; $sql .= " AND s.nom LIKE '%".$db->escape($search_company)."%'";
} }
if (!empty($contactname)) // acces a partir du module de recherche if (!empty($contactname)) { // acces a partir du module de recherche
{
$sql .= " AND (p.name LIKE '%".$db->escape($contactname)."%' OR lower(p.firstname) LIKE '%".$db->escape($contactname)."%') "; $sql .= " AND (p.name LIKE '%".$db->escape($contactname)."%' OR lower(p.firstname) LIKE '%".$db->escape($contactname)."%') ";
$sortfield = "p.name"; $sortfield = "p.name";
$sortorder = "ASC"; $sortorder = "ASC";
@ -117,8 +130,7 @@ $sql .= $db->order($sortfield, $sortorder);
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$param = "&type=".$type; $param = "&type=".$type;
@ -146,8 +158,7 @@ if ($resql)
print "</tr>\n"; print "</tr>\n";
$i = 0; $i = 0;
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';

View File

@ -687,8 +687,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU
$obj = $companystatic; $obj = $companystatic;
$s = ''; $s = '';
/*if (($obj->client == 2 || $obj->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) /*if (($obj->client == 2 || $obj->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
{
$s .= '<a class="customer-back opacitymedium" title="'.$langs->trans("Prospect").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$companystatic->id.'">'.dol_substr($langs->trans("Prospect"), 0, 1).'</a>'; $s .= '<a class="customer-back opacitymedium" title="'.$langs->trans("Prospect").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$companystatic->id.'">'.dol_substr($langs->trans("Prospect"), 0, 1).'</a>';
} }
if (($obj->client == 1 || $obj->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) if (($obj->client == 1 || $obj->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))

View File

@ -22,7 +22,9 @@
* \brief Page to define emailing targets * \brief Page to define emailing targets
*/ */
if (!defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); if (!defined('NOSTYLECHECK')) {
define('NOSTYLECHECK', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
@ -41,22 +43,27 @@ if (!empty($conf->categorie->enabled)) {
} }
// Security check // Security check
if (!$user->rights->mailing->lire || $user->socid > 0) if (!$user->rights->mailing->lire || $user->socid > 0) {
accessforbidden(); accessforbidden();
}
// Load variable for pagination // Load variable for pagination
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) if (!$sortorder) {
$sortorder = "ASC"; $sortorder = "ASC";
if (!$sortfield) }
if (!$sortfield) {
$sortfield = "email"; $sortfield = "email";
}
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$rowid = GETPOST('rowid', 'int'); $rowid = GETPOST('rowid', 'int');
@ -84,8 +91,7 @@ if (empty($template_id)) {
$result = $advTarget->fetch($template_id); $result = $advTarget->fetch($template_id);
} }
if ($result < 0) if ($result < 0) {
{
setEventMessages($advTarget->error, $advTarget->errors, 'errors'); setEventMessages($advTarget->error, $advTarget->errors, 'errors');
} else { } else {
if (!empty($advTarget->id)) { if (!empty($advTarget->id)) {
@ -397,16 +403,12 @@ if ($_POST["button_removefilter"]) {
$search_email = ''; $search_email = '';
} }
/* /*
* View * View
*/ */
llxHeader('', $langs->trans("MailAdvTargetRecipients")); llxHeader('', $langs->trans("MailAdvTargetRecipients"));
$form = new Form($db); $form = new Form($db);
$formadvtargetemaling = new FormAdvTargetEmailing($db); $formadvtargetemaling = new FormAdvTargetEmailing($db);
$formcompany = new FormCompany($db); $formcompany = new FormCompany($db);

View File

@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$langs->load("mails"); $langs->load("mails");
// Security check // Security check
if (!$user->rights->mailing->lire || $user->socid > 0) accessforbidden(); if (!$user->rights->mailing->lire || $user->socid > 0) {
accessforbidden();
}
// Load variable for pagination // Load variable for pagination
@ -44,12 +46,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = "mc.statut,email"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC,ASC"; $sortfield = "mc.statut,email";
}
if (!$sortorder) {
$sortorder = "DESC,ASC";
}
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$rowid = GETPOST('rowid', 'int'); $rowid = GETPOST('rowid', 'int');
@ -71,13 +79,11 @@ $result = $object->fetch($id);
* Actions * Actions
*/ */
if ($action == 'add') if ($action == 'add') {
{
$module = GETPOST("module", 'alpha'); $module = GETPOST("module", 'alpha');
$result = -1; $result = -1;
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
// Load modules attributes in arrays (name, numero, orders) from dir directory // Load modules attributes in arrays (name, numero, orders) from dir directory
//print $dir."\n<br>"; //print $dir."\n<br>";
dol_syslog("Scan directory ".$dir." for modules"); dol_syslog("Scan directory ".$dir." for modules");
@ -86,8 +92,7 @@ if ($action == 'add')
$file = $dir."/".$module.".modules.php"; $file = $dir."/".$module.".modules.php";
$classname = "mailing_".$module; $classname = "mailing_".$module;
if (file_exists($file)) if (file_exists($file)) {
{
require_once $file; require_once $file;
// Add targets into database // Add targets into database
@ -96,25 +101,21 @@ if ($action == 'add')
$result = $obj->add_to_target($id); $result = $obj->add_to_target($id);
} }
} }
if ($result > 0) if ($result > 0) {
{
setEventMessages($langs->trans("XTargetsAdded", $result), null, 'mesgs'); setEventMessages($langs->trans("XTargetsAdded", $result), null, 'mesgs');
header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
exit; exit;
} }
if ($result == 0) if ($result == 0) {
{
setEventMessages($langs->trans("WarningNoEMailsAdded"), null, 'warnings'); setEventMessages($langs->trans("WarningNoEMailsAdded"), null, 'warnings');
} }
if ($result < 0) if ($result < 0) {
{
setEventMessages($langs->trans("Error").($obj->error ? ' '.$obj->error : ''), null, 'errors'); setEventMessages($langs->trans("Error").($obj->error ? ' '.$obj->error : ''), null, 'errors');
} }
} }
if (GETPOST('clearlist', 'int')) if (GETPOST('clearlist', 'int')) {
{
// Loading Class // Loading Class
$obj = new MailingTargets($db); $obj = new MailingTargets($db);
$obj->clear_target($id); $obj->clear_target($id);
@ -124,8 +125,7 @@ if (GETPOST('clearlist', 'int'))
*/ */
} }
if (GETPOST('exportcsv', 'int')) if (GETPOST('exportcsv', 'int')) {
{
$completefilename = 'targets_emailing'.$object->id.'_'.dol_print_date(dol_now(), 'dayhourlog').'.csv'; $completefilename = 'targets_emailing'.$object->id.'_'.dol_print_date(dol_now(), 'dayhourlog').'.csv';
header('Content-Type: text/csv'); header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename='.$completefilename); header('Content-Disposition: attachment;filename='.$completefilename);
@ -138,13 +138,11 @@ if (GETPOST('exportcsv', 'int'))
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$sep = ','; $sep = ',';
while ($obj = $db->fetch_object($resql)) while ($obj = $db->fetch_object($resql)) {
{
print $obj->rowid.$sep; print $obj->rowid.$sep;
print '"'.$obj->lastname.'"'.$sep; print '"'.$obj->lastname.'"'.$sep;
print '"'.$obj->firstname.'"'.$sep; print '"'.$obj->firstname.'"'.$sep;
@ -166,15 +164,12 @@ if (GETPOST('exportcsv', 'int'))
exit; exit;
} }
if ($action == 'delete') if ($action == 'delete') {
{
// Ici, rowid indique le destinataire et id le mailing // Ici, rowid indique le destinataire et id le mailing
$sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$rowid; $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$rowid;
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ if (!empty($id)) {
if (!empty($id))
{
$obj = new MailingTargets($db); $obj = new MailingTargets($db);
$obj->update_nb($id); $obj->update_nb($id);
@ -189,8 +184,7 @@ if ($action == 'delete')
} }
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$search_lastname = ''; $search_lastname = '';
$search_firstname = ''; $search_firstname = '';
$search_email = ''; $search_email = '';
@ -209,8 +203,7 @@ llxHeader('', $langs->trans("Mailing"), 'EN:Module_EMailing|FR:Module_Mailing|ES
$form = new Form($db); $form = new Form($db);
$formmailing = new FormMailing($db); $formmailing = new FormMailing($db);
if ($object->fetch($id) >= 0) if ($object->fetch($id) >= 0) {
{
$head = emailing_prepare_head($object); $head = emailing_prepare_head($object);
print dol_get_fiche_head($head, 'targets', $langs->trans("Mailing"), -1, 'email'); print dol_get_fiche_head($head, 'targets', $langs->trans("Mailing"), -1, 'email');
@ -219,14 +212,15 @@ if ($object->fetch($id) >= 0)
$morehtmlright = ''; $morehtmlright = '';
$nbtry = $nbok = 0; $nbtry = $nbok = 0;
if ($object->statut == 2 || $object->statut == 3) if ($object->statut == 2 || $object->statut == 3) {
{
$nbtry = $object->countNbOfTargets('alreadysent'); $nbtry = $object->countNbOfTargets('alreadysent');
$nbko = $object->countNbOfTargets('alreadysentko'); $nbko = $object->countNbOfTargets('alreadysentko');
$nbok = ($nbtry - $nbko); $nbok = ($nbtry - $nbko);
$morehtmlright .= ' ('.$nbtry.'/'.$object->nbemail; $morehtmlright .= ' ('.$nbtry.'/'.$object->nbemail;
if ($nbko) $morehtmlright .= ' - '.$nbko.' '.$langs->trans("Error"); if ($nbko) {
$morehtmlright .= ' - '.$nbko.' '.$langs->trans("Error");
}
$morehtmlright .= ') &nbsp; '; $morehtmlright .= ') &nbsp; ';
} }
@ -279,21 +273,19 @@ if ($object->fetch($id) >= 0)
print $langs->trans("TotalNbOfDistinctRecipients"); print $langs->trans("TotalNbOfDistinctRecipients");
print '</td><td colspan="3">'; print '</td><td colspan="3">';
$nbemail = ($object->nbemail ? $object->nbemail : 0); $nbemail = ($object->nbemail ? $object->nbemail : 0);
if (is_numeric($nbemail)) if (is_numeric($nbemail)) {
{
$text = ''; $text = '';
if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) {
{ if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) {
if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0)
{
$text .= $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); $text .= $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB);
} else { } else {
$text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed'); $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed');
} }
} }
if (empty($nbemail)) $nbemail .= ' '.img_warning('').' <font class="warning">'.$langs->trans("NoTargetYet").'</font>'; if (empty($nbemail)) {
if ($text) $nbemail .= ' '.img_warning('').' <font class="warning">'.$langs->trans("NoTargetYet").'</font>';
{ }
if ($text) {
print $form->textwithpicto($nbemail, $text, 1, 'warning'); print $form->textwithpicto($nbemail, $text, 1, 'warning');
} else { } else {
print $nbemail; print $nbemail;
@ -313,8 +305,7 @@ if ($object->fetch($id) >= 0)
$allowaddtarget = ($object->statut == 0); $allowaddtarget = ($object->statut == 0);
// Show email selectors // Show email selectors
if ($allowaddtarget && $user->rights->mailing->creer) if ($allowaddtarget && $user->rights->mailing->creer) {
{
print load_fiche_titre($langs->trans("ToAddRecipientsChooseHere"), ($user->admin ?info_admin($langs->trans("YouCanAddYourOwnPredefindedListHere"), 1) : ''), 'generic'); print load_fiche_titre($langs->trans("ToAddRecipientsChooseHere"), ($user->admin ?info_admin($langs->trans("YouCanAddYourOwnPredefindedListHere"), 1) : ''), 'generic');
//print '<table class="noborder centpercent">'; //print '<table class="noborder centpercent">';
@ -335,23 +326,20 @@ if ($object->fetch($id) >= 0)
clearstatcache(); clearstatcache();
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
$modulenames = array(); $modulenames = array();
// Load modules attributes in arrays (name, numero, orders) from dir directory // Load modules attributes in arrays (name, numero, orders) from dir directory
//print $dir."\n<br>"; //print $dir."\n<br>";
dol_syslog("Scan directory ".$dir." for modules"); dol_syslog("Scan directory ".$dir." for modules");
$handle = @opendir($dir); $handle = @opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') {
{ if (preg_match("/(.*)\.modules\.php$/i", $file, $reg)) {
if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') if ($reg[1] == 'example') {
{ continue;
if (preg_match("/(.*)\.modules\.php$/i", $file, $reg)) }
{
if ($reg[1] == 'example') continue;
$modulenames[] = $reg[1]; $modulenames[] = $reg[1];
} }
} }
@ -365,8 +353,7 @@ if ($object->fetch($id) >= 0)
$var = true; $var = true;
// Loop on each submodule // Loop on each submodule
foreach ($modulenames as $modulename) foreach ($modulenames as $modulename) {
{
// Loading Class // Loading Class
$file = $dir.$modulename.".modules.php"; $file = $dir.$modulename.".modules.php";
$classname = "mailing_".$modulename; $classname = "mailing_".$modulename;
@ -376,10 +363,8 @@ if ($object->fetch($id) >= 0)
// Check dependencies // Check dependencies
$qualified = (isset($obj->enabled) ? $obj->enabled : 1); $qualified = (isset($obj->enabled) ? $obj->enabled : 1);
foreach ($obj->require_module as $key) foreach ($obj->require_module as $key) {
{ if (!$conf->$key->enabled || (!$user->admin && $obj->require_admin)) {
if (!$conf->$key->enabled || (!$user->admin && $obj->require_admin))
{
$qualified = 0; $qualified = 0;
//print "Les prerequis d'activation du module mailing ne sont pas respectes. Il ne sera pas actif"; //print "Les prerequis d'activation du module mailing ne sont pas respectes. Il ne sera pas actif";
break; break;
@ -387,12 +372,10 @@ if ($object->fetch($id) >= 0)
} }
// Si le module mailing est qualifie // Si le module mailing est qualifie
if ($qualified) if ($qualified) {
{
$var = !$var; $var = !$var;
if ($allowaddtarget) if ($allowaddtarget) {
{
print '<form '.$bctag[$var].' name="'.$modulename.'" action="'.$_SERVER['PHP_SELF'].'?action=add&id='.$object->id.'&module='.$modulename.'" method="POST" enctype="multipart/form-data">'; print '<form '.$bctag[$var].' name="'.$modulename.'" action="'.$_SERVER['PHP_SELF'].'?action=add&id='.$object->id.'&module='.$modulename.'" method="POST" enctype="multipart/form-data">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
} else { } else {
@ -400,7 +383,9 @@ if ($object->fetch($id) >= 0)
} }
print '<div class="tagtd">'; print '<div class="tagtd">';
if (empty($obj->picto)) $obj->picto = 'generic'; if (empty($obj->picto)) {
$obj->picto = 'generic';
}
print img_object($langs->trans("EmailingTargetSelector").': '.get_class($obj), $obj->picto, 'class="valignmiddle pictomodule"'); print img_object($langs->trans("EmailingTargetSelector").': '.get_class($obj), $obj->picto, 'class="valignmiddle pictomodule"');
print ' '; print ' ';
print $obj->getDesc(); print $obj->getDesc();
@ -408,14 +393,12 @@ if ($object->fetch($id) >= 0)
try { try {
$nbofrecipient = $obj->getNbOfRecipients(''); $nbofrecipient = $obj->getNbOfRecipients('');
} catch (Exception $e) } catch (Exception $e) {
{
dol_syslog($e->getMessage(), LOG_ERR); dol_syslog($e->getMessage(), LOG_ERR);
} }
print '<div class="tagtd center">'; print '<div class="tagtd center">';
if ($nbofrecipient >= 0) if ($nbofrecipient >= 0) {
{
print $nbofrecipient; print $nbofrecipient;
} else { } else {
print $langs->trans("Error").' '.img_error($obj->error); print $langs->trans("Error").' '.img_error($obj->error);
@ -423,22 +406,22 @@ if ($object->fetch($id) >= 0)
print '</div>'; print '</div>';
print '<div class="tagtd left">'; print '<div class="tagtd left">';
if ($allowaddtarget) if ($allowaddtarget) {
{
try { try {
$filter = $obj->formFilter(); $filter = $obj->formFilter();
} catch (Exception $e) } catch (Exception $e) {
{
dol_syslog($e->getMessage(), LOG_ERR); dol_syslog($e->getMessage(), LOG_ERR);
} }
if ($filter) print $filter; if ($filter) {
else print $langs->trans("None"); print $filter;
} else {
print $langs->trans("None");
}
} }
print '</div>'; print '</div>';
print '<div class="tagtd right">'; print '<div class="tagtd right">';
if ($allowaddtarget) if ($allowaddtarget) {
{
print '<input type="submit" class="button" name="button_'.$modulename.'" value="'.$langs->trans("Add").'">'; print '<input type="submit" class="button" name="button_'.$modulename.'" value="'.$langs->trans("Add").'">';
} else { } else {
print '<input type="submit" class="button disabled" disabled="disabled" name="button_'.$modulename.'" value="'.$langs->trans("Add").'">'; print '<input type="submit" class="button disabled" disabled="disabled" name="button_'.$modulename.'" value="'.$langs->trans("Add").'">';
@ -447,8 +430,11 @@ if ($object->fetch($id) >= 0)
} }
print '</div>'; print '</div>';
if ($allowaddtarget) print '</form>'; if ($allowaddtarget) {
else print '</div>'; print '</form>';
} else {
print '</div>';
}
} }
} }
} // End foreach dir } // End foreach dir
@ -488,8 +474,7 @@ if ($object->fetch($id) >= 0)
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
@ -514,17 +499,26 @@ if ($object->fetch($id) >= 0)
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$param = "&id=".$object->id; $param = "&id=".$object->id;
//if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); //if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_lastname) $param .= "&search_lastname=".urlencode($search_lastname); $param .= '&limit='.urlencode($limit);
if ($search_firstname) $param .= "&search_firstname=".urlencode($search_firstname); }
if ($search_email) $param .= "&search_email=".urlencode($search_email); if ($search_lastname) {
if ($search_other) $param .= "&search_other=".urlencode($search_other); $param .= "&search_lastname=".urlencode($search_lastname);
}
if ($search_firstname) {
$param .= "&search_firstname=".urlencode($search_firstname);
}
if ($search_email) {
$param .= "&search_email=".urlencode($search_email);
}
if ($search_other) {
$param .= "&search_other=".urlencode($search_other);
}
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -599,7 +593,9 @@ if ($object->fetch($id) >= 0)
print '</td>'; print '</td>';
print '</tr>'; print '</tr>';
if ($page) $param .= "&page=".urlencode($page); if ($page) {
$param .= "&page=".urlencode($page);
}
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print_liste_field_titre("EMail", $_SERVER["PHP_SELF"], "mc.email", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("EMail", $_SERVER["PHP_SELF"], "mc.email", $param, "", "", $sortfield, $sortorder);
@ -617,8 +613,7 @@ if ($object->fetch($id) >= 0)
$i = 0; $i = 0;
if ($num) if ($num) {
{
include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
@ -628,8 +623,7 @@ if ($object->fetch($id) >= 0)
$objectstaticcompany = new Societe($db); $objectstaticcompany = new Societe($db);
$objectstaticcontact = new Contact($db); $objectstaticcontact = new Contact($db);
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
@ -638,24 +632,19 @@ if ($object->fetch($id) >= 0)
print '<td>'.$obj->firstname.'</td>'; print '<td>'.$obj->firstname.'</td>';
print '<td>'.$obj->other.'</td>'; print '<td>'.$obj->other.'</td>';
print '<td class="center">'; print '<td class="center">';
if (empty($obj->source_id) || empty($obj->source_type)) if (empty($obj->source_id) || empty($obj->source_type)) {
{
print empty($obj->source_url) ? '' : $obj->source_url; // For backward compatibility print empty($obj->source_url) ? '' : $obj->source_url; // For backward compatibility
} else { } else {
if ($obj->source_type == 'member') if ($obj->source_type == 'member') {
{
$objectstaticmember->fetch($obj->source_id); $objectstaticmember->fetch($obj->source_id);
print $objectstaticmember->getNomUrl(1); print $objectstaticmember->getNomUrl(1);
} elseif ($obj->source_type == 'user') } elseif ($obj->source_type == 'user') {
{
$objectstaticuser->fetch($obj->source_id); $objectstaticuser->fetch($obj->source_id);
print $objectstaticuser->getNomUrl(1); print $objectstaticuser->getNomUrl(1);
} elseif ($obj->source_type == 'thirdparty') } elseif ($obj->source_type == 'thirdparty') {
{
$objectstaticcompany->fetch($obj->source_id); $objectstaticcompany->fetch($obj->source_id);
print $objectstaticcompany->getNomUrl(1); print $objectstaticcompany->getNomUrl(1);
} elseif ($obj->source_type == 'contact') } elseif ($obj->source_type == 'contact') {
{
$objectstaticcontact->fetch($obj->source_id); $objectstaticcontact->fetch($obj->source_id);
print $objectstaticcontact->getNomUrl(1); print $objectstaticcontact->getNomUrl(1);
} else { } else {
@ -670,8 +659,7 @@ if ($object->fetch($id) >= 0)
print '</td>'; print '</td>';
// Status of recipient sending email (Warning != status of emailing) // Status of recipient sending email (Warning != status of emailing)
if ($obj->statut == 0) if ($obj->statut == 0) {
{
// Date sent // Date sent
print '<td align="center">&nbsp;</td>'; print '<td align="center">&nbsp;</td>';
@ -689,8 +677,7 @@ if ($object->fetch($id) >= 0)
// Search Icon // Search Icon
print '<td class="right">'; print '<td class="right">';
if ($obj->statut == 0) // Not sent yet if ($obj->statut == 0) { // Not sent yet
{
if ($user->rights->mailing->creer && $allowaddtarget) { if ($user->rights->mailing->creer && $allowaddtarget) {
print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=delete&token='.newToken().'&rowid='.$obj->rowid.$param.'">'.img_delete($langs->trans("RemoveRecipient")).'</a>'; print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=delete&token='.newToken().'&rowid='.$obj->rowid.$param.'">'.img_delete($langs->trans("RemoveRecipient")).'</a>';
} }
@ -705,8 +692,7 @@ if ($object->fetch($id) >= 0)
$i++; $i++;
} }
} else { } else {
if ($object->statut < 2) if ($object->statut < 2) {
{
print '<tr><td colspan="9" class="opacitymedium">'; print '<tr><td colspan="9" class="opacitymedium">';
print $langs->trans("NoTargetYet"); print $langs->trans("NoTargetYet");
print '</td></tr>'; print '</td></tr>';

View File

@ -74,8 +74,9 @@ class FormAdvTargetEmailing extends Form
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$level = $langs->trans($obj->code); $level = $langs->trans($obj->code);
if ($level == $obj->code) if ($level == $obj->code) {
$level = $langs->trans($obj->label); $level = $langs->trans($obj->label);
}
$options_array[$obj->code] = $level; $options_array[$obj->code] = $level;
$i++; $i++;
@ -131,8 +132,9 @@ class FormAdvTargetEmailing extends Form
foreach ($countryArray as $row) { foreach ($countryArray as $row) {
$label = dol_trunc($row['label'], $maxlength, 'middle'); $label = dol_trunc($row['label'], $maxlength, 'middle');
if ($row['code_iso']) if ($row['code_iso']) {
$label .= ' ('.$row['code_iso'].')'; $label .= ' ('.$row['code_iso'].')';
}
$options_array[$row['rowid']] = $label; $options_array[$row['rowid']] = $label;
} }
@ -165,8 +167,9 @@ class FormAdvTargetEmailing extends Form
$sql_usr .= " WHERE u2.entity IN (0,".$conf->entity.")"; $sql_usr .= " WHERE u2.entity IN (0,".$conf->entity.")";
$sql_usr .= " AND u2.rowid = sc.fk_user "; $sql_usr .= " AND u2.rowid = sc.fk_user ";
if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX)) if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX)) {
$sql_usr .= " AND u2.statut<>0 "; $sql_usr .= " AND u2.statut<>0 ";
}
$sql_usr .= " ORDER BY name ASC"; $sql_usr .= " ORDER BY name ASC";
// print $sql_usr;exit; // print $sql_usr;exit;
@ -201,8 +204,7 @@ class FormAdvTargetEmailing extends Form
$langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 12); $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 12);
foreach ($langs_available as $key => $value) foreach ($langs_available as $key => $value) {
{
$label = $value; $label = $value;
$options_array[$key] = $label; $options_array[$key] = $label;
} }
@ -223,8 +225,7 @@ class FormAdvTargetEmailing extends Form
{ {
$options_array = array(); $options_array = array();
if (is_array($sqlqueryparam)) if (is_array($sqlqueryparam)) {
{
$param_list = array_keys($sqlqueryparam); $param_list = array_keys($sqlqueryparam);
$InfoFieldList = explode(":", $param_list [0]); $InfoFieldList = explode(":", $param_list [0]);
@ -297,14 +298,11 @@ class FormAdvTargetEmailing extends Form
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num)
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
$label = ($langs->trans("Civility".$obj->code) != "Civility".$obj->code ? $langs->trans("Civility".$obj->code) : ($obj->civilite != '-' ? $obj->civilite : '')); $label = ($langs->trans("Civility".$obj->code) != "Civility".$obj->code ? $langs->trans("Civility".$obj->code) : ($obj->civilite != '-' ? $obj->civilite : ''));
@ -364,8 +362,9 @@ class FormAdvTargetEmailing extends Form
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">'; $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
if ($showempty) if ($showempty) {
$out .= '<option value=""></option>'; $out .= '<option value=""></option>';
}
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
if ($num) { if ($num) {

View File

@ -80,16 +80,14 @@ print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("TargetsStatistic
$dir = DOL_DOCUMENT_ROOT."/core/modules/mailings"; $dir = DOL_DOCUMENT_ROOT."/core/modules/mailings";
$handle = opendir($dir); $handle = opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') {
{ if (preg_match("/(.*)\.(.*)\.(.*)/i", $file, $reg)) {
if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')
{
if (preg_match("/(.*)\.(.*)\.(.*)/i", $file, $reg))
{
$modulename = $reg[1]; $modulename = $reg[1];
if ($modulename == 'example') continue; if ($modulename == 'example') {
continue;
}
// Loading Class // Loading Class
$file = $dir."/".$modulename.".modules.php"; $file = $dir."/".$modulename.".modules.php";
@ -98,10 +96,8 @@ if (is_resource($handle))
$mailmodule = new $classname($db); $mailmodule = new $classname($db);
$qualified = 1; $qualified = 1;
foreach ($mailmodule->require_module as $key) foreach ($mailmodule->require_module as $key) {
{ if (!$conf->$key->enabled || (!$user->admin && $mailmodule->require_admin)) {
if (!$conf->$key->enabled || (!$user->admin && $mailmodule->require_admin))
{
$qualified = 0; $qualified = 0;
//print "Les pr<70>requis d'activation du module mailing ne sont pas respect<63>s. Il ne sera pas actif"; //print "Les pr<70>requis d'activation du module mailing ne sont pas respect<63>s. Il ne sera pas actif";
break; break;
@ -109,10 +105,8 @@ if (is_resource($handle))
} }
// Si le module mailing est qualifi<66> // Si le module mailing est qualifi<66>
if ($qualified) if ($qualified) {
{ foreach ($mailmodule->getSqlArrayForStats() as $sql) {
foreach ($mailmodule->getSqlArrayForStats() as $sql)
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
$result = $db->query($sql); $result = $db->query($sql);
@ -121,8 +115,7 @@ if (is_resource($handle))
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($result); $obj = $db->fetch_object($result);
print '<td>'.img_object('', $mailmodule->picto).' '.$obj->label.'</td><td class="right">'.$obj->nb.'<td>'; print '<td>'.img_object('', $mailmodule->picto).' '.$obj->label.'</td><td class="right">'.$obj->nb.'<td>';
$i++; $i++;
@ -169,12 +162,10 @@ if ($result) {
print '<td class="right"><a href="'.DOL_URL_ROOT.'/comm/mailing/list.php">'.$langs->trans("AllEMailings").'</a></td></tr>'; print '<td class="right"><a href="'.DOL_URL_ROOT.'/comm/mailing/list.php">'.$langs->trans("AllEMailings").'</a></td></tr>';
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($num > 0) if ($num > 0) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($result); $obj = $db->fetch_object($result);
$mailstatic = new Mailing($db); $mailstatic = new Mailing($db);
$mailstatic->id = $obj->rowid; $mailstatic->id = $obj->rowid;

View File

@ -77,7 +77,6 @@ if ($object->fetch($id) >= 0) {
dol_print_object_info($object, 0); dol_print_object_info($object, 0);
//print '</td></tr></table>'; //print '</td></tr></table>';
print dol_get_fiche_end(); print dol_get_fiche_end();
} }

View File

@ -36,12 +36,18 @@ $sortorder = GETPOST("sortorder", 'alpha');
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$optioncss = GETPOST('optioncss', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "m.date_creat"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "m.date_creat";
}
$search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
$search_ref = GETPOST("search_ref", "alpha") ? GETPOST("search_ref", "alpha") : GETPOST("sref", "alpha"); $search_ref = GETPOST("search_ref", "alpha") ? GETPOST("search_ref", "alpha") : GETPOST("sref", "alpha");
@ -70,21 +76,25 @@ $fieldstosearchall = array(
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
/*foreach($object->fields as $key => $val) /*foreach($object->fields as $key => $val)
{ {
$search[$key]=''; $search[$key]='';
@ -95,8 +105,7 @@ if (empty($reshook))
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@ -125,29 +134,43 @@ if ($filteremail) {
$sql .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc";
$sql .= " WHERE m.rowid = mc.fk_mailing AND m.entity = ".$conf->entity; $sql .= " WHERE m.rowid = mc.fk_mailing AND m.entity = ".$conf->entity;
$sql .= " AND mc.email = '".$db->escape($filteremail)."'"; $sql .= " AND mc.email = '".$db->escape($filteremail)."'";
if ($search_ref) $sql .= " AND m.rowid = '".$db->escape($search_ref)."'"; if ($search_ref) {
if ($search_all) $sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')"; $sql .= " AND m.rowid = '".$db->escape($search_ref)."'";
if (!$sortorder) $sortorder = "ASC"; }
if (!$sortfield) $sortfield = "m.rowid"; if ($search_all) {
$sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')";
}
if (!$sortorder) {
$sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "m.rowid";
}
} else { } else {
$sql = "SELECT m.rowid, m.titre as title, m.nbemail, m.statut, m.date_creat as datec, m.date_envoi as date_envoi"; $sql = "SELECT m.rowid, m.titre as title, m.nbemail, m.statut, m.date_creat as datec, m.date_envoi as date_envoi";
$sql .= " FROM ".MAIN_DB_PREFIX."mailing as m"; $sql .= " FROM ".MAIN_DB_PREFIX."mailing as m";
$sql .= " WHERE m.entity = ".$conf->entity; $sql .= " WHERE m.entity = ".$conf->entity;
if ($search_ref) $sql .= " AND m.rowid = '".$db->escape($search_ref)."'"; if ($search_ref) {
if ($search_all) $sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')"; $sql .= " AND m.rowid = '".$db->escape($search_ref)."'";
if (!$sortorder) $sortorder = "ASC"; }
if (!$sortfield) $sortfield = "m.rowid"; if ($search_all) {
$sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')";
}
if (!$sortorder) {
$sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "m.rowid";
}
} }
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@ -158,28 +181,36 @@ $sql .= $db->plimit($limit + 1, $offset);
dol_syslog("comm/mailing/list.php", LOG_DEBUG); dol_syslog("comm/mailing/list.php", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$title = $langs->trans("ListOfEMailings"); $title = $langs->trans("ListOfEMailings");
if ($filteremail) $title .= ' ('.$langs->trans("SentTo", $filteremail).')'; if ($filteremail) {
$title .= ' ('.$langs->trans("SentTo", $filteremail).')';
}
$newcardbutton = ''; $newcardbutton = '';
if ($user->rights->mailing->creer) if ($user->rights->mailing->creer) {
{
$newcardbutton .= dolGetButtonTitle($langs->trans('NewMailing'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/mailing/card.php?action=create'); $newcardbutton .= dolGetButtonTitle($langs->trans('NewMailing'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/mailing/card.php?action=create');
} }
$i = 0; $i = 0;
$param = "&search_all=".urlencode($search_all); $param = "&search_all=".urlencode($search_all);
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($filteremail) $param .= '&filteremail='.urlencode($filteremail); }
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
if ($filteremail) {
$param .= '&filteremail='.urlencode($filteremail);
}
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@ -201,7 +232,9 @@ if ($resql)
print '<input type="text" class="flat maxwidth100 maxwidth50onsmartphone" name="search_all" value="'.dol_escape_htmltag($search_all).'">'; print '<input type="text" class="flat maxwidth100 maxwidth50onsmartphone" name="search_all" value="'.dol_escape_htmltag($search_all).'">';
print '</td>'; print '</td>';
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
if (!$filteremail) print '<td class="liste_titre">&nbsp;</td>'; if (!$filteremail) {
print '<td class="liste_titre">&nbsp;</td>';
}
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
print '<td class="liste_titre maxwidthsearch">'; print '<td class="liste_titre maxwidthsearch">';
@ -214,9 +247,14 @@ if ($resql)
print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "m.rowid", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "m.rowid", $param, "", "", $sortfield, $sortorder);
print_liste_field_titre("Title", $_SERVER["PHP_SELF"], "m.titre", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Title", $_SERVER["PHP_SELF"], "m.titre", $param, "", "", $sortfield, $sortorder);
print_liste_field_titre("DateCreation", $_SERVER["PHP_SELF"], "m.date_creat", $param, "", 'align="center"', $sortfield, $sortorder); print_liste_field_titre("DateCreation", $_SERVER["PHP_SELF"], "m.date_creat", $param, "", 'align="center"', $sortfield, $sortorder);
if (!$filteremail) print_liste_field_titre("NbOfEMails", $_SERVER["PHP_SELF"], "m.nbemail", $param, "", 'align="center"', $sortfield, $sortorder); if (!$filteremail) {
if (!$filteremail) print_liste_field_titre("DateLastSend", $_SERVER["PHP_SELF"], "m.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder); print_liste_field_titre("NbOfEMails", $_SERVER["PHP_SELF"], "m.nbemail", $param, "", 'align="center"', $sortfield, $sortorder);
else print_liste_field_titre("DateSending", $_SERVER["PHP_SELF"], "mc.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder); }
if (!$filteremail) {
print_liste_field_titre("DateLastSend", $_SERVER["PHP_SELF"], "m.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder);
} else {
print_liste_field_titre("DateSending", $_SERVER["PHP_SELF"], "mc.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder);
}
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], ($filteremail ? "mc.statut" : "m.statut"), $param, "", 'class="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], ($filteremail ? "mc.statut" : "m.statut"), $param, "", 'class="right"', $sortfield, $sortorder);
print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', 'class="right"', $sortfield, $sortorder, 'maxwidthsearch '); print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', 'class="right"', $sortfield, $sortorder, 'maxwidthsearch ');
print "</tr>\n"; print "</tr>\n";
@ -224,8 +262,7 @@ if ($resql)
$email = new Mailing($db); $email = new Mailing($db);
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$email->id = $obj->rowid; $email->id = $obj->rowid;
@ -246,8 +283,7 @@ if ($resql)
print '</td>'; print '</td>';
// Nb of email // Nb of email
if (!$filteremail) if (!$filteremail) {
{
print '<td class="center">'; print '<td class="center">';
$nbemail = $obj->nbemail; $nbemail = $obj->nbemail;
/*if ($obj->statut != 3 && !empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) /*if ($obj->statut != 3 && !empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail)
@ -269,8 +305,7 @@ if ($resql)
// Status // Status
print '<td class="nowrap right">'; print '<td class="nowrap right">';
if ($filteremail) if ($filteremail) {
{
print $email::libStatutDest($obj->sendstatut, 2); print $email::libStatutDest($obj->sendstatut, 2);
} else { } else {
print $email->LibStatut($obj->statut, 5); print $email->LibStatut($obj->statut, 5);
@ -284,7 +319,9 @@ if ($resql)
} }
if (empty($num)) { if (empty($num)) {
$colspan = 6; $colspan = 6;
if (!$filteremail) $colspan++; if (!$filteremail) {
$colspan++;
}
print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }

View File

@ -33,8 +33,7 @@ $langs->loadLangs(array('orders', 'companies'));
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$_socid = GETPOST("id", 'int'); $_socid = GETPOST("id", 'int');
// Security check // Security check
if ($user->socid > 0) if ($user->socid > 0) {
{
$_socid = $user->socid; $_socid = $user->socid;
} }
@ -43,8 +42,7 @@ if ($user->socid > 0)
* Actions * Actions
*/ */
if ($_POST["action"] == 'setpricelevel') if ($_POST["action"] == 'setpricelevel') {
{
$soc = new Societe($db); $soc = new Societe($db);
$soc->fetch($id); $soc->fetch($id);
$soc->set_price_level($_POST["price_level"], $user); $soc->set_price_level($_POST["price_level"], $user);
@ -62,8 +60,7 @@ llxHeader();
$userstatic = new User($db); $userstatic = new User($db);
if ($_socid > 0) if ($_socid > 0) {
{
// We load data of thirdparty // We load data of thirdparty
$objsoc = new Societe($db); $objsoc = new Societe($db);
$objsoc->id = $_socid; $objsoc->id = $_socid;
@ -73,8 +70,12 @@ if ($_socid > 0)
$head = societe_prepare_head($objsoc); $head = societe_prepare_head($objsoc);
$tabchoice = ''; $tabchoice = '';
if ($objsoc->client == 1) $tabchoice = 'customer'; if ($objsoc->client == 1) {
if ($objsoc->client == 2) $tabchoice = 'prospect'; $tabchoice = 'customer';
}
if ($objsoc->client == 2) {
$tabchoice = 'prospect';
}
print '<form method="POST" action="multiprix.php?id='.$objsoc->id.'">'; print '<form method="POST" action="multiprix.php?id='.$objsoc->id.'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -90,14 +91,16 @@ if ($_socid > 0)
print '<tr><td>'; print '<tr><td>';
print $langs->trans("NewValue").'</td><td>'; print $langs->trans("NewValue").'</td><td>';
print '<select name="price_level" class="flat">'; print '<select name="price_level" class="flat">';
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
{
print '<option value="'.$i.'"'; print '<option value="'.$i.'"';
if ($i == $objsoc->price_level) if ($i == $objsoc->price_level) {
print 'selected'; print 'selected';
}
print '>'.$i; print '>'.$i;
$keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i;
if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); if (!empty($conf->global->$keyforlabel)) {
print ' - '.$langs->trans($conf->global->$keyforlabel);
}
print '</option>'; print '</option>';
} }
print '</select>'; print '</select>';
@ -125,8 +128,7 @@ if ($_socid > 0)
$sql .= " ORDER BY rc.datec DESC"; $sql .= " ORDER BY rc.datec DESC";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
$tag = !$tag; $tag = !$tag;
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
@ -137,8 +139,7 @@ if ($_socid > 0)
$i = 0; $i = 0;
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';

File diff suppressed because it is too large Load Diff

View File

@ -162,28 +162,37 @@ class Proposals extends DolibarrApi
// If the internal user must only see his customers, force searching by him // If the internal user must only see his customers, force searching by him
$search_sale = 0; $search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
$search_sale = DolibarrApiAccess::$user->id;
}
$sql = "SELECT t.rowid"; $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) 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."propal as t"; $sql .= " FROM ".MAIN_DB_PREFIX."propal 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('propal').')'; $sql .= ' WHERE t.entity IN ('.getEntity('propal').')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; $sql .= " AND t.fk_soc = sc.fk_soc";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale }
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 // Insert sale filter
if ($search_sale > 0) if ($search_sale > 0) {
{
$sql .= " AND sc.fk_user = ".$search_sale; $sql .= " AND sc.fk_user = ".$search_sale;
} }
// Add sql filters // Add sql filters
if ($sqlfilters) if ($sqlfilters) {
{ if (!DolibarrApi::_checkFilters($sqlfilters)) {
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@ -192,8 +201,7 @@ class Proposals extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -204,13 +212,11 @@ class Proposals extends DolibarrApi
dol_syslog("API Rest request"); dol_syslog("API Rest request");
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0; $i = 0;
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$proposal_static = new Propal($this->db); $proposal_static = new Propal($this->db);
if ($proposal_static->fetch($obj->rowid)) { if ($proposal_static->fetch($obj->rowid)) {
@ -572,25 +578,23 @@ class Proposals extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->propal->$field = $value; $this->propal->$field = $value;
} }
// update end of validity date // update end of validity date
if (empty($this->propal->fin_validite) && !empty($this->propal->duree_validite) && !empty($this->propal->date_creation)) if (empty($this->propal->fin_validite) && !empty($this->propal->duree_validite) && !empty($this->propal->date_creation)) {
{
$this->propal->fin_validite = $this->propal->date_creation + ($this->propal->duree_validite * 24 * 3600); $this->propal->fin_validite = $this->propal->date_creation + ($this->propal->duree_validite * 24 * 3600);
} }
if (!empty($this->propal->fin_validite)) if (!empty($this->propal->fin_validite)) {
{ if ($this->propal->set_echeance(DolibarrApiAccess::$user, $this->propal->fin_validite) < 0) {
if ($this->propal->set_echeance(DolibarrApiAccess::$user, $this->propal->fin_validite) < 0)
{
throw new RestException(500, $this->propal->error); throw new RestException(500, $this->propal->error);
} }
} }
if ($this->propal->update(DolibarrApiAccess::$user) > 0) if ($this->propal->update(DolibarrApiAccess::$user) > 0) {
{
return $this->get($id); return $this->get($id);
} else { } else {
throw new RestException(500, $this->propal->error); throw new RestException(500, $this->propal->error);
@ -834,8 +838,9 @@ class Proposals extends DolibarrApi
{ {
$propal = array(); $propal = array();
foreach (Proposals::$FIELDS as $field) { foreach (Proposals::$FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$propal[$field] = $data[$field]; $propal[$field] = $data[$field];
} }
return $propal; return $propal;

File diff suppressed because it is too large Load Diff

View File

@ -69,8 +69,7 @@ class PropaleStats extends Stats
$this->userid = $userid; $this->userid = $userid;
$this->join = ''; $this->join = '';
if ($mode == 'customer') if ($mode == 'customer') {
{
$object = new Propal($this->db); $object = new Propal($this->db);
$this->from = MAIN_DB_PREFIX.$object->table_element." as p"; $this->from = MAIN_DB_PREFIX.$object->table_element." as p";
@ -81,8 +80,7 @@ class PropaleStats extends Stats
//$this->where .= " p.fk_statut > 0"; //$this->where .= " p.fk_statut > 0";
} }
if ($mode == 'supplier') if ($mode == 'supplier') {
{
$object = new SupplierProposal($this->db); $object = new SupplierProposal($this->db);
$this->from = MAIN_DB_PREFIX.$object->table_element." as p"; $this->from = MAIN_DB_PREFIX.$object->table_element." as p";
@ -95,21 +93,22 @@ class PropaleStats extends Stats
} }
//$this->where.= " AND p.fk_soc = s.rowid AND p.entity = ".$conf->entity; //$this->where.= " AND p.fk_soc = s.rowid AND p.entity = ".$conf->entity;
$this->where .= ($this->where ? ' AND ' : '')."p.entity IN (".getEntity('propal').")"; $this->where .= ($this->where ? ' AND ' : '')."p.entity IN (".getEntity('propal').")";
if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$this->socid) {
if ($this->socid) $this->where .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
{ }
if ($this->socid) {
$this->where .= " AND p.fk_soc = ".$this->socid; $this->where .= " AND p.fk_soc = ".$this->socid;
} }
if ($this->userid > 0) $this->where .= ' AND fk_user_author = '.$this->userid; if ($this->userid > 0) {
$this->where .= ' AND fk_user_author = '.$this->userid;
}
if ($typentid) if ($typentid) {
{
$this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc'; $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc';
$this->where .= ' AND s.fk_typent = '.$typentid; $this->where .= ' AND s.fk_typent = '.$typentid;
} }
if ($categid) if ($categid) {
{
$this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cs ON cs.fk_soc = p.fk_soc'; $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cs ON cs.fk_soc = p.fk_soc';
$this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie as c ON c.rowid = cs.fk_categorie'; $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie as c ON c.rowid = cs.fk_categorie';
$this->where .= ' AND c.rowid = '.$categid; $this->where .= ' AND c.rowid = '.$categid;
@ -130,7 +129,9 @@ class PropaleStats extends Stats
$sql = "SELECT date_format(".$this->field_date.",'%m') as dm, COUNT(*) as nb"; $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, COUNT(*) as nb";
$sql .= " FROM ".$this->from; $sql .= " FROM ".$this->from;
if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$user->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= $this->join; $sql .= $this->join;
$sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
$sql .= " AND ".$this->where; $sql .= " AND ".$this->where;
@ -153,7 +154,9 @@ class PropaleStats extends Stats
$sql = "SELECT date_format(".$this->field_date.",'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; $sql = "SELECT date_format(".$this->field_date.",'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")";
$sql .= " FROM ".$this->from; $sql .= " FROM ".$this->from;
if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$this->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= $this->join; $sql .= $this->join;
$sql .= " WHERE ".$this->where; $sql .= " WHERE ".$this->where;
$sql .= " GROUP BY dm"; $sql .= " GROUP BY dm";
@ -175,7 +178,9 @@ class PropaleStats extends Stats
$sql = "SELECT date_format(".$this->field_date.",'%m') as dm, SUM(p.".$this->field.")"; $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, SUM(p.".$this->field.")";
$sql .= " FROM ".$this->from; $sql .= " FROM ".$this->from;
if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$this->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= $this->join; $sql .= $this->join;
$sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
$sql .= " AND ".$this->where; $sql .= " AND ".$this->where;
@ -198,7 +203,9 @@ class PropaleStats extends Stats
$sql = "SELECT date_format(".$this->field_date.",'%m') as dm, AVG(p.".$this->field.")"; $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, AVG(p.".$this->field.")";
$sql .= " FROM ".$this->from; $sql .= " FROM ".$this->from;
if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$this->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= $this->join; $sql .= $this->join;
$sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
$sql .= " AND ".$this->where; $sql .= " AND ".$this->where;
@ -219,7 +226,9 @@ class PropaleStats extends Stats
$sql = "SELECT date_format(".$this->field_date.",'%Y') as year, COUNT(*) as nb, SUM(".$this->field.") as total, AVG(".$this->field.") as avg"; $sql = "SELECT date_format(".$this->field_date.",'%Y') as year, COUNT(*) as nb, SUM(".$this->field.") as total, AVG(".$this->field.") as avg";
$sql .= " FROM ".$this->from; $sql .= " FROM ".$this->from;
if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$this->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= $this->join; $sql .= $this->join;
$sql .= " WHERE ".$this->where; $sql .= " WHERE ".$this->where;
$sql .= " GROUP BY year"; $sql .= " GROUP BY year";
@ -243,7 +252,9 @@ class PropaleStats extends Stats
$sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg";
$sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product";
if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$user->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= $this->join; $sql .= $this->join;
$sql .= " WHERE ".$this->where; $sql .= " WHERE ".$this->where;
$sql .= " AND p.rowid = tl.fk_propal AND tl.fk_product = product.rowid"; $sql .= " AND p.rowid = tl.fk_propal AND tl.fk_product = product.rowid";

View File

@ -33,7 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('facture', 'orders', 'sendings', 'companies')); $langs->loadLangs(array('facture', 'propal', 'orders', 'sendings', 'companies'));
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
@ -41,28 +41,26 @@ $lineid = GETPOST('lineid', 'int');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'propal', $id); $result = restrictedArea($user, 'propal', $id);
$object = new Propal($db); $object = new Propal($db);
// Load object // Load object
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$ret = $object->fetch($id, $ref); $ret = $object->fetch($id, $ref);
if ($ret == 0) if ($ret == 0) {
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors'); setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors');
$error++; $error++;
} elseif ($ret < 0) } elseif ($ret < 0) {
{
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
} else { } else {
header('Location: '.DOL_URL_ROOT.'/comm/propal/list.php'); header('Location: '.DOL_URL_ROOT.'/comm/propal/list.php');
@ -74,42 +72,34 @@ if (!$error)
* Add a new contact * Add a new contact
*/ */
if ($action == 'addcontact' && $user->rights->propale->creer) if ($action == 'addcontact' && $user->rights->propale->creer) {
{ if ($object->id > 0) {
if ($object->id > 0)
{
$contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'));
$typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
$result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
} }
if ($result >= 0) if ($result >= 0) {
{
header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
exit; exit;
} else { } else {
if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
} else { } else {
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
} }
} // Toggle the status of a contact } elseif ($action == 'swapstatut' && $user->rights->propale->creer) {
elseif ($action == 'swapstatut' && $user->rights->propale->creer) // Toggle the status of a contact
{ if ($object->id > 0) {
if ($object->id > 0)
{
$result = $object->swapContactStatus(GETPOST('ligne')); $result = $object->swapContactStatus(GETPOST('ligne'));
} }
} // Deletes a contact } elseif ($action == 'deletecontact' && $user->rights->propale->creer) {
elseif ($action == 'deletecontact' && $user->rights->propale->creer) // Deletes a contact
{
$result = $object->delete_contact($lineid); $result = $object->delete_contact($lineid);
if ($result >= 0) if ($result >= 0) {
{
header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
exit; exit;
} else { } else {
@ -134,8 +124,7 @@ $form = new Form($db);
$formcompany = new FormCompany($db); $formcompany = new FormCompany($db);
$formother = new FormOther($db); $formother = new FormOther($db);
if ($object->id > 0) if ($object->id > 0) {
{
$head = propal_prepare_head($object); $head = propal_prepare_head($object);
print dol_get_fiche_head($head, 'contact', $langs->trans("Proposal"), -1, 'propal'); print dol_get_fiche_head($head, 'contact', $langs->trans("Proposal"), -1, 'propal');
@ -152,12 +141,10 @@ if ($object->id > 0)
// Thirdparty // Thirdparty
$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer');
// Project // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($user->rights->propal->creer) if ($user->rights->propal->creer) {
{
if ($action != 'classify') { if ($action != 'classify') {
//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>';
$morehtmlref .= ' : '; $morehtmlref .= ' : ';
@ -194,10 +181,11 @@ if ($object->id > 0)
// Contacts lines (modules that overwrite templates must declare this into descriptor) // Contacts lines (modules that overwrite templates must declare this into descriptor)
$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
foreach ($dirtpls as $reldir) foreach ($dirtpls as $reldir) {
{
$res = @include dol_buildpath($reldir.'/contacts.tpl.php'); $res = @include dol_buildpath($reldir.'/contacts.tpl.php');
if ($res) break; if ($res) {
break;
}
} }
} }

View File

@ -46,8 +46,7 @@ $ref = GETPOST('ref', 'alpha');
// Security check // Security check
$socid = ''; $socid = '';
if (!empty($user->socid)) if (!empty($user->socid)) {
{
$socid = $user->socid; $socid = $user->socid;
} }
$result = restrictedArea($user, 'propal', $id); $result = restrictedArea($user, 'propal', $id);
@ -57,16 +56,26 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; } if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) {
if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; } $sortfield = $conf->global->MAIN_DOC_SORT_FIELD;
}
if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) {
$sortorder = $conf->global->MAIN_DOC_SORT_ORDER;
}
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "name";
}
$object = new Propal($db); $object = new Propal($db);
$object->fetch($id, $ref); $object->fetch($id, $ref);
@ -76,8 +85,7 @@ $object->fetch($id, $ref);
* Actions * Actions
*/ */
if ($object->id > 0) if ($object->id > 0) {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
$upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
@ -92,8 +100,7 @@ llxHeader('', $langs->trans('Proposal'), 'EN:Commercial_Proposals|FR:Proposition
$form = new Form($db); $form = new Form($db);
if ($object->id > 0) if ($object->id > 0) {
{
$upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
$head = propal_prepare_head($object); $head = propal_prepare_head($object);
@ -102,8 +109,7 @@ if ($object->id > 0)
// Build file list // Build file list
$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
$totalsize = 0; $totalsize = 0;
foreach ($filearray as $key => $file) foreach ($filearray as $key => $file) {
{
$totalsize += $file['size']; $totalsize += $file['size'];
} }
@ -120,12 +126,10 @@ if ($object->id > 0)
// Thirdparty // Thirdparty
$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer');
// Project // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($user->rights->propal->creer) if ($user->rights->propal->creer) {
{
if ($action != 'classify') { if ($action != 'classify') {
//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>';
$morehtmlref .= ' : '; $morehtmlref .= ' : ';

View File

@ -40,12 +40,13 @@ $ref = GETPOST('ref', 'alpha');
$socid = GETPOST('socid', 'int'); $socid = GETPOST('socid', 'int');
// Security check // Security check
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'propal', $id); $result = restrictedArea($user, 'propal', $id);
$object = new Propal($db); $object = new Propal($db);
if (!$object->fetch($id, $ref) > 0) if (!$object->fetch($id, $ref) > 0) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -80,12 +81,10 @@ $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_cl
// Thirdparty // Thirdparty
$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
// Project // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($user->rights->propal->creer) if ($user->rights->propal->creer) {
{
if ($action != 'classify') { if ($action != 'classify') {
//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>';
$morehtmlref .= ' : '; $morehtmlref .= ' : ';

File diff suppressed because it is too large Load Diff

View File

@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'propale', $id, 'propal'); $result = restrictedArea($user, 'propale', $id, 'propal');
$object = new Propal($db); $object = new Propal($db);
@ -67,16 +69,15 @@ llxHeader('', $langs->trans('Proposal'), $help_url);
$form = new Form($db); $form = new Form($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{ if ($mesg) {
if ($mesg) print $mesg; print $mesg;
}
$now = dol_now(); $now = dol_now();
if ($object->fetch($id, $ref) > 0) if ($object->fetch($id, $ref) > 0) {
{ if ($object->fetch_thirdparty() > 0) {
if ($object->fetch_thirdparty() > 0)
{
$head = propal_prepare_head($object); $head = propal_prepare_head($object);
print dol_get_fiche_head($head, 'note', $langs->trans('Proposal'), -1, 'propal'); print dol_get_fiche_head($head, 'note', $langs->trans('Proposal'), -1, 'propal');
@ -97,12 +98,10 @@ if ($id > 0 || !empty($ref))
// Thirdparty // Thirdparty
$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
// Project // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($user->rights->propal->creer) if ($user->rights->propal->creer) {
{
if ($action != 'classify') { if ($action != 'classify') {
//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>';
$morehtmlref .= ' : '; $morehtmlref .= ' : ';

View File

@ -38,8 +38,12 @@ $WIDTH = DolGraph::getDefaultGraphSizeForStats('width');
$HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height');
$mode = GETPOSTISSET("mode") ? GETPOST("mode", 'aZ09') : 'customer'; $mode = GETPOSTISSET("mode") ? GETPOST("mode", 'aZ09') : 'customer';
if ($mode == 'customer' && !$user->rights->propale->lire) accessforbidden(); if ($mode == 'customer' && !$user->rights->propale->lire) {
if ($mode == 'supplier' && !$user->rights->supplier_proposal->lire) accessforbidden(); accessforbidden();
}
if ($mode == 'supplier' && !$user->rights->supplier_proposal->lire) {
accessforbidden();
}
$object_status = GETPOST('object_status', 'intcomma'); $object_status = GETPOST('object_status', 'intcomma');
$typent_id = GETPOST('typent_id', 'int'); $typent_id = GETPOST('typent_id', 'int');
@ -48,8 +52,7 @@ $categ_id = GETPOST('categ_id', 'categ_id');
$userid = GETPOST('userid', 'int'); $userid = GETPOST('userid', 'int');
$socid = GETPOST('socid', 'int'); $socid = GETPOST('socid', 'int');
// Security check // Security check
if ($user->socid > 0) if ($user->socid > 0) {
{
$action = ''; $action = '';
$socid = $user->socid; $socid = $user->socid;
} }
@ -75,16 +78,14 @@ $formother = new FormOther($db);
$langs->loadLangs(array('propal', 'other', 'companies')); $langs->loadLangs(array('propal', 'other', 'companies'));
if ($mode == 'customer') if ($mode == 'customer') {
{
$picto = 'propal'; $picto = 'propal';
$title = $langs->trans("ProposalsStatistics"); $title = $langs->trans("ProposalsStatistics");
$dir = $conf->propale->dir_temp; $dir = $conf->propale->dir_temp;
$cat_type = Categorie::TYPE_CUSTOMER; $cat_type = Categorie::TYPE_CUSTOMER;
$cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Customer")); $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Customer"));
} }
if ($mode == 'supplier') if ($mode == 'supplier') {
{
$picto = 'supplier_proposal'; $picto = 'supplier_proposal';
$title = $langs->trans("ProposalsStatisticsSuppliers"); $title = $langs->trans("ProposalsStatisticsSuppliers");
$dir = $conf->supplier_proposal->dir_temp; $dir = $conf->supplier_proposal->dir_temp;
@ -101,15 +102,16 @@ dol_mkdir($dir);
$stats = new PropaleStats($db, $socid, ($userid > 0 ? $userid : 0), $mode, ($typent_id > 0 ? $typent_id : 0), ($categ_id > 0 ? $categ_id : 0)); $stats = new PropaleStats($db, $socid, ($userid > 0 ? $userid : 0), $mode, ($typent_id > 0 ? $typent_id : 0), ($categ_id > 0 ? $categ_id : 0));
if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND p.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; if ($object_status != '' && $object_status >= 0) {
$stats->where .= ' AND p.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')';
}
// Build graphic number of object // Build graphic number of object
$data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear);
// $data = array(array('Lib',val1,val2,val3),...) // $data = array(array('Lib',val1,val2,val3),...)
if (!$user->rights->societe->client->voir || $user->socid) if (!$user->rights->societe->client->voir || $user->socid) {
{
$filenamenb = $dir.'/proposalsnbinyear-'.$user->id.'-'.$year.'.png'; $filenamenb = $dir.'/proposalsnbinyear-'.$user->id.'-'.$year.'.png';
$fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=proposalsnbinyear-'.$user->id.'-'.$year.'.png'; $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=proposalsnbinyear-'.$user->id.'-'.$year.'.png';
} else { } else {
@ -119,12 +121,10 @@ if (!$user->rights->societe->client->voir || $user->socid)
$px1 = new DolGraph(); $px1 = new DolGraph();
$mesg = $px1->isGraphKo(); $mesg = $px1->isGraphKo();
if (!$mesg) if (!$mesg) {
{
$px1->SetData($data); $px1->SetData($data);
$i = $startyear; $legend = array(); $i = $startyear; $legend = array();
while ($i <= $endyear) while ($i <= $endyear) {
{
$legend[] = $i; $legend[] = $i;
$i++; $i++;
} }
@ -146,8 +146,7 @@ if (!$mesg)
$data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear, 0); $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear, 0);
// $data = array(array('Lib',val1,val2,val3),...) // $data = array(array('Lib',val1,val2,val3),...)
if (!$user->rights->societe->client->voir || $user->socid) if (!$user->rights->societe->client->voir || $user->socid) {
{
$filenameamount = $dir.'/proposalsamountinyear-'.$user->id.'-'.$year.'.png'; $filenameamount = $dir.'/proposalsamountinyear-'.$user->id.'-'.$year.'.png';
$fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=proposalsamountinyear-'.$user->id.'-'.$year.'.png'; $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=proposalsamountinyear-'.$user->id.'-'.$year.'.png';
} else { } else {
@ -157,12 +156,10 @@ if (!$user->rights->societe->client->voir || $user->socid)
$px2 = new DolGraph(); $px2 = new DolGraph();
$mesg = $px2->isGraphKo(); $mesg = $px2->isGraphKo();
if (!$mesg) if (!$mesg) {
{
$px2->SetData($data); $px2->SetData($data);
$i = $startyear; $legend = array(); $i = $startyear; $legend = array();
while ($i <= $endyear) while ($i <= $endyear) {
{
$legend[] = $i; $legend[] = $i;
$i++; $i++;
} }
@ -183,25 +180,30 @@ if (!$mesg)
$data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear);
$fileurl_avg = ''; $fileurl_avg = '';
if (!$user->rights->societe->client->voir || $user->socid) if (!$user->rights->societe->client->voir || $user->socid) {
{
$filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png'; $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png';
if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; if ($mode == 'customer') {
if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png';
}
if ($mode == 'supplier') {
$fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png';
}
} else { } else {
$filename_avg = $dir.'/ordersaverage-'.$year.'.png'; $filename_avg = $dir.'/ordersaverage-'.$year.'.png';
if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; if ($mode == 'customer') {
if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png';
}
if ($mode == 'supplier') {
$fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png';
}
} }
$px3 = new DolGraph(); $px3 = new DolGraph();
$mesg = $px3->isGraphKo(); $mesg = $px3->isGraphKo();
if (!$mesg) if (!$mesg) {
{
$px3->SetData($data); $px3->SetData($data);
$i = $startyear; $legend = array(); $i = $startyear; $legend = array();
while ($i <= $endyear) while ($i <= $endyear) {
{
$legend[] = $i; $legend[] = $i;
$i++; $i++;
} }
@ -228,7 +230,9 @@ foreach ($data as $val) {
$arrayyears[$val['year']] = $val['year']; $arrayyears[$val['year']] = $val['year'];
} }
} }
if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; if (!count($arrayyears)) {
$arrayyears[$nowyear] = $nowyear;
}
$h = 0; $h = 0;
@ -264,7 +268,9 @@ print '<div class="fichecenter"><div class="fichethirdleft">';
print '<tr><td>'.$langs->trans("ThirdPartyType").'</td><td>'; print '<tr><td>'.$langs->trans("ThirdPartyType").'</td><td>';
$sortparam_typent = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. $sortparam_typent = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label.
print $form->selectarray("typent_id", $formcompany->typent_array(0), $typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam_typent, '', 1); print $form->selectarray("typent_id", $formcompany->typent_array(0), $typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam_typent, '', 1);
if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); if ($user->admin) {
print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
print '</td></tr>'; print '</td></tr>';
// Category // Category
print '<tr><td>'.$cat_label.'</td><td>'; print '<tr><td>'.$cat_label.'</td><td>';
@ -280,8 +286,12 @@ print '<div class="fichecenter"><div class="fichethirdleft">';
print '</td></tr>'; print '</td></tr>';
// Year // Year
print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">'; print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">';
if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; if (!in_array($year, $arrayyears)) {
if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; $arrayyears[$year] = $year;
}
if (!in_array($nowyear, $arrayyears)) {
$arrayyears[$nowyear] = $nowyear;
}
arsort($arrayyears); arsort($arrayyears);
print $form->selectarray('year', $arrayyears, $year, 0); print $form->selectarray('year', $arrayyears, $year, 0);
print '</td></tr>'; print '</td></tr>';
@ -304,11 +314,9 @@ print '<td class="right">%</td>';
print '</tr>'; print '</tr>';
$oldyear = 0; $oldyear = 0;
foreach ($data as $val) foreach ($data as $val) {
{
$year = $val['year']; $year = $val['year'];
while (!empty($year) && $oldyear > $year + 1) while (!empty($year) && $oldyear > $year + 1) { // If we have empty year
{ // If we have empty year
$oldyear--; $oldyear--;
print '<tr class="oddeven" height="24">'; print '<tr class="oddeven" height="24">';
@ -341,7 +349,9 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
// Show graphs // Show graphs
print '<table class="border centpercent"><tr class="pair nohover"><td align="center">'; print '<table class="border centpercent"><tr class="pair nohover"><td align="center">';
if ($mesg) { print $mesg; } else { if ($mesg) {
print $mesg;
} else {
print $px1->show(); print $px1->show();
print "<br>\n"; print "<br>\n";
print $px2->show(); print $px2->show();

View File

@ -44,16 +44,16 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1)
$total = 0; $total = 0;
$ilink = 0; $ilink = 0;
foreach ($linkedObjectBlock as $key => $objectlink) foreach ($linkedObjectBlock as $key => $objectlink) {
{
$ilink++; $ilink++;
$trclass = 'oddeven'; $trclass = 'oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) {
$trclass .= ' liste_sub_total';
}
print '<tr class="'.$trclass.'" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" >'; print '<tr class="'.$trclass.'" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" >';
print '<td class="linkedcol-element" >'.$langs->trans("Proposal"); print '<td class="linkedcol-element" >'.$langs->trans("Proposal");
if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) {
{
$url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$objectlink->id; $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$objectlink->id;
print '<a class="objectlinked_importbtn" href="'.$url.'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a>'; print '<a class="objectlinked_importbtn" href="'.$url.'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a>';
} }
@ -71,8 +71,7 @@ foreach ($linkedObjectBlock as $key => $objectlink)
print '<td class="linkedcol-action right"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key.'">'.img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink').'</a></td>'; print '<td class="linkedcol-action right"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key.'">'.img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink').'</a></td>';
print "</tr>\n"; print "</tr>\n";
} }
if (count($linkedObjectBlock) > 1) if (count($linkedObjectBlock) > 1) {
{
print '<tr class="liste_total '.(empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : '').'">'; print '<tr class="liste_total '.(empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : '').'">';
print '<td>'.$langs->trans("Total").'</td>'; print '<td>'.$langs->trans("Total").'</td>';
print '<td></td>'; print '<td></td>';

View File

@ -36,7 +36,6 @@ if ($user->socid > 0) {
} }
/* /*
* View * View
*/ */

View File

@ -28,26 +28,25 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('companies', 'other')); $langs->loadLangs(array('companies', 'other'));
if (!empty($conf->facture->enabled)) $langs->load("bills"); if (!empty($conf->facture->enabled)) {
$langs->load("bills");
}
// Security check // Security check
$socid = $_GET["socid"]; $socid = $_GET["socid"];
if ($user->socid > 0) if ($user->socid > 0) {
{
$action = ''; $action = '';
$socid = $user->socid; $socid = $user->socid;
} }
/* /*
* View * View
*/ */
llxHeader(); llxHeader();
if ($socid > 0) if ($socid > 0) {
{
$societe = new Societe($db); $societe = new Societe($db);
$societe->fetch($socid); $societe->fetch($socid);
@ -68,8 +67,7 @@ if ($socid > 0)
print '<tr><td width="20%">'.$langs->trans("Thirdpary").'</td><td width="80%" colspan="3">'.$societe->getNomUrl(1).'</td></tr>'; print '<tr><td width="20%">'.$langs->trans("Thirdpary").'</td><td width="80%" colspan="3">'.$societe->getNomUrl(1).'</td></tr>';
// Prefix // Prefix
if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field
{
print '<tr><td>'.$langs->trans("Prefix").'</td><td colspan="3">'; print '<tr><td>'.$langs->trans("Prefix").'</td><td colspan="3">';
print ($societe->prefix_comm ? $societe->prefix_comm : '&nbsp;'); print ($societe->prefix_comm ? $societe->prefix_comm : '&nbsp;');
print '</td></tr>'; print '</td></tr>';

View File

@ -28,12 +28,13 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
// Load translation files required by the page // Load translation files required by the page
$langs->load("companies"); $langs->load("companies");
if (!empty($conf->facture->enabled)) $langs->load("bills"); if (!empty($conf->facture->enabled)) {
$langs->load("bills");
}
// Security check // Security check
$socid = $_GET["socid"]; $socid = $_GET["socid"];
if ($user->socid > 0) if ($user->socid > 0) {
{
$action = ''; $action = '';
$socid = $user->socid; $socid = $user->socid;
} }
@ -46,8 +47,7 @@ if ($user->socid > 0)
llxHeader(); llxHeader();
if ($socid > 0) if ($socid > 0) {
{
$societe = new Societe($db); $societe = new Societe($db);
$societe->fetch($socid); $societe->fetch($socid);
@ -68,8 +68,7 @@ if ($socid > 0)
print '<tr><td width="20%">'.$langs->trans("ThirdParty").'</td><td width="80%" colspan="3">'.$societe->getNomUrl(1).'</td></tr>'; print '<tr><td width="20%">'.$langs->trans("ThirdParty").'</td><td width="80%" colspan="3">'.$societe->getNomUrl(1).'</td></tr>';
// Prefix // Prefix
if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field
{
print '<tr><td>'.$langs->trans("Prefix").'</td><td colspan="3">'; print '<tr><td>'.$langs->trans("Prefix").'</td><td colspan="3">';
print ($societe->prefix_comm ? $societe->prefix_comm : '&nbsp;'); print ($societe->prefix_comm ? $societe->prefix_comm : '&nbsp;');
print '</td></tr>'; print '</td></tr>';

View File

@ -33,8 +33,7 @@ $id = GETPOST("id", 'int');
$socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); $socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int');
// Security check // Security check
if ($user->socid > 0) if ($user->socid > 0) {
{
$socid = $user->socid; $socid = $user->socid;
} }
@ -45,14 +44,12 @@ $backtopage = GETPOST('backtopage', 'alpha');
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha') && !empty($backtopage)) if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} }
if (GETPOST('action', 'aZ09') == 'setremise') if (GETPOST('action', 'aZ09') == 'setremise') {
{
$object = new Societe($db); $object = new Societe($db);
$object->fetch($id); $object->fetch($id);
@ -64,10 +61,8 @@ if (GETPOST('action', 'aZ09') == 'setremise')
$result = $object->set_remise_client(price2num(GETPOST("remise")), GETPOST("note", "alphanohtml"), $user); $result = $object->set_remise_client(price2num(GETPOST("remise")), GETPOST("note", "alphanohtml"), $user);
} }
if ($result > 0) if ($result > 0) {
{ if (!empty($backtopage)) {
if (!empty($backtopage))
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} else { } else {
@ -94,8 +89,7 @@ llxHeader();
* Mode fiche * Mode fiche
* *
*********************************************************************************/ *********************************************************************************/
if ($socid > 0) if ($socid > 0) {
{
// On recupere les donnees societes par l'objet // On recupere les donnees societes par l'objet
$object = new Societe($db); $object = new Societe($db);
$object->fetch($socid); $object->fetch($socid);
@ -164,8 +158,7 @@ if ($socid > 0)
print '<table class="border centpercent">'; print '<table class="border centpercent">';
if ($isCustomer || $isSupplier) if ($isCustomer || $isSupplier) {
{
// Discount type // Discount type
print '<tr><td class="titlefield fieldrequired">'.$langs->trans('DiscountType').'</td><td>'; print '<tr><td class="titlefield fieldrequired">'.$langs->trans('DiscountType').'</td><td>';
if ($isCustomer) { if ($isCustomer) {
@ -193,8 +186,7 @@ if ($socid > 0)
print '<div class="center">'; print '<div class="center">';
print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">'; print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
if (!empty($backtopage)) if (!empty($backtopage)) {
{
print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
} }
@ -223,8 +215,7 @@ if ($socid > 0)
$sql .= " ORDER BY rc.datec DESC"; $sql .= " ORDER BY rc.datec DESC";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
$tag = !$tag; $tag = !$tag;
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
@ -234,11 +225,9 @@ if ($socid > 0)
print '<td class="center">'.$langs->trans("User").'</td>'; print '<td class="center">'.$langs->trans("User").'</td>';
print '</tr>'; print '</tr>';
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num > 0) if ($num > 0) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.dol_print_date($db->jdate($obj->dc), "dayhour").'</td>'; print '<td>'.dol_print_date($db->jdate($obj->dc), "dayhour").'</td>';
@ -278,8 +267,7 @@ if ($socid > 0)
$sql .= " ORDER BY rc.datec DESC"; $sql .= " ORDER BY rc.datec DESC";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
$tag = !$tag; $tag = !$tag;
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
@ -289,11 +277,9 @@ if ($socid > 0)
print '<td class="center">'.$langs->trans("User").'</td>'; print '<td class="center">'.$langs->trans("User").'</td>';
print '</tr>'; print '</tr>';
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num > 0) if ($num > 0) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.dol_print_date($db->jdate($obj->dc), "dayhour").'</td>'; print '<td>'.dol_print_date($db->jdate($obj->dc), "dayhour").'</td>';

View File

@ -40,8 +40,7 @@ $backtopage = GETPOST('backtopage', 'alpha');
// Security check // Security check
$socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); $socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int');
if ($user->socid > 0) if ($user->socid > 0) {
{
$socid = $user->socid; $socid = $user->socid;
} }
@ -50,14 +49,12 @@ if ($user->socid > 0)
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha') && !empty($backtopage)) if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} }
if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') {
{
//if ($user->rights->societe->creer) //if ($user->rights->societe->creer)
//if ($user->rights->facture->creer) //if ($user->rights->facture->creer)
@ -70,23 +67,19 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes')
$remid = (GETPOST("remid", 'int') ? GETPOST("remid", 'int') : 0); $remid = (GETPOST("remid", 'int') ? GETPOST("remid", 'int') : 0);
$discount = new DiscountAbsolute($db); $discount = new DiscountAbsolute($db);
$res = $discount->fetch($remid); $res = $discount->fetch($remid);
if (!($res > 0)) if (!($res > 0)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFailedToLoadDiscount"), null, 'errors'); setEventMessages($langs->trans("ErrorFailedToLoadDiscount"), null, 'errors');
} }
if (!$error && price2num($amount_ttc_1 + $amount_ttc_2) != $discount->amount_ttc) if (!$error && price2num($amount_ttc_1 + $amount_ttc_2) != $discount->amount_ttc) {
{
$error++; $error++;
setEventMessages($langs->trans("TotalOfTwoDiscountMustEqualsOriginal"), null, 'errors'); setEventMessages($langs->trans("TotalOfTwoDiscountMustEqualsOriginal"), null, 'errors');
} }
if (!$error && $discount->fk_facture_line) if (!$error && $discount->fk_facture_line) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorCantSplitAUsedDiscount"), null, 'errors'); setEventMessages($langs->trans("ErrorCantSplitAUsedDiscount"), null, 'errors');
} }
if (!$error) if (!$error) {
{
$newdiscount1 = new DiscountAbsolute($db); $newdiscount1 = new DiscountAbsolute($db);
$newdiscount2 = new DiscountAbsolute($db); $newdiscount2 = new DiscountAbsolute($db);
$newdiscount1->fk_facture_source = $discount->fk_facture_source; $newdiscount1->fk_facture_source = $discount->fk_facture_source;
@ -101,8 +94,7 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes')
$newdiscount2->fk_invoice_supplier = $discount->fk_invoice_supplier; $newdiscount2->fk_invoice_supplier = $discount->fk_invoice_supplier;
$newdiscount1->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line; $newdiscount1->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line;
$newdiscount2->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line; $newdiscount2->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line;
if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') {
{
$newdiscount1->description = $discount->description; $newdiscount1->description = $discount->description;
$newdiscount2->description = $discount->description; $newdiscount2->description = $discount->description;
} else { } else {
@ -143,8 +135,7 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes')
$res = $discount->delete($user); $res = $discount->delete($user);
$newid1 = $newdiscount1->create($user); $newid1 = $newdiscount1->create($user);
$newid2 = $newdiscount2->create($user); $newid2 = $newdiscount2->create($user);
if ($res > 0 && $newid1 > 0 && $newid2 > 0) if ($res > 0 && $newid1 > 0 && $newid2 > 0) {
{
$db->commit(); $db->commit();
header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id.($backtopage ? '&backtopage='.urlencode($backtopage) : '')); // To avoid pb whith back header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id.($backtopage ? '&backtopage='.urlencode($backtopage) : '')); // To avoid pb whith back
exit; exit;
@ -154,8 +145,7 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes')
} }
} }
if ($action == 'setremise' && $user->rights->societe->creer) if ($action == 'setremise' && $user->rights->societe->creer) {
{
//if ($user->rights->societe->creer) //if ($user->rights->societe->creer)
//if ($user->rights->facture->creer) //if ($user->rights->facture->creer)
@ -164,25 +154,20 @@ if ($action == 'setremise' && $user->rights->societe->creer)
$tva_tx = GETPOST('tva_tx', 'alpha'); $tva_tx = GETPOST('tva_tx', 'alpha');
$discount_type = !empty($_POST['discount_type']) ?GETPOST('discount_type', 'alpha') : 0; $discount_type = !empty($_POST['discount_type']) ?GETPOST('discount_type', 'alpha') : 0;
if ($amount_ht > 0) if ($amount_ht > 0) {
{
$error = 0; $error = 0;
if (empty($desc)) if (empty($desc)) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReasonDiscount")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReasonDiscount")), null, 'errors');
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$soc = new Societe($db); $soc = new Societe($db);
$soc->fetch($id); $soc->fetch($id);
$discountid = $soc->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type); $discountid = $soc->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type);
if ($discountid > 0) if ($discountid > 0) {
{ if (!empty($backtopage)) {
if (!empty($backtopage))
{
header("Location: ".$backtopage.'&discountid='.$discountid); header("Location: ".$backtopage.'&discountid='.$discountid);
exit; exit;
} else { } else {
@ -199,8 +184,7 @@ if ($action == 'setremise' && $user->rights->societe->creer)
} }
} }
if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes') if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes') {
{
//if ($user->rights->societe->creer) //if ($user->rights->societe->creer)
//if ($user->rights->facture->creer) //if ($user->rights->facture->creer)
@ -209,8 +193,7 @@ if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes'
$discount = new DiscountAbsolute($db); $discount = new DiscountAbsolute($db);
$result = $discount->fetch(GETPOST("remid")); $result = $discount->fetch(GETPOST("remid"));
$result = $discount->delete($user); $result = $discount->delete($user);
if ($result > 0) if ($result > 0) {
{
$db->commit(); $db->commit();
header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id); // To avoid pb whith back header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id); // To avoid pb whith back
exit; exit;
@ -231,8 +214,7 @@ $facturefournstatic = new FactureFournisseur($db);
llxHeader('', $langs->trans("GlobalDiscount")); llxHeader('', $langs->trans("GlobalDiscount"));
if ($socid > 0) if ($socid > 0) {
{
// On recupere les donnees societes par l'objet // On recupere les donnees societes par l'objet
$object = new Societe($db); $object = new Societe($db);
$object->fetch($socid); $object->fetch($socid);
@ -283,11 +265,12 @@ if ($socid > 0)
$sql .= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; $sql .= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)";
$sql .= " GROUP BY rc.fk_user"; $sql .= " GROUP BY rc.fk_user";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$remise_all += $obj->amount; $remise_all += $obj->amount;
if ($obj->fk_user == $user->id) $remise_user += $obj->amount; if ($obj->fk_user == $user->id) {
$remise_user += $obj->amount;
}
} else { } else {
dol_print_error($db); dol_print_error($db);
} }
@ -295,8 +278,7 @@ if ($socid > 0)
print '<tr><td class="titlefield">'.$langs->trans("CustomerAbsoluteDiscountAllUsers").'</td>'; print '<tr><td class="titlefield">'.$langs->trans("CustomerAbsoluteDiscountAllUsers").'</td>';
print '<td>'.$remise_all.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>'; print '<td>'.$remise_all.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>';
if (!empty($user->fk_soc)) // No need to show this for external users if (!empty($user->fk_soc)) { // No need to show this for external users
{
print '<tr><td>'.$langs->trans("CustomerAbsoluteDiscountMy").'</td>'; print '<tr><td>'.$langs->trans("CustomerAbsoluteDiscountMy").'</td>';
print '<td>'.$remise_user.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>'; print '<td>'.$remise_user.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>';
} }
@ -313,11 +295,12 @@ if ($socid > 0)
$sql .= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)"; $sql .= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)";
$sql .= " GROUP BY rc.fk_user"; $sql .= " GROUP BY rc.fk_user";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$remise_all += $obj->amount; $remise_all += $obj->amount;
if ($obj->fk_user == $user->id) $remise_user += $obj->amount; if ($obj->fk_user == $user->id) {
$remise_user += $obj->amount;
}
} else { } else {
dol_print_error($db); dol_print_error($db);
} }
@ -325,8 +308,7 @@ if ($socid > 0)
print '<tr><td class="titlefield">'.$langs->trans("SupplierAbsoluteDiscountAllUsers").'</td>'; print '<tr><td class="titlefield">'.$langs->trans("SupplierAbsoluteDiscountAllUsers").'</td>';
print '<td>'.$remise_all.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>'; print '<td>'.$remise_all.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>';
if (!empty($user->fk_soc)) // No need to show this for external users if (!empty($user->fk_soc)) { // No need to show this for external users
{
print '<tr><td>'.$langs->trans("SupplierAbsoluteDiscountMy").'</td>'; print '<tr><td>'.$langs->trans("SupplierAbsoluteDiscountMy").'</td>';
print '<td>'.$remise_user.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>'; print '<td>'.$remise_user.'&nbsp;'.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'</td></tr>';
} }
@ -339,8 +321,7 @@ if ($socid > 0)
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($user->rights->societe->creer) if ($user->rights->societe->creer) {
{
print '<br>'; print '<br>';
print load_fiche_titre($langs->trans("NewGlobalDiscount"), '', ''); print load_fiche_titre($langs->trans("NewGlobalDiscount"), '', '');
@ -378,12 +359,10 @@ if ($socid > 0)
print dol_get_fiche_end(); print dol_get_fiche_end();
} }
if ($user->rights->societe->creer) if ($user->rights->societe->creer) {
{
print '<div class="center">'; print '<div class="center">';
print '<input type="submit" class="button" name="submit" value="'.$langs->trans("AddGlobalDiscount").'">'; print '<input type="submit" class="button" name="submit" value="'.$langs->trans("AddGlobalDiscount").'">';
if (!empty($backtopage)) if (!empty($backtopage)) {
{
print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
} }
@ -395,8 +374,7 @@ if ($socid > 0)
print '<br>'; print '<br>';
if ($_GET['action'] == 'remove') if ($_GET['action'] == 'remove') {
{
print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.GETPOST('remid'), $langs->trans('RemoveDiscount'), $langs->trans('ConfirmRemoveDiscount'), 'confirm_remove', '', 0, 1); print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.GETPOST('remid'), $langs->trans('RemoveDiscount'), $langs->trans('ConfirmRemoveDiscount'), 'confirm_remove', '', 0, 1);
} }
@ -430,8 +408,7 @@ if ($socid > 0)
$sql .= " ORDER BY rc.datec DESC"; $sql .= " ORDER BY rc.datec DESC";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table width="100%" class="noborder">'; print '<table width="100%" class="noborder">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
@ -439,14 +416,12 @@ if ($socid > 0)
print '<td>'.$langs->trans("ReasonDiscount").'</td>'; print '<td>'.$langs->trans("ReasonDiscount").'</td>';
print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>'; print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>';
print '<td class="right">'.$langs->trans("AmountHT").'</td>'; print '<td class="right">'.$langs->trans("AmountHT").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>';
} }
print '<td class="right">'.$langs->trans("VATRate").'</td>'; print '<td class="right">'.$langs->trans("VATRate").'</td>';
print '<td class="right">'.$langs->trans("AmountTTC").'</td>'; print '<td class="right">'.$langs->trans("AmountTTC").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>';
} }
print '<td width="100" class="center">'.$langs->trans("DiscountOfferedBy").'</td>'; print '<td width="100" class="center">'.$langs->trans("DiscountOfferedBy").'</td>';
@ -457,32 +432,27 @@ if ($socid > 0)
$i = 0; $i = 0;
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num > 0) if ($num > 0) {
{ while ($i < $num) {
while ($i < $num)
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>'; print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>';
if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturestatic->id = $obj->fk_facture_source; $facturestatic->id = $obj->fk_facture_source;
$facturestatic->ref = $obj->ref; $facturestatic->ref = $obj->ref;
$facturestatic->type = $obj->type; $facturestatic->type = $obj->type;
print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1); print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturestatic->id = $obj->fk_facture_source; $facturestatic->id = $obj->fk_facture_source;
$facturestatic->ref = $obj->ref; $facturestatic->ref = $obj->ref;
$facturestatic->type = $obj->type; $facturestatic->type = $obj->type;
print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1); print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturestatic->id = $obj->fk_facture_source; $facturestatic->id = $obj->fk_facture_source;
$facturestatic->ref = $obj->ref; $facturestatic->ref = $obj->ref;
@ -496,30 +466,28 @@ if ($socid > 0)
} }
print '<td class="nowrap">'.$langs->trans("NotConsumed").'</td>'; print '<td class="nowrap">'.$langs->trans("NotConsumed").'</td>';
print '<td class="right">'.price($obj->amount_ht).'</td>'; print '<td class="right">'.price($obj->amount_ht).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>';
} }
print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>'; print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>';
print '<td class="right">'.price($obj->amount_ttc).'</td>'; print '<td class="right">'.price($obj->amount_ttc).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>';
} }
print '<td class="center">'; print '<td class="center">';
print '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$obj->user_id.'">'.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.'</a>'; print '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$obj->user_id.'">'.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.'</a>';
print '</td>'; print '</td>';
if ($user->rights->societe->creer || $user->rights->facture->creer) if ($user->rights->societe->creer || $user->rights->facture->creer) {
{
print '<td class="center nowrap">'; print '<td class="center nowrap">';
print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=split&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).'</a>'; print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=split&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).'</a>';
print '<a class="reposition marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=remove&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).'</a>'; print '<a class="reposition marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=remove&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).'</a>';
print '</td>'; print '</td>';
} else print '<td>&nbsp;</td>'; } else {
print '<td>&nbsp;</td>';
}
print '</tr>'; print '</tr>';
if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) {
{
$showconfirminfo['rowid'] = $obj->rowid; $showconfirminfo['rowid'] = $obj->rowid;
$showconfirminfo['amount_ttc'] = $obj->amount_ttc; $showconfirminfo['amount_ttc'] = $obj->amount_ttc;
} }
@ -527,15 +495,16 @@ if ($socid > 0)
} }
} else { } else {
$colspan = 8; $colspan = 8;
if (!empty($conf->multicurrency->enabled)) $colspan += 2; if (!empty($conf->multicurrency->enabled)) {
$colspan += 2;
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
} }
$db->free($resql); $db->free($resql);
print "</table>"; print "</table>";
print '</div>'; print '</div>';
if (count($showconfirminfo)) if (count($showconfirminfo)) {
{
$amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT'); $amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT');
$amount2 = ($showconfirminfo['amount_ttc'] - $amount1); $amount2 = ($showconfirminfo['amount_ttc'] - $amount1);
$formquestion = array( $formquestion = array(
@ -578,8 +547,7 @@ if ($socid > 0)
$sql .= " ORDER BY rc.datec DESC"; $sql .= " ORDER BY rc.datec DESC";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table width="100%" class="noborder">'; print '<table width="100%" class="noborder">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
@ -587,14 +555,12 @@ if ($socid > 0)
print '<td>'.$langs->trans("ReasonDiscount").'</td>'; print '<td>'.$langs->trans("ReasonDiscount").'</td>';
print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>'; print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>';
print '<td class="right">'.$langs->trans("AmountHT").'</td>'; print '<td class="right">'.$langs->trans("AmountHT").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>';
} }
print '<td class="right">'.$langs->trans("VATRate").'</td>'; print '<td class="right">'.$langs->trans("VATRate").'</td>';
print '<td class="right">'.$langs->trans("AmountTTC").'</td>'; print '<td class="right">'.$langs->trans("AmountTTC").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>';
} }
print '<td width="100" class="center">'.$langs->trans("DiscountOfferedBy").'</td>'; print '<td width="100" class="center">'.$langs->trans("DiscountOfferedBy").'</td>';
@ -605,32 +571,27 @@ if ($socid > 0)
$i = 0; $i = 0;
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num > 0) if ($num > 0) {
{ while ($i < $num) {
while ($i < $num)
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>'; print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>';
if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->id = $obj->fk_invoice_supplier_source;
$facturefournstatic->ref = $obj->ref; $facturefournstatic->ref = $obj->ref;
$facturefournstatic->type = $obj->type; $facturefournstatic->type = $obj->type;
print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1); print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->id = $obj->fk_invoice_supplier_source;
$facturefournstatic->ref = $obj->ref; $facturefournstatic->ref = $obj->ref;
$facturefournstatic->type = $obj->type; $facturefournstatic->type = $obj->type;
print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1); print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->id = $obj->fk_invoice_supplier_source;
$facturefournstatic->ref = $obj->ref; $facturefournstatic->ref = $obj->ref;
@ -644,30 +605,28 @@ if ($socid > 0)
} }
print '<td class="nowrap">'.$langs->trans("NotConsumed").'</td>'; print '<td class="nowrap">'.$langs->trans("NotConsumed").'</td>';
print '<td class="right">'.price($obj->amount_ht).'</td>'; print '<td class="right">'.price($obj->amount_ht).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>';
} }
print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>'; print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>';
print '<td class="right">'.price($obj->amount_ttc).'</td>'; print '<td class="right">'.price($obj->amount_ttc).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>';
} }
print '<td class="center">'; print '<td class="center">';
print '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$obj->user_id.'">'.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.'</a>'; print '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$obj->user_id.'">'.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.'</a>';
print '</td>'; print '</td>';
if ($user->rights->societe->creer || $user->rights->facture->creer) if ($user->rights->societe->creer || $user->rights->facture->creer) {
{
print '<td class="center nowrap">'; print '<td class="center nowrap">';
print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=split&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).'</a>'; print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=split&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).'</a>';
print '<a class="reposition marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=remove&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).'</a>'; print '<a class="reposition marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=remove&remid='.$obj->rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).'</a>';
print '</td>'; print '</td>';
} else print '<td>&nbsp;</td>'; } else {
print '<td>&nbsp;</td>';
}
print '</tr>'; print '</tr>';
if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) {
{
$showconfirminfo['rowid'] = $obj->rowid; $showconfirminfo['rowid'] = $obj->rowid;
$showconfirminfo['amount_ttc'] = $obj->amount_ttc; $showconfirminfo['amount_ttc'] = $obj->amount_ttc;
} }
@ -675,15 +634,16 @@ if ($socid > 0)
} }
} else { } else {
$colspan = 8; $colspan = 8;
if (!empty($conf->multicurrency->enabled)) $colspan += 2; if (!empty($conf->multicurrency->enabled)) {
$colspan += 2;
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
} }
$db->free($resql); $db->free($resql);
print "</table>"; print "</table>";
print '</div>'; print '</div>';
if (count($showconfirminfo)) if (count($showconfirminfo)) {
{
$amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT'); $amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT');
$amount2 = ($showconfirminfo['amount_ttc'] - $amount1); $amount2 = ($showconfirminfo['amount_ttc'] - $amount1);
$formquestion = array( $formquestion = array(
@ -758,9 +718,10 @@ if ($socid > 0)
$resql = $db->query($sql); $resql = $db->query($sql);
$resql2 = null; $resql2 = null;
if ($resql) $resql2 = $db->query($sql2); if ($resql) {
if ($resql2) $resql2 = $db->query($sql2);
{ }
if ($resql2) {
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
@ -768,14 +729,12 @@ if ($socid > 0)
print '<td>'.$langs->trans("ReasonDiscount").'</td>'; print '<td>'.$langs->trans("ReasonDiscount").'</td>';
print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>'; print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>';
print '<td class="right">'.$langs->trans("AmountHT").'</td>'; print '<td class="right">'.$langs->trans("AmountHT").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>';
} }
print '<td class="right">'.$langs->trans("VATRate").'</td>'; print '<td class="right">'.$langs->trans("VATRate").'</td>';
print '<td class="right">'.$langs->trans("AmountTTC").'</td>'; print '<td class="right">'.$langs->trans("AmountTTC").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>';
} }
print '<td width="100" class="center">'.$langs->trans("Author").'</td>'; print '<td width="100" class="center">'.$langs->trans("Author").'</td>';
@ -785,10 +744,8 @@ if ($socid > 0)
$tab_sqlobj = array(); $tab_sqlobj = array();
$tab_sqlobjOrder = array(); $tab_sqlobjOrder = array();
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num > 0) if ($num > 0) {
{ for ($i = 0; $i < $num; $i++) {
for ($i = 0; $i < $num; $i++)
{
$sqlobj = $db->fetch_object($resql); $sqlobj = $db->fetch_object($resql);
$tab_sqlobj[] = $sqlobj; $tab_sqlobj[] = $sqlobj;
$tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc);
@ -797,8 +754,7 @@ if ($socid > 0)
$db->free($resql); $db->free($resql);
$num = $db->num_rows($resql2); $num = $db->num_rows($resql2);
for ($i = 0; $i < $num; $i++) for ($i = 0; $i < $num; $i++) {
{
$sqlobj = $db->fetch_object($resql2); $sqlobj = $db->fetch_object($resql2);
$tab_sqlobj[] = $sqlobj; $tab_sqlobj[] = $sqlobj;
$tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc);
@ -807,32 +763,27 @@ if ($socid > 0)
array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj); array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj);
$num = count($tab_sqlobj); $num = count($tab_sqlobj);
if ($num > 0) if ($num > 0) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = array_shift($tab_sqlobj); $obj = array_shift($tab_sqlobj);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>'; print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>';
if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturestatic->id = $obj->fk_facture_source; $facturestatic->id = $obj->fk_facture_source;
$facturestatic->ref = $obj->invoice_source_ref; $facturestatic->ref = $obj->invoice_source_ref;
$facturestatic->type = $obj->type; $facturestatic->type = $obj->type;
print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1); print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturestatic->id = $obj->fk_facture_source; $facturestatic->id = $obj->fk_facture_source;
$facturestatic->ref = $obj->invoice_source_ref; $facturestatic->ref = $obj->invoice_source_ref;
$facturestatic->type = $obj->type; $facturestatic->type = $obj->type;
print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1); print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturestatic->id = $obj->fk_facture_source; $facturestatic->id = $obj->fk_facture_source;
$facturestatic->ref = $obj->invoice_source_ref; $facturestatic->ref = $obj->invoice_source_ref;
@ -845,20 +796,17 @@ if ($socid > 0)
print '</td>'; print '</td>';
} }
print '<td class="left nowrap">'; print '<td class="left nowrap">';
if ($obj->invoiceid) if ($obj->invoiceid) {
{
print '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$obj->invoiceid.'">'.img_object($langs->trans("ShowBill"), 'bill').' '.$obj->ref.'</a>'; print '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$obj->invoiceid.'">'.img_object($langs->trans("ShowBill"), 'bill').' '.$obj->ref.'</a>';
} }
print '</td>'; print '</td>';
print '<td class="right">'.price($obj->amount_ht).'</td>'; print '<td class="right">'.price($obj->amount_ht).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>';
} }
print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>'; print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>';
print '<td class="right">'.price($obj->amount_ttc).'</td>'; print '<td class="right">'.price($obj->amount_ttc).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>';
} }
print '<td class="center">'; print '<td class="center">';
@ -870,7 +818,9 @@ if ($socid > 0)
} }
} else { } else {
$colspan = 8; $colspan = 8;
if (!empty($conf->multicurrency->enabled)) $colspan += 2; if (!empty($conf->multicurrency->enabled)) {
$colspan += 2;
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
} }
@ -928,9 +878,10 @@ if ($socid > 0)
$resql = $db->query($sql); $resql = $db->query($sql);
$resql2 = null; $resql2 = null;
if ($resql) $resql2 = $db->query($sql2); if ($resql) {
if ($resql2) $resql2 = $db->query($sql2);
{ }
if ($resql2) {
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
@ -938,14 +889,12 @@ if ($socid > 0)
print '<td>'.$langs->trans("ReasonDiscount").'</td>'; print '<td>'.$langs->trans("ReasonDiscount").'</td>';
print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>'; print '<td class="nowrap">'.$langs->trans("ConsumedBy").'</td>';
print '<td class="right">'.$langs->trans("AmountHT").'</td>'; print '<td class="right">'.$langs->trans("AmountHT").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountHT").'</td>';
} }
print '<td class="right">'.$langs->trans("VATRate").'</td>'; print '<td class="right">'.$langs->trans("VATRate").'</td>';
print '<td class="right">'.$langs->trans("AmountTTC").'</td>'; print '<td class="right">'.$langs->trans("AmountTTC").'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>'; print '<td class="right">'.$langs->trans("MulticurrencyAmountTTC").'</td>';
} }
print '<td width="100" class="center">'.$langs->trans("Author").'</td>'; print '<td width="100" class="center">'.$langs->trans("Author").'</td>';
@ -955,10 +904,8 @@ if ($socid > 0)
$tab_sqlobj = array(); $tab_sqlobj = array();
$tab_sqlobjOrder = array(); $tab_sqlobjOrder = array();
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num > 0) if ($num > 0) {
{ for ($i = 0; $i < $num; $i++) {
for ($i = 0; $i < $num; $i++)
{
$sqlobj = $db->fetch_object($resql); $sqlobj = $db->fetch_object($resql);
$tab_sqlobj[] = $sqlobj; $tab_sqlobj[] = $sqlobj;
$tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc);
@ -967,8 +914,7 @@ if ($socid > 0)
$db->free($resql); $db->free($resql);
$num = $db->num_rows($resql2); $num = $db->num_rows($resql2);
for ($i = 0; $i < $num; $i++) for ($i = 0; $i < $num; $i++) {
{
$sqlobj = $db->fetch_object($resql2); $sqlobj = $db->fetch_object($resql2);
$tab_sqlobj[] = $sqlobj; $tab_sqlobj[] = $sqlobj;
$tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc);
@ -977,32 +923,27 @@ if ($socid > 0)
array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj); array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj);
$num = count($tab_sqlobj); $num = count($tab_sqlobj);
if ($num > 0) if ($num > 0) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = array_shift($tab_sqlobj); $obj = array_shift($tab_sqlobj);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>'; print '<td>'.dol_print_date($db->jdate($obj->dc), 'dayhour').'</td>';
if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->id = $obj->fk_invoice_supplier_source;
$facturefournstatic->ref = $obj->invoice_source_ref; $facturefournstatic->ref = $obj->invoice_source_ref;
$facturefournstatic->type = $obj->type; $facturefournstatic->type = $obj->type;
print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1); print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->id = $obj->fk_invoice_supplier_source;
$facturefournstatic->ref = $obj->invoice_source_ref; $facturefournstatic->ref = $obj->invoice_source_ref;
$facturefournstatic->type = $obj->type; $facturefournstatic->type = $obj->type;
print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1); print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1);
print '</td>'; print '</td>';
} elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) {
{
print '<td class="minwidth100">'; print '<td class="minwidth100">';
$facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->id = $obj->fk_invoice_supplier_source;
$facturefournstatic->ref = $obj->invoice_source_ref; $facturefournstatic->ref = $obj->invoice_source_ref;
@ -1020,14 +961,12 @@ if ($socid > 0)
} }
print '</td>'; print '</td>';
print '<td class="right">'.price($obj->amount_ht).'</td>'; print '<td class="right">'.price($obj->amount_ht).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ht).'</td>';
} }
print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>'; print '<td class="right">'.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).'</td>';
print '<td class="right">'.price($obj->amount_ttc).'</td>'; print '<td class="right">'.price($obj->amount_ttc).'</td>';
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>'; print '<td class="right">'.price($obj->multicurrency_amount_ttc).'</td>';
} }
print '<td class="center">'; print '<td class="center">';
@ -1039,7 +978,9 @@ if ($socid > 0)
} }
} else { } else {
$colspan = 8; $colspan = 8;
if (!empty($conf->multicurrency->enabled)) $colspan += 2; if (!empty($conf->multicurrency->enabled)) {
$colspan += 2;
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
} }

File diff suppressed because it is too large Load Diff

View File

@ -165,28 +165,37 @@ class Orders extends DolibarrApi
// If the internal user must only see his customers, force searching by him // If the internal user must only see his customers, force searching by him
$search_sale = 0; $search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
$search_sale = DolibarrApiAccess::$user->id;
}
$sql = "SELECT t.rowid"; $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) 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 .= " 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').')'; $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 ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; $sql .= " AND t.fk_soc = sc.fk_soc";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale }
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 // Insert sale filter
if ($search_sale > 0) if ($search_sale > 0) {
{
$sql .= " AND sc.fk_user = ".$search_sale; $sql .= " AND sc.fk_user = ".$search_sale;
} }
// Add sql filters // Add sql filters
if ($sqlfilters) if ($sqlfilters) {
{ if (!DolibarrApi::_checkFilters($sqlfilters)) {
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@ -195,8 +204,7 @@ class Orders extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -207,13 +215,11 @@ class Orders extends DolibarrApi
dol_syslog("API Rest request"); dol_syslog("API Rest request");
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0; $i = 0;
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$commande_static = new Commande($this->db); $commande_static = new Commande($this->db);
if ($commande_static->fetch($obj->rowid)) { if ($commande_static->fetch($obj->rowid)) {
@ -613,18 +619,20 @@ class Orders extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->commande->$field = $value; $this->commande->$field = $value;
} }
// Update availability // Update availability
if (!empty($this->commande->availability_id)) { 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'); throw new RestException(400, 'Error while updating availability');
} }
}
if ($this->commande->update(DolibarrApiAccess::$user) > 0) if ($this->commande->update(DolibarrApiAccess::$user) > 0) {
{
return $this->get($id); return $this->get($id);
} else { } else {
throw new RestException(500, $this->commande->error); throw new RestException(500, $this->commande->error);
@ -979,8 +987,9 @@ class Orders extends DolibarrApi
{ {
$commande = array(); $commande = array();
foreach (Orders::$FIELDS as $field) { foreach (Orders::$FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, $field." field missing"); throw new RestException(400, $field." field missing");
}
$commande[$field] = $data[$field]; $commande[$field] = $data[$field];
} }
return $commande; return $commande;

Some files were not shown because too many files have changed in this diff Show More